Modern Apps git

← Modern-Apps.git

kart: TV racer + generic phone-as-controller SDK

Commit
8a646d5a197345597e239dfd421d4ac74807be4f
Author
vayun-mathur <[email protected]>
When
2026-10-17 19:58 UTC (1 month ago)
Parents
b31d637

Diff

games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex 48589af72a..66622e86c7 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -20,6 +20,7 @@         <package android:name="com.vayunmathur.games.minesweeper" />         <package android:name="com.vayunmathur.games.nonogram" />         <package android:name="com.vayunmathur.games.arrows" />+        <package android:name="com.vayunmathur.games.kart" />         <package android:name="com.vayunmathur.games" />         <intent>             <action android:name="android.intent.action.MAIN" />
games/kart/build.gradle.kts
diff --git a/games/kart/build.gradle.kts b/games/kart/build.gradle.ktsnew file mode 100644index 0000000000..15cd393b44--- /dev/null+++ b/games/kart/build.gradle.kts@@ -0,0 +1,23 @@+plugins {+    id("common-conventions-app")+    // Listing screenshots come from Compose previews (src/screenshotTest), not from an+    // instrumented test on a device. Same `:games:kart:metadata` task name either way.+    id("common-conventions-preview-metadata")+}++launcherIcon {+    symbol = "directions_car"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.games.kart"+    }+}++dependencies {+    implementation(project(":sdk:games"))+    implementation(project(":sdk:controller"))+    implementation(project(":library:work"))+    implementation(libs.androidx.datastore.preferences)+}
games/kart/src/main/AndroidManifest.xml
diff --git a/games/kart/src/main/AndroidManifest.xml b/games/kart/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..35f7b04fca--- /dev/null+++ b/games/kart/src/main/AndroidManifest.xml@@ -0,0 +1,39 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <uses-permission android:name="com.vayunmathur.games.hub.permission.READ_GAME_DATA" />+    <uses-permission android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" />+    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+    <!-- TV lobby: TCP accept + mDNS advertise/register for the phone controllers. -->+    <uses-permission android:name="android.permission.INTERNET" />+    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />+    <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />++    <application+        android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+            <!-- Pairs with openSettingsIfRequested, so App Info's settings cog deep-links there. -->+            <intent-filter>+                <action android:name="android.intent.action.APPLICATION_PREFERENCES" />+                <category android:name="android.intent.category.DEFAULT" />+            </intent-filter>+        </activity>+    </application>++</manifest>
games/kart/src/main/assets/achievements.json
diff --git a/games/kart/src/main/assets/achievements.json b/games/kart/src/main/assets/achievements.jsonnew file mode 100644index 0000000000..cd101beb4c--- /dev/null+++ b/games/kart/src/main/assets/achievements.json@@ -0,0 +1,41 @@+[+  {+    "id": "first_race",+    "name": "Green Light",+    "description": "Finish your first race!"+  },+  {+    "id": "first_win",+    "name": "Photo Finish",+    "description": "Win your first race."+  },+  {+    "id": "first_daily",+    "name": "Daily Habit",+    "description": "Finish a daily event."+  },+  {+    "id": "cups_3",+    "name": "Podium Tour",+    "description": "Clear 3 cups.",+    "targetProgress": 3+  },+  {+    "id": "cups_10",+    "name": "Grand Tour",+    "description": "Clear 10 cups.",+    "targetProgress": 10+  },+  {+    "id": "daily_streak_7",+    "name": "Week Streak",+    "description": "Finish the daily event 7 days in a row.",+    "targetProgress": 7+  },+  {+    "id": "daily_streak_30",+    "name": "Month Streak",+    "description": "Finish the daily event 30 days in a row.",+    "targetProgress": 30+  }+]
games/kart/src/main/java/com/vayunmathur/games/kart/MainActivity.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/MainActivity.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/MainActivity.ktnew file mode 100644index 0000000000..de5ff7bf5d--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/MainActivity.kt@@ -0,0 +1,44 @@+package com.vayunmathur.games.kart++import android.view.KeyEvent+import android.view.MotionEvent+import androidx.compose.runtime.Composable+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.games.kart.platform.GamepadDirect+import com.vayunmathur.games.kart.platform.KartViewModel+import com.vayunmathur.library.ui.MaActivity++class MainActivity : MaActivity() {+    private var gamepad: GamepadDirect? = null++    override fun onCreateBeforeContent() {+        val vm = ViewModelProvider(this)[KartViewModel::class.java]+        gamepad = GamepadDirect(+            context = this,+            onSeat = { playerId, name, present -> vm.onGamepadSeat(playerId, name, present) },+            onInput = { input -> vm.onGamepadInput(input) },+        )+    }++    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean =+        gamepad?.onKeyEvent(event) == true || super.onKeyDown(keyCode, event)++    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean =+        gamepad?.onKeyEvent(event) == true || super.onKeyUp(keyCode, event)++    override fun onGenericMotionEvent(event: MotionEvent): Boolean =+        gamepad?.onGenericMotionEvent(event) == true || super.onGenericMotionEvent(event)++    override fun onDestroy() {+        gamepad?.close()+        gamepad = null+        super.onDestroy()+    }++    @Composable+    override fun Content() {+        val viewModel: KartViewModel = viewModel()+        Navigation(viewModel)+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/Navigation.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/Navigation.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/Navigation.ktnew file mode 100644index 0000000000..7d2e05c875--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/Navigation.kt@@ -0,0 +1,44 @@+package com.vayunmathur.games.kart++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.kart.platform.KartViewModel+import com.vayunmathur.games.kart.ui.KartGamePage+import com.vayunmathur.games.kart.ui.SettingsPage+import com.vayunmathur.library.ui.AchievementNotification+import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.util.GameHubComposeHook+import com.vayunmathur.library.util.FullscreenPage+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.openSettingsIfRequested+import com.vayunmathur.library.util.rememberNavBackStack++@Composable+fun Navigation(viewModel: KartViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Game)+    // Launching from App Info's settings cog deep-links straight to Settings.+    backStack.openSettingsIfRequested(Route.Settings)+    val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+    GameHubComposeHook("kart", viewModel.achievementsManager)+    Box(Modifier.fillMaxSize()) {+        MainNavigation(backStack) {+            entry<Route.Game>(metadata = FullscreenPage()) { KartGamePage(backStack, viewModel) }+            entry<Route.GameCenter> {+                GameCenterScreen(+                    manager = viewModel.achievementsManager,+                    onBack = { backStack.pop() },+                )+            }+            entry<Route.Settings> {+                SettingsPage(viewModel = viewModel, onBack = { backStack.pop() })+            }+        }+        newAchievement?.let {+            AchievementNotification(it) { viewModel.dismissAchievementNotification() }+        }+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/Route.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/Route.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/Route.ktnew file mode 100644index 0000000000..72a44fe24b--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/Route.kt@@ -0,0 +1,17 @@+package com.vayunmathur.games.kart++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+    /** The garage screen: which karts/tracks are unlocked and what the next race looks like. */+    @Serializable+    data object Game : Route++    @Serializable+    data object GameCenter : Route++    @Serializable+    data object Settings : Route+}
games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.ktnew file mode 100644index 0000000000..412559972f--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt@@ -0,0 +1,86 @@+package com.vayunmathur.games.kart.data++import android.content.Context+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.intPreferencesKey+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.map++private val Context.dataStore by preferencesDataStore(name = "settings")++/**+ * Everything the game remembers.+ *+ * Casual progress is a single cup number plus lifetime counters; advancing clears nothing, it+ * just moves the pointer. Daily progress is stamped with the day it belongs to, so yesterday's+ * result can never bleed into today's.+ */+class KartDataStore(private val context: Context) {++    val currentCup: Flow<Int> = context.dataStore.data.map { it[CUP_KEY] ?: 0 }++    /** Lifetime count of cleared cups, which survives [saveCup] moving the pointer on. */+    val cupsCleared: Flow<Int> = context.dataStore.data.map { it[CLEARED_KEY] ?: 0 }++    /** Lifetime race wins, counted by the race flow once it exists. */+    val racesWon: Flow<Int> = context.dataStore.data.map { it[RACES_WON_KEY] ?: 0 }++    /** Best lap in milliseconds; zero means no lap has been timed yet. */+    val bestLapMs: Flow<Long> = context.dataStore.data.map { it[BEST_LAP_KEY] ?: 0L }++    val gameMode: Flow<GameMode> = context.dataStore.data.map { prefs ->+        prefs[GAME_MODE_KEY]?.let { runCatching { GameMode.valueOf(it) }.getOrNull() }+            ?: GameMode.CASUAL+    }++    // ---- Daily ----++    val dailyDay: Flow<Long> = context.dataStore.data.map { it[DAILY_DAY_KEY] ?: NO_DAY }++    suspend fun setGameMode(mode: GameMode) {+        context.dataStore.edit { it[GAME_MODE_KEY] = mode.name }+    }++    /** Moves to [cup] without touching the lifetime counters. */+    suspend fun saveCup(cup: Int) {+        context.dataStore.edit { prefs -> prefs[CUP_KEY] = cup }+    }++    /** Bumps and returns the lifetime cleared count. */+    suspend fun recordCleared(): Int {+        var total = 0+        context.dataStore.edit { prefs ->+            total = (prefs[CLEARED_KEY] ?: 0) + 1+            prefs[CLEARED_KEY] = total+        }+        return total+    }++    /**+     * Rolls the daily board over to [day] if it is not already there.+     *+     * The early return keeps re-entering daily mode from wiping work in progress.+     */+    suspend fun ensureDailyDay(day: Long) {+        context.dataStore.edit { prefs ->+            if (prefs[DAILY_DAY_KEY] == day) return@edit+            prefs[DAILY_DAY_KEY] = day+        }+    }++    private companion object {+        val CUP_KEY = intPreferencesKey("current_cup")+        val CLEARED_KEY = intPreferencesKey("cups_cleared")+        val RACES_WON_KEY = intPreferencesKey("races_won")+        val BEST_LAP_KEY = longPreferencesKey("best_lap_ms")+        val GAME_MODE_KEY = stringPreferencesKey("game_mode")++        val DAILY_DAY_KEY = longPreferencesKey("daily_day")++        /** Sentinel for "no daily played yet"; distinct from epoch day 0, which is a real date. */+        const val NO_DAY = Long.MIN_VALUE+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/data/KartModels.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartModels.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartModels.ktnew file mode 100644index 0000000000..86b13e4bd2--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartModels.kt@@ -0,0 +1,41 @@+package com.vayunmathur.games.kart.data++import kotlinx.serialization.Serializable++/** Which garage the player is looking at. Mirrors the arrows split: a ladder, plus one a day. */+@Serializable+enum class GameMode { CASUAL, DAILY }++/**+ * A single grand-prix event.+ *+ * The scaffold ships no tracks yet: the cup is a named slot the race flow will fill in once the+ * engine lands. Keeping the model in place now means the GameCenter progress lines already have+ * something to count.+ */+data class KartCup(+    val id: Int,+    val name: String,+    val trackCount: Int,+)++/** The three cups the full game will ship. Placeholder names until tracks are modelled. */+val CUPS = listOf(+    KartCup(id = 0, name = "Mushroom Cup", trackCount = 4),+    KartCup(id = 1, name = "Flower Cup", trackCount = 4),+    KartCup(id = 2, name = "Star Cup", trackCount = 4),+)++/**+ * Where the player stands.+ *+ * [cupsCleared] is the lifetime count the achievements count against; [bestLapMs] and+ * [racesWon] feed the GameCenter rows once races exist. All three start empty: nothing here+ * pretends a race has happened.+ */+data class KartProgress(+    val currentCup: Int = 0,+    val cupsCleared: Int = 0,+    val racesWon: Int = 0,+    val bestLapMs: Long = 0L,+)
games/kart/src/main/java/com/vayunmathur/games/kart/domain/GameInputLoop.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/GameInputLoop.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/GameInputLoop.ktnew file mode 100644index 0000000000..8e62863d56--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/GameInputLoop.kt@@ -0,0 +1,89 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.sdk.controller.AXIS_BRAKE+import com.vayunmathur.sdk.controller.AXIS_LEFT_X+import com.vayunmathur.sdk.controller.AXIS_LEFT_Y+import com.vayunmathur.sdk.controller.AXIS_THROTTLE+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput++/**+ * One tick of kart control, normalized and game-ready.+ *+ * [throttle] 0..1 forward, [brake] 0..1, [steering] -1..1 (left negative), [drift] held,+ * [itemUse] edge-triggered by the game (the loop sets it from the button state; the game consumes+ * and clears it, so holding the button does not fire twice).+ */+data class KartControl(+    val throttle: Float = 0f,+    val steering: Float = 0f,+    val brake: Float = 0f,+    val drift: Boolean = false,+    val itemUse: Boolean = false,+) {+    companion object {+        val NEUTRAL = KartControl()+    }+}++/**+ * The fan-in: network phones and local gamepads arrive as generic [ControllerInput] and leave as+ * one [KartControl] per player per tick.+ *+ * Deadzones and the cubic curve match the voxels `Joystick` feel (0.15 deadzone, then+ * `0.2a + 0.8a³`), so a phone stick and a TV gamepad with the same deflection drive the same line.+ * The game reads the output on its own tick; samples are idempotent snapshots, so a missed frame+ * costs one tick of staleness and repairs itself.+ */+object GameInputLoop {++    /** Stick deflection below this is rest, not input. Matches the voxels move stick. */+    const val DEADZONE = 0.15f++    /**+     * Merge one sample into kart control.+     *+     * Steering comes from the left stick X; throttle prefers the right trigger axis, then the left+     * stick Y pushed up; brake prefers the left trigger axis, then stick Y pulled down. Trigger+     * axes are 0..1 pressed amounts (a centered stick leaves them at 0 = unpressed; gamepads that+     * report -1..1 normalize at their own layer). Drift is the right shoulder; item is A. D-pad+     * left/right nudge the steering when the stick is at rest, so a D-pad-only pad can corner.+     */+    fun normalize(input: ControllerInput): KartControl {+        val axes = input.axes+        val stickX = axes.getOrElse(AXIS_LEFT_X) { 0f }+        val stickY = axes.getOrElse(AXIS_LEFT_Y) { 0f }+        val throttleAxis = axes.getOrElse(AXIS_THROTTLE) { 0f }+        val brakeAxis = axes.getOrElse(AXIS_BRAKE) { 0f }++        var steering = curve(stickX)+        if (steering == 0f) {+            if (input.isPressed(ControllerButton.DPAD_LEFT)) steering = -0.6f+            if (input.isPressed(ControllerButton.DPAD_RIGHT)) steering = 0.6f+        }+        val throttle = maxOf(curve(throttleAxis.coerceIn(0f, 1f)), curve(-stickY))+        val brake = maxOf(curve(brakeAxis.coerceIn(0f, 1f)), curve(stickY))++        return KartControl(+            throttle = throttle.coerceIn(0f, 1f),+            steering = steering.coerceIn(-1f, 1f),+            brake = brake.coerceIn(0f, 1f),+            drift = input.isPressed(ControllerButton.RIGHT_SHOULDER) ||+                input.isPressed(ControllerButton.LEFT_SHOULDER),+            itemUse = input.isPressed(ControllerButton.A),+        )+    }++    /**+     * The voxels stick curve: deadzone, then `0.2a + 0.8a³` for fine control near center and full+     * throw at the edge.+     */+    fun curve(v: Float): Float {+        val a = kotlin.math.abs(v)+        if (a < DEADZONE) return 0f+        // Rescale so the curve starts at zero at the deadzone edge rather than jumping.+        val t = ((a - DEADZONE) / (1f - DEADZONE)).coerceIn(0f, 1f)+        val shaped = 0.2f * t + 0.8f * t * t * t+        return if (v < 0f) -shaped else shaped+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.ktnew file mode 100644index 0000000000..cce664ddf2--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt@@ -0,0 +1,23 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.games.kart.data.CUPS++/**+ * The garage rules, as pure functions on progress counters.+ *+ * There is no race engine yet, so this is deliberately thin: it decides which cup is on screen+ * and whether a cup index is playable. Physics, items and AI will grow their own files beside+ * this one rather than bloating it.+ */+object KartRules {++    /** The cup on screen for [cupIndex], wrapping past the end of the list. */+    fun cupAt(cupIndex: Int) = CUPS[cupIndex.mod(CUPS.size)]++    /** Whether [cupIndex] names a real cup rather than a pointer past the end. */+    fun isUnlocked(cupIndex: Int, cupsCleared: Int): Boolean = cupIndex <= cupsCleared++    /** The next cup after [cupIndex], or null once the last cup is cleared. */+    fun nextCup(cupIndex: Int): Int? =+        if (cupIndex + 1 < CUPS.size) cupIndex + 1 else null+}
games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.ktnew file mode 100644index 0000000000..ded8dcf374--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt@@ -0,0 +1,121 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.games.kart.data.CUPS++/**+ * The placeholder race: a software top-down model that unblocks lobby → race → results before the+ * native 3D engine lands.+ *+ * One lap is [TRACK_LENGTH] units; karts advance by throttle × [TOP_SPEED] per second, minus a+ * steering scrub. Positions are fractional progress in laps; [leaderboard] sorts by total progress.+ * AI drivers hold a fixed pace with a wobble so they are beatable but not statues.+ *+ * Everything here is pure and timestepped ([tick] takes seconds), so the race is a JVM test and+ * the native engine only has to reproduce its shape, not its code.+ */+class PlaceholderRace(+    val playerIds: List<String>,+    val laps: Int = 3,+    private val aiCount: Int = 3,+) {+    companion object {+        /** Units per lap. Arbitrary: only ratios matter until the 3D track defines meters. */+        const val TRACK_LENGTH = 1000f++        /** Units per second at full throttle. A lap takes ~25 s flat out. */+        const val TOP_SPEED = 40f++        /**+         * Fraction of speed kept while drifting through full lock.+         *+         * Above the 0.82 a plain full-lock corner keeps: drift trades grip for keeping boost+         * charge, not for raw pace. Anything at or below that would make drifting the fast way+         * through every corner with no decision in it.+         */+        const val DRIFT_KEEP = 0.88f++        /** AI pace as a fraction of top speed, before the per-driver wobble. */+        const val AI_PACE = 0.78f+    }++    private data class Kart(+        val id: String,+        val ai: Boolean,+        var progress: Float = 0f,+        var wobble: Float = 0f,+    )++    private val karts = (playerIds.map { Kart(it, ai = false) } ++        List(aiCount) { i -> Kart("ai-$i", ai = true, wobble = 0.92f + 0.04f * i) })+        .toMutableList()++    private val controls = mutableMapOf<String, KartControl>()++    /** Last tick's item-button state per player: the rising-edge latch for [useItem]. */+    private val itemLatch = mutableMapOf<String, Boolean>()++    val finished: Boolean get() = karts.any { lapOf(it) >= laps }++    /** Completed laps for [kart]. */+    fun lapOf(id: String): Int = karts.firstOrNull { it.id == id }?.let { lapOf(it) } ?: 0++    private fun lapOf(kart: Kart): Int = (kart.progress / TRACK_LENGTH).toInt()++    /** 0..1 through the current lap, for the progress bar. */+    fun lapProgress(id: String): Float {+        val kart = karts.firstOrNull { it.id == id } ?: return 0f+        return ((kart.progress % TRACK_LENGTH) / TRACK_LENGTH).coerceIn(0f, 1f)+    }++    /** Player ids first, then AI, each by total progress descending. */+    fun leaderboard(): List<String> = karts.sortedByDescending { it.progress }.map { it.id }++    /** The winner: first across the line once [finished]. */+    fun winner(): String? =+        if (finished) karts.maxByOrNull { it.progress }?.id else null++    fun setControl(playerId: String, control: KartControl) {+        controls[playerId] = control+    }++    /**+     * Fire the held item for [playerId]. True only on the rising edge.+     *+     * The loop sets `itemUse` from the button state every tick, so a held button reads true on+     * consecutive ticks; the latch remembers the last tick and fires once, so holding the button+     * does not fire twice. No items are modelled yet — firing spends nothing — but the edge+     * discipline is what the engine will build on.+     */+    fun useItem(playerId: String): Boolean {+        val held = controls[playerId]?.itemUse == true+        val was = itemLatch[playerId] ?: false+        itemLatch[playerId] = held+        return held && !was+    }++    /**+     * Advance the race by [dtSeconds].+     *+     * Steering scrubs speed (full lock costs ~18%, less while drifting); AI runs its pace ×+     * wobble. Progress never goes backwards: braking to a standstill holds position.+     */+    fun tick(dtSeconds: Float) {+        val dt = dtSeconds.coerceIn(0f, 1f)+        for (kart in karts) {+            if (lapOf(kart) >= laps) continue+            val speed = if (kart.ai) {+                TOP_SPEED * AI_PACE * kart.wobble+            } else {+                val control = controls[kart.id] ?: KartControl.NEUTRAL+                val scrub = 1f - kotlin.math.abs(control.steering) *+                    (if (control.drift) 1f - DRIFT_KEEP else 0.18f)+                TOP_SPEED * control.throttle * scrub -+                    TOP_SPEED * 0.5f * control.brake+            }+            kart.progress = (kart.progress + speed * dt).coerceAtLeast(0f)+        }+    }++    /** Which cup this race counts for, so results can bank progress. */+    fun cupIndex(cup: Int): Int = cup.mod(CUPS.size)+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/AppBackupAgent.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/AppBackupAgent.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..edc4bc195e--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/AppBackupAgent.kt@@ -0,0 +1,12 @@+package com.vayunmathur.games.kart.platform++import com.vayunmathur.library.util.BaseBackupAgent++class AppBackupAgent : BaseBackupAgent() {+    /**+     * Both files, or a restore silently wipes half the player's history: "settings" holds the cup+     * pointer and the lifetime counters, while the shared DataStoreUtils file holds the daily streak+     * and the achievement unlocks.+     */+    override val datastoreNames: List<String> get() = listOf("settings", "datastore_default")+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/GamepadDirect.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/GamepadDirect.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/GamepadDirect.ktnew file mode 100644index 0000000000..5dac97322f--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/GamepadDirect.kt@@ -0,0 +1,251 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import android.hardware.input.InputManager+import android.os.SystemClock+import android.view.InputDevice+import android.view.KeyEvent+import android.view.MotionEvent+import com.vayunmathur.library.log.Log+import com.vayunmathur.sdk.controller.AXIS_BRAKE+import com.vayunmathur.sdk.controller.AXIS_COUNT+import com.vayunmathur.sdk.controller.AXIS_LEFT_X+import com.vayunmathur.sdk.controller.AXIS_LEFT_Y+import com.vayunmathur.sdk.controller.AXIS_RIGHT_X+import com.vayunmathur.sdk.controller.AXIS_RIGHT_Y+import com.vayunmathur.sdk.controller.AXIS_THROTTLE+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput++private const val TAG = "GamepadDirect"++/** Axis deflection past this counts as a hat direction, for pads exposing the D-pad as axes. */+private const val HAT_THRESHOLD = 0.5f++/**+ * Physical gamepads plugged into the TV: enumeration, buttons, sticks, hot-plug.+ *+ * Each pad takes a seat through the same [ControllerHost] local-player path the phones use, so+ * downstream everything is indistinguishable: the race loop reads `host.inputs` and `host.lobby`+ * and never learns which seats are network and which are USB/Bluetooth. A pad plugged in+ * mid-race joins the lobby at once and drives from the next race; the running snapshot is fixed+ * at countdown end, so it never reshuffles under a live tick.+ *+ * Kept separate from the media-key dispatch path on purpose: this only ever consumes events from+ * devices it has seated, and only gamepad buttons/axes at that. Volume, navigation and media+ * keys fall through to the system untouched.+ */+class GamepadDirect(+    context: Context,+    private val onSeat: (playerId: String, name: String, present: Boolean) -> Unit,+    private val onInput: (ControllerInput) -> Unit,+) {++    private val inputManager: InputManager? =+        context.applicationContext.getSystemService(InputManager::class.java)++    private val lock = Any()+    /** deviceId → seat, so a disconnect frees exactly the seat its connect took. */+    private val seats = mutableMapOf<Int, String>()+    private val buttons = mutableMapOf<Int, Long>()+    private val axesCache = mutableMapOf<Int, FloatArray>()+    private val seqs = mutableMapOf<Int, Long>()++    /** Seats currently held by pads, for the race to snapshot at countdown end. */+    val playerIds: Set<String> get() = synchronized(lock) { seats.values.toSet() }++    private val deviceListener = object : InputManager.InputDeviceListener {+        override fun onInputDeviceAdded(deviceId: Int) {+            addDevice(deviceId)+        }++        override fun onInputDeviceRemoved(deviceId: Int) {+            removeDevice(deviceId)+        }++        override fun onInputDeviceChanged(deviceId: Int) {+            val device = InputDevice.getDevice(deviceId)+            if (device == null || !isGamepad(device)) removeDevice(deviceId)+            else addDevice(deviceId)+        }+    }++    init {+        InputDevice.getDeviceIds().forEach { addDevice(it) }+        inputManager?.registerInputDeviceListener(deviceListener, null)+        if (inputManager == null) Log.status(TAG, "no InputManager - gamepads will not be seen")+    }++    fun close() {+        inputManager?.unregisterInputDeviceListener(deviceListener)+        synchronized(lock) { seats.keys.toList() }.forEach { removeDevice(it) }+    }++    /**+     * Feed a key event from the activity. True when a seated pad owned it.+     *+     * A press from an unknown device with a gamepad source seats it first, so a pad plugged in+     * between the listener firing and the first press still drives rather than dropping its first+     * input.+     */+    fun onKeyEvent(event: KeyEvent): Boolean {+        val bit = keyCodeToBit(event.keyCode) ?: return false+        var playerId = synchronized(lock) { seats[event.deviceId] }+        if (playerId == null) {+            val device = InputDevice.getDevice(event.deviceId)+            if (device == null || !isGamepad(device)) return false+            playerId = addDevice(event.deviceId) ?: return false+        }+        if (event.repeatCount > 0) return true+        val deviceId = event.deviceId+        when (event.action) {+            KeyEvent.ACTION_DOWN -> synchronized(lock) {+                buttons[deviceId] = (buttons[deviceId] ?: 0L) or bit+            }+            KeyEvent.ACTION_UP -> synchronized(lock) {+                buttons[deviceId] = (buttons[deviceId] ?: 0L) and bit.inv()+            }+            else -> return false+        }+        emit(deviceId, playerId)+        return true+    }++    /**+     * Feed a motion event from the activity. True when a seated pad owned it.+     *+     * Sticks arrive here; buttons ride along from the state the key path maintains, so a sample+     * always carries the whole pad, never half of it.+     */+    fun onGenericMotionEvent(event: MotionEvent): Boolean {+        if ((event.source and InputDevice.SOURCE_CLASS_JOYSTICK) == 0) return false+        var playerId = synchronized(lock) { seats[event.deviceId] }+        if (playerId == null) {+            val device = InputDevice.getDevice(event.deviceId)+            if (device == null || !isGamepad(device)) return false+            playerId = addDevice(event.deviceId) ?: return false+        }+        val device = InputDevice.getDevice(event.deviceId)+        val ranges: (Int) -> Float = { axis ->+            device?.getMotionRange(axis)?.let { range ->+                event.getAxisValue(axis).zeroWithin(range.flat)+            } ?: 0f+        }+        synchronized(lock) {+            axesCache[event.deviceId] = floatArrayOf(+                ranges(MotionEvent.AXIS_X),+                ranges(MotionEvent.AXIS_Y),+                ranges(MotionEvent.AXIS_Z),+                ranges(MotionEvent.AXIS_RZ),+                ranges(MotionEvent.AXIS_RTRIGGER),+                ranges(MotionEvent.AXIS_LTRIGGER),+            )+        }+        emit(event.deviceId, playerId)+        return true+    }++    private fun emit(deviceId: Int, playerId: String) {+        val (pressed, axes) = synchronized(lock) {+            (buttons[deviceId] ?: 0L) to+                (axesCache[deviceId]?.copyOf() ?: FloatArray(AXIS_COUNT))+        }+        val seq = synchronized(lock) {+            val next = (seqs[deviceId] ?: 0L) + 1+            seqs[deviceId] = next+            next+        }+        onInput(+            ControllerInput(+                playerId = playerId,+                seq = seq,+                buttons = pressed,+                axes = axes.toList(),+                hatX = hatOf(axes[AXIS_LEFT_X], pressed, ControllerButton.DPAD_LEFT, ControllerButton.DPAD_RIGHT),+                hatY = hatOf(axes[AXIS_LEFT_Y], pressed, ControllerButton.DPAD_UP, ControllerButton.DPAD_DOWN),+                clientTimestampMs = SystemClock.uptimeMillis(),+            ),+        )+    }++    private fun hatOf(+        axis: Float,+        pressed: Long,+        negative: ControllerButton,+        positive: ControllerButton,+    ): Int = when {+        pressed and negative.bit != 0L || axis < -HAT_THRESHOLD -> -1+        pressed and positive.bit != 0L || axis > HAT_THRESHOLD -> 1+        else -> 0+    }++    private fun addDevice(deviceId: Int): String? {+        val device = InputDevice.getDevice(deviceId) ?: return null+        if (!isGamepad(device)) return null+        synchronized(lock) {+            seats[deviceId]?.let { return it }+            val playerId = "pad-$deviceId"+            seats[deviceId] = playerId+            Log.status(TAG, "seated ${device.name} as $playerId")+            onSeat(playerId, device.name, true)+            return playerId+        }+    }++    private fun removeDevice(deviceId: Int) {+        val playerId = synchronized(lock) {+            buttons.remove(deviceId)+            axesCache.remove(deviceId)+            seqs.remove(deviceId)+            seats.remove(deviceId)+        } ?: return+        Log.status(TAG, "freed seat $playerId")+        onSeat(playerId, "", false)+    }++    companion object {+        /**+         * True for gamepads and joysticks only: keyboards, mice and remotes never take a seat, so+         * their keys always fall through to the system.+         */+        fun isGamepad(device: InputDevice): Boolean =+            (device.sources and (InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK)) != 0++        /** A hardware value inside the device's own noise floor is rest, not input. */+        fun Float.zeroWithin(flat: Float): Float =+            if (kotlin.math.abs(this) <= flat) 0f else this++        /** `KeyEvent` buttons onto the same bitmask the phones send. */+        fun keyCodeToBit(keyCode: Int): Long? = when (keyCode) {+            KeyEvent.KEYCODE_BUTTON_A -> ControllerButton.A.bit+            KeyEvent.KEYCODE_BUTTON_B -> ControllerButton.B.bit+            KeyEvent.KEYCODE_BUTTON_X -> ControllerButton.X.bit+            KeyEvent.KEYCODE_BUTTON_Y -> ControllerButton.Y.bit+            KeyEvent.KEYCODE_BUTTON_L1 -> ControllerButton.LEFT_SHOULDER.bit+            KeyEvent.KEYCODE_BUTTON_R1 -> ControllerButton.RIGHT_SHOULDER.bit+            KeyEvent.KEYCODE_BUTTON_L2 -> ControllerButton.LEFT_TRIGGER.bit+            KeyEvent.KEYCODE_BUTTON_R2 -> ControllerButton.RIGHT_TRIGGER.bit+            KeyEvent.KEYCODE_BUTTON_START -> ControllerButton.START.bit+            KeyEvent.KEYCODE_BUTTON_SELECT -> ControllerButton.SELECT.bit+            KeyEvent.KEYCODE_BUTTON_THUMBL -> ControllerButton.LEFT_STICK.bit+            KeyEvent.KEYCODE_BUTTON_THUMBR -> ControllerButton.RIGHT_STICK.bit+            KeyEvent.KEYCODE_DPAD_UP -> ControllerButton.DPAD_UP.bit+            KeyEvent.KEYCODE_DPAD_DOWN -> ControllerButton.DPAD_DOWN.bit+            KeyEvent.KEYCODE_DPAD_LEFT -> ControllerButton.DPAD_LEFT.bit+            KeyEvent.KEYCODE_DPAD_RIGHT -> ControllerButton.DPAD_RIGHT.bit+            else -> null+        }++        /** Axis slots in [ControllerInput.axes], mirroring the SDK's fixed order. */+        @Suppress("unused")+        fun axisSlotFor(motionAxis: Int): Int? = when (motionAxis) {+            MotionEvent.AXIS_X -> AXIS_LEFT_X+            MotionEvent.AXIS_Y -> AXIS_LEFT_Y+            MotionEvent.AXIS_Z -> AXIS_RIGHT_X+            MotionEvent.AXIS_RZ -> AXIS_RIGHT_Y+            MotionEvent.AXIS_RTRIGGER -> AXIS_THROTTLE+            MotionEvent.AXIS_LTRIGGER -> AXIS_BRAKE+            else -> null+        }+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartAchievementsManager.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartAchievementsManager.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartAchievementsManager.ktnew file mode 100644index 0000000000..fc86bcf522--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartAchievementsManager.kt@@ -0,0 +1,39 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import com.vayunmathur.games.kart.data.KartDataStore+import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.DailyChallengeStore+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch++class KartAchievementsManager(+    context: Context,+    json: String,+    private val dataStore: KartDataStore,+    private val dailyStore: DailyChallengeStore,+) : AchievementsManager(context, json) {++    /**+     * Back-fills from stored progress on launch, so an achievement added in a later release is awarded+     * for work the player has already done rather than only for the next race they finish.+     *+     * The reads are suspending, so this hands off to a coroutine rather than blocking.+     */+    override fun checkExistingAchievements() {+        CoroutineScope(Dispatchers.IO).launch {+            val total = dataStore.cupsCleared.first()+            if (total > 0) onAchievementUnlocked("first_race")+            onProgressUpdated("cups_3", total)++            if (dailyStore.lastCompletedDay() != DailyChallengeStore.NO_DAY) {+                onAchievementUnlocked("first_daily")+            }+            val best = dailyStore.bestStreak().toInt()+            onProgressUpdated("daily_streak_7", best)+            onProgressUpdated("daily_streak_30", best)+        }+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.ktnew file mode 100644index 0000000000..0b3532bcfe--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt@@ -0,0 +1,122 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import android.content.SharedPreferences+import android.util.Base64+import androidx.core.content.edit+import com.vayunmathur.library.log.Log+import com.vayunmathur.sdk.controller.ControllerAdvertiser+import com.vayunmathur.sdk.controller.ControllerHost+import com.vayunmathur.sdk.controller.ControllerInput+import com.vayunmathur.sdk.controller.ControllerSocket+import com.vayunmathur.sdk.controller.LobbyState+import java.net.ServerSocket+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch++private const val TAG = "KartHost"+private const val PREFS = "kart_host"+private const val KEY_HOST_ID = "host_id"++/**+ * The TV-side lobby owner: advertises `_gamepad._tcp`, accepts phones, and exposes the+ * [ControllerHost] fan-in the race loop reads.+ *+ * Key material is injectable: [publicBundle] is the ML-KEM+ML-DSA bundle from `:library:e2ee-p2p`+ * (`PqcIdentity.publicBundle`), [unsealSecret] opens a sealed session secret with the KEM private+ * half. Device keys persist in private prefs keyed by phone id. The host id is a stable UUID minted+ * once, so re-pairing survives restarts.+ *+ * PQC stays behind the lambdas deliberately: this module never touches the native library+ * directly, and tests construct a `KartHost` with fake keys.+ */+class KartHost(+    private val context: Context,+    private val publicBundle: () -> ByteArray?,+    private val unsealSecret: (ByteArray) -> ByteArray?,+) {+    private val prefs: SharedPreferences =+        context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++    private val hostId: String = prefs.getString(KEY_HOST_ID, null) ?: run {+        val fresh = java.util.UUID.randomUUID().toString()+        prefs.edit { putString(KEY_HOST_ID, fresh) }+        fresh+    }++    val host = ControllerHost(+        gameId = "kart",+        hostId = hostId,+        providePublicBundle = publicBundle,+        unsealSecret = unsealSecret,+        loadDeviceKey = ::loadDeviceKey,+        saveDeviceKey = ::saveDeviceKey,+    )++    val lobby: StateFlow<LobbyState> = host.lobby+    val inputs: StateFlow<Map<String, ControllerInput>> = host.inputs++    private val advertiser = ControllerAdvertiser(context)+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+    private var server: ServerSocket? = null++    /** The pair code on screen, if a phone is mid-handshake. */+    val pairingCode: String? get() = host.pairingCode++    /**+     * Start advertising and accepting. Safe to call repeatedly; restarts the accept loop rather+     * than stacking a second one.+     */+    fun start() {+        scope.launch { acceptLoop() }+    }++    fun stop() {+        runCatching { server?.close() }+        server = null+        advertiser.unadvertise()+        host.close()+        scope.cancel()+    }++    private fun acceptLoop() {+        val server = try {+            ServerSocket(0).also { this.server = it }+        } catch (e: Exception) {+            Log.status(TAG, "cannot bind a lobby port", e)+            return+        }+        advertiser.advertise(+            friendlyName = android.os.Build.MODEL ?: "TV",+            deviceId = hostId,+            port = server.localPort,+            gameId = "kart",+        )+        Log.status(TAG, "lobby open on port ${server.localPort}")+        while (true) {+            val accepted = try {+                server.accept()+            } catch (_: Exception) {+                return+            }+            val socket = ControllerSocket()+            socket.attach(accepted)+            host.accept(socket)+        }+    }++    private fun loadDeviceKey(senderId: String): ByteArray? =+        prefs.getString(deviceKeyOf(senderId), null)?.let {+            runCatching { Base64.decode(it, Base64.NO_WRAP) }.getOrNull()+        }++    private fun saveDeviceKey(senderId: String, key: ByteArray) {+        prefs.edit { putString(deviceKeyOf(senderId), Base64.encodeToString(key, Base64.NO_WRAP)) }+    }++    private fun deviceKeyOf(senderId: String): String = "device_$senderId"+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.ktnew file mode 100644index 0000000000..ba52e12df4--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartNative.kt@@ -0,0 +1,51 @@+// PACKAGE STRUCTURE EXCEPTION (JNI): FQN frozen for native RegisterNatives/symbol mangling+// NOTE: file lives under platform/ but package is ...kart.util to match the native symbol+@file:Suppress("InvalidPackageDeclaration")+package com.vayunmathur.games.kart.util++import com.vayunmathur.library.log.Log++/**+ * The engine bridge, shaped like `VoxelsNative.onMoveInput`.+ *+ * Today there is no native library: every call is a no-op behind [isAvailable] = false, and the+ * game runs on [com.vayunmathur.games.kart.domain.PlaceholderRace] instead. The signatures below+ * are the contract the Rust engine will implement in Phase 4b, so the Kotlin side never changes+ * shape when native lands - only this object's body does.+ */+@Suppress("TooManyFunctions")+object KartNative {+    /** False until `libkart_engine` ships. The game checks this once per surface, like voxels. */+    val isAvailable: Boolean = try {+        System.loadLibrary("kart_engine")+        Log.status("KartNative", "libkart_engine loaded")+        true+    } catch (t: Throwable) {+        Log.status("KartNative", "libkart_engine absent - running the placeholder race")+        false+    }++    /** One player's control for this tick: throttle/steering/brake normalized, drift/item edges. */+    fun onDriveInput(player: Int, throttle: Float, steering: Float, brake: Float) {+        if (!isAvailable) return+        nativeOnDriveInput(player, throttle, steering, brake)+    }++    fun setDrift(player: Int, held: Boolean) {+        if (!isAvailable) return+        nativeSetDrift(player, held)+    }++    fun useItem(player: Int) {+        if (!isAvailable) return+        nativeUseItem(player)+    }++    /** Snapshot for the HUD/standings: JSON `[{player,lap,progress,place}]`. */+    fun getStandingsJson(): String = if (isAvailable) nativeGetStandingsJson() else "[]"++    private external fun nativeOnDriveInput(player: Int, throttle: Float, steering: Float, brake: Float)+    private external fun nativeSetDrift(player: Int, held: Boolean)+    private external fun nativeUseItem(player: Int)+    private external fun nativeGetStandingsJson(): String+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.ktnew file mode 100644index 0000000000..da2641c55e--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt@@ -0,0 +1,51 @@+package com.vayunmathur.games.kart.platform++import com.vayunmathur.games.kart.data.GameMode+import com.vayunmathur.games.kart.data.KartCup+import com.vayunmathur.games.kart.data.KartProgress++/**+ * The UI contract between [KartViewModel] and the garage screen.+ *+ * The screen takes this interface rather than the ViewModel itself so it can be rendered by a+ * `@Preview` — which is what the store listing images are generated from. It lives in `platform`+ * rather than next to the screen so the dependency runs one way: `ui` depends on `platform`, and+ * the ViewModel implements this.+ *+ * Every member has a no-op default, so `Noop` is the whole implementation a preview needs.+ */+interface KartGameActions {+    /** Starts the lobby countdown; the tick loop banks the cup clear when the race finishes. */+    fun startRace() {}++    fun nextCup() {}+    fun setGameMode(mode: GameMode) {}++    /** Back to the lobby from the results screen. */+    fun backToLobby() {}++    companion object { val Noop: KartGameActions = object : KartGameActions {} }+}++/** What the garage screen needs to draw itself. */+data class KartUiState(+    val cup: KartCup? = null,+    val progress: KartProgress = KartProgress(),+    val mode: GameMode = GameMode.CASUAL,+    val dailyStreak: Long = 0,+    /** True once today's daily has been cleared, which swaps the race button for a note. */+    val dailyDone: Boolean = false,+)++interface SettingsActions {+    fun setReminderEnabled(enabled: Boolean) {}+    fun setReminderTime(hour: Int, minute: Int) {}++    companion object { val Noop: SettingsActions = object : SettingsActions {} }+}++data class SettingsUiState(+    val reminderEnabled: Boolean = false,+    val reminderHour: Int = 20,+    val reminderMinute: Int = 0,+)
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.ktnew file mode 100644index 0000000000..6dd800c483--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt@@ -0,0 +1,363 @@+package com.vayunmathur.games.kart.platform++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.kart.data.GameMode+import com.vayunmathur.games.kart.data.KartDataStore+import com.vayunmathur.games.kart.data.KartProgress+import com.vayunmathur.games.kart.domain.GameInputLoop+import com.vayunmathur.games.kart.domain.KartRules+import com.vayunmathur.games.kart.domain.PlaceholderRace+import com.vayunmathur.games.kart.util.KartNative+import com.vayunmathur.library.util.AchievementsManager+import com.vayunmathur.library.util.DailyChallengeStore+import com.vayunmathur.library.util.DailyStreakReporter+import com.vayunmathur.library.work.DailyPuzzleReminder+import com.vayunmathur.library.work.DailyReminderSettings+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch++/**+ * Owns the garage screen and the progress behind it.+ *+ * Casual mode is a single cup pointer: advancing writes `cup + 1` and leaves the lifetime+ * counters alone, so there is no cup list and no way back. Daily mode is one event per calendar+ * day, with its progress stamped with the day it belongs to.+ */+class KartViewModel(application: Application) : AndroidViewModel(application),+    KartGameActions, SettingsActions {++    val dataStore = KartDataStore(application)+    private val dailyStore = DailyChallengeStore(application, DAILY_KEY_PREFIX)+    private val reminderSettings = DailyReminderSettings(application, DAILY_KEY_PREFIX)++    private val _uiState = MutableStateFlow(KartUiState())+    val uiState: StateFlow<KartUiState> = _uiState.asStateFlow()++    val reminderEnabled: StateFlow<Boolean> = reminderSettings.enabled+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)++    val reminderMinutesOfDay: StateFlow<Long> = reminderSettings.minutesOfDay+        .stateIn(+            viewModelScope,+            SharingStarted.WhileSubscribed(5_000),+            DailyPuzzleReminder.DEFAULT_MINUTES_OF_DAY,+        )++    val achievementsManager: AchievementsManager = run {+        val json = application.assets.open("achievements.json").bufferedReader().readText()+        KartAchievementsManager(application, json, dataStore, dailyStore)+    }++    /**+     * The TV lobby. No PQC identity ships in the scaffold: the bundle lambda returns null until+     * the TV service wires `:library:e2ee-p2p`, so network handshakes refuse cleanly while the+     * placeholder race runs on local seats.+     */+    private val kartHost = KartHost(+        context = application,+        publicBundle = { null },+        unsealSecret = { null },+    )++    private val _racePhase = MutableStateFlow<RacePhase>(RacePhase.Lobby(kartHost.lobby.value))+    /** Lobby → countdown → race → results. The garage reads this alongside [uiState]. */+    val racePhase: StateFlow<RacePhase> = _racePhase.asStateFlow()++    private var tickJob: Job? = null+    private var race: PlaceholderRace? = null++    /** This device's seat, so the HUD knows which kart is ours. Null until the race starts. */+    var localPlayerId: String? = null+        private set++    init {+        achievementsManager.checkExistingAchievements()++        viewModelScope.launch { kartHost.start() }++        viewModelScope.launch {+            kartHost.lobby.collectLatest { lobby ->+                if (_racePhase.value is RacePhase.Lobby) {+                    _racePhase.value = RacePhase.Lobby(lobby)+                }+            }+        }++        viewModelScope.launch {+            combine(+                dataStore.gameMode,+                dataStore.currentCup,+                dataStore.cupsCleared,+                dataStore.racesWon,+                dataStore.bestLapMs,+            ) { mode, cup, cleared, won, bestLap ->+                Progress(mode, cup, cleared, won, bestLap)+            }.combine(dailyStore.currentStreak) { progress, streak ->+                Session(progress.mode, progress.cup, progress.cleared, progress.won, progress.bestLap, streak)+            }.collectLatest { session -> load(session) }+        }+    }++    private data class Progress(+        val mode: GameMode,+        val cup: Int,+        val cleared: Int,+        val won: Int,+        val bestLap: Long,+    )++    /** The stored inputs that decide which cup is on screen. */+    private data class Session(+        val mode: GameMode,+        val cup: Int,+        val cleared: Int,+        val won: Int,+        val bestLap: Long,+        val streak: Long,+    )++    private suspend fun load(session: Session) {+        val daily = session.mode == GameMode.DAILY+        val day = dailyStore.todayEpochDay()+        if (daily) dataStore.ensureDailyDay(day)++        _uiState.value = KartUiState(+            cup = KartRules.cupAt(session.cup),+            progress = KartProgress(+                currentCup = session.cup,+                cupsCleared = session.cleared,+                racesWon = session.won,+                bestLapMs = session.bestLap,+            ),+            mode = session.mode,+            dailyStreak = session.streak,+            dailyDone = daily && dailyStore.lastCompletedDay() == day,+        )+    }++    override fun startRace() {+        // The garage button starts the lobby countdown; the tick loop banks the cup clear when+        // the race finishes. Daily mode keeps the old instant-clear until daily events race.+        val state = _uiState.value+        if (state.mode == GameMode.DAILY) {+            onDailyCleared()+            return+        }+        if (_racePhase.value !is RacePhase.Lobby) return+        // Solo seat for the scaffold: this device drives kart one until phones join.+        localPlayerId = localPlayerId ?: "local-${System.currentTimeMillis()}"+        val seat = requireNotNull(localPlayerId)+        kartHost.host.addLocalPlayer(seat, "You")+        viewModelScope.launch {+            for (count in COUNTDOWN_SECONDS downTo 1) {+                _racePhase.value = RacePhase.Countdown(count)+                delay(1_000)+            }+            beginRace(seat)+        }+    }++    /**+     * Feed one raw stick sample for the local seat. Called by the placeholder touch controls below;+     * gamepads and network phones arrive through the host instead.+     *+     * Builds the same [ControllerInput] shape every other source builds and routes it through the+     * same session, so the tick loop has exactly one input path per seat to read.+     */+    fun onLocalStick(playerId: String, x: Float, y: Float) {+        if (_racePhase.value !is RacePhase.Racing) return+        kartHost.host.onLocalInput(+            com.vayunmathur.sdk.controller.ControllerInput(+                playerId = playerId,+                seq = 0L,+                axes = listOf(x, y, 0f, 0f, 0f, 0f),+            ),+        )+    }++    /** A gamepad took or freed a seat. Hot-plug mid-race changes the next race, never this one. */+    fun onGamepadSeat(playerId: String, name: String, present: Boolean) {+        if (present) kartHost.host.addLocalPlayer(playerId, name.ifBlank { "Gamepad" })+        else kartHost.host.removeLocalPlayer(playerId)+    }++    /** One gamepad sample, already shaped as a [ControllerInput] by [GamepadDirect]. */+    fun onGamepadInput(input: com.vayunmathur.sdk.controller.ControllerInput) {+        if (_racePhase.value !is RacePhase.Racing) return+        kartHost.host.onLocalInput(input)+    }++    private fun beginRace(seat: String) {+        val playerIds = kartHost.lobby.value.slots.map { it.playerId }+        val seats = if (playerIds.isEmpty()) listOf(seat) else playerIds+        val newRace = PlaceholderRace(playerIds = seats)+        race = newRace+        kartHost.host.startRace()+        tickJob?.cancel()+        tickJob = viewModelScope.launch {+            var lastMs = android.os.SystemClock.uptimeMillis()+            while (isActive) {+                delay(TICK_MS)+                val nowMs = android.os.SystemClock.uptimeMillis()+                val dt = ((nowMs - lastMs).coerceAtMost(250L)) / 1_000f+                lastMs = nowMs+                val latest = kartHost.inputs.value+                for (id in seats) {+                    val sample = latest[id] ?: continue+                    val control = GameInputLoop.normalize(sample)+                    newRace.setControl(id, control)+                    KartNative.onDriveInput(+                        seats.indexOf(id),+                        control.throttle,+                        control.steering,+                        control.brake,+                    )+                    KartNative.setDrift(seats.indexOf(id), control.drift)+                    if (control.itemUse) {+                        newRace.useItem(id)+                        KartNative.useItem(seats.indexOf(id))+                    }+                }+                newRace.tick(dt)+                if (newRace.finished) {+                    finishRace(newRace)+                    return@launch+                }+                val order = newRace.leaderboard()+                _racePhase.value = RacePhase.Racing(+                    order = order,+                    lapProgress = order.associateWith { newRace.lapProgress(it) },+                    playerLap = newRace.lapOf(seat),+                    totalLaps = RACE_LAPS,+                )+            }+        }+    }++    private fun finishRace(finished: PlaceholderRace) {+        tickJob?.cancel()+        tickJob = null+        kartHost.host.endRace()+        val winner = finished.winner() ?: finished.leaderboard().first()+        val order = finished.leaderboard()+        _racePhase.value = RacePhase.Results(winner = winner, order = order)+        val state = _uiState.value+        viewModelScope.launch {+            val manager = achievementsManager+            manager.onAchievementUnlocked("first_race")+            if (winner == localPlayerId) {+                manager.onAchievementUnlocked("first_win")+            }+            val total = dataStore.recordCleared()+            manager.onProgressUpdated("cups_3", total)+            manager.onProgressUpdated("cups_10", total)+            KartRules.nextCup(state.progress.currentCup)?.let { dataStore.saveCup(it) }+        }+        race = null+    }++    /** Back to the lobby from results. Seats stay; the next Start Race counts down again. */+    override fun backToLobby() {+        _racePhase.value = RacePhase.Lobby(kartHost.lobby.value)+    }++    override fun onCleared() {+        tickJob?.cancel()+        kartHost.stop()+    }++    override fun nextCup() {+        val cup = _uiState.value.progress.currentCup+        viewModelScope.launch {+            KartRules.nextCup(cup)?.let { dataStore.saveCup(it) }+        }+    }++    override fun setGameMode(mode: GameMode) {+        viewModelScope.launch { dataStore.setGameMode(mode) }+    }++    override fun setReminderEnabled(enabled: Boolean) {+        viewModelScope.launch {+            reminderSettings.setEnabled(enabled)+            rescheduleReminder(enabled, reminderMinutesOfDay.value)+        }+    }++    override fun setReminderTime(hour: Int, minute: Int) {+        viewModelScope.launch {+            val minutes = (hour * 60 + minute).toLong()+            reminderSettings.setMinutesOfDay(minutes)+            rescheduleReminder(reminderEnabled.value, minutes)+        }+    }++    private fun rescheduleReminder(enabled: Boolean, minutesOfDay: Long) {+        DailyPuzzleReminder.update(+            context = getApplication(),+            keyPrefix = DAILY_KEY_PREFIX,+            notificationId = REMINDER_NOTIFICATION_ID,+            enabled = enabled,+            hour = (minutesOfDay / 60).toInt(),+            minute = (minutesOfDay % 60).toInt(),+        )+    }++    fun dismissAchievementNotification() = achievementsManager.dismissNotification()++    private fun onDailyCleared() {+        viewModelScope.launch {+            val day = dailyStore.todayEpochDay()+            val manager = achievementsManager+            manager.onAchievementUnlocked("first_daily")+            val streak = dailyStore.recordDayCompleted(day)+            DailyStreakReporter.report(getApplication(), "kart", streak, day)+            manager.onProgressUpdated("daily_streak_7", streak.current.toInt())+            manager.onProgressUpdated("daily_streak_30", streak.current.toInt())+            load(uiState.value.toSession())+        }+    }++    private fun KartUiState.toSession() = Session(+        mode = mode,+        cup = progress.currentCup,+        cleared = progress.cupsCleared,+        won = progress.racesWon,+        bestLap = progress.bestLapMs,+        streak = dailyStreak,+    )++    companion object {+        /** Namespace shared by the daily-challenge store and its reminder. */+        const val DAILY_KEY_PREFIX = "kart_daily"++        private const val REMINDER_NOTIFICATION_ID = 5106++        /** Ticks per second for the placeholder race loop. */+        private const val TICK_MS = 50L++        /** Laps per race. Mirrors the placeholder's default. */+        private const val RACE_LAPS = 3++        /** Seconds of 3-2-1 before controls go live. */+        private const val COUNTDOWN_SECONDS = 3++        /**+         * Keeps date-derived daily seeds away from the cup indexes casual mode uses, and away+         * from the offsets the other games picked (500M pipes, 700M wordmaker, 900M unblockjam,+         * 1.1B nonogram, 1.3B arrows).+         */+        const val DAILY_SEED_OFFSET = 1_500_000_000L+    }+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.ktnew file mode 100644index 0000000000..dbc542aa19--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt@@ -0,0 +1,28 @@+package com.vayunmathur.games.kart.platform++import com.vayunmathur.games.kart.domain.KartControl+import com.vayunmathur.sdk.controller.LobbyState++/** Where a race stands. The garage is [Lobby]; [Results] banks progress on entry. */+sealed interface RacePhase {++    /** Seats filling up. [lobby] mirrors `ControllerHost.lobby`. */+    data class Lobby(val lobby: LobbyState) : RacePhase++    /** 3-2-1-GO, in seconds remaining. Controls are ignored. */+    data class Countdown(val secondsLeft: Int) : RacePhase++    /**+     * Live race. [order] is player ids (humans then AI) by progress descending; [lapProgress]+     * maps each id to 0..1 through its current lap; [playerLap] is this device's completed laps.+     */+    data class Racing(+        val order: List<String>,+        val lapProgress: Map<String, Float>,+        val playerLap: Int,+        val totalLaps: Int,+    ) : RacePhase++    /** Across the line. [winner] may be an AI id; [order] is the final standing. */+    data class Results(val winner: String, val order: List<String>) : RacePhase+}
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.ktnew file mode 100644index 0000000000..005bfd1c62--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGamePage.kt@@ -0,0 +1,30 @@+package com.vayunmathur.games.kart.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.games.kart.Route+import com.vayunmathur.games.kart.platform.KartViewModel+import com.vayunmathur.library.util.NavBackStack++/**+ * Binds [KartViewModel] to the stateless [KartGameScreen].+ *+ * The ViewModel already implements the actions contract, so this only has to collect state and supply+ * the two navigation callbacks the garage cannot know about.+ */+@Composable+fun KartGamePage(+    backStack: NavBackStack<Route>,+    viewModel: KartViewModel,+) {+    val uiState by viewModel.uiState.collectAsState()+    val racePhase by viewModel.racePhase.collectAsState()+    KartGameScreen(+        state = uiState,+        phase = racePhase,+        actions = viewModel,+        onOpenSettings = { backStack.add(Route.Settings) },+        onOpenGameCenter = { backStack.add(Route.GameCenter) },+    )+}
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.ktnew file mode 100644index 0000000000..1ef56cca15--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt@@ -0,0 +1,229 @@+package com.vayunmathur.games.kart.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import com.vayunmathur.games.kart.R+import com.vayunmathur.games.kart.data.GameMode+import com.vayunmathur.games.kart.platform.KartGameActions+import com.vayunmathur.games.kart.platform.KartUiState+import com.vayunmathur.games.kart.platform.RacePhase+import com.vayunmathur.library.ui.AppBarAlignment+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.game.DailyStreakText+import com.vayunmathur.library.ui.game.GameModeChooser+import com.vayunmathur.library.ui.game.GameTopBarActions++/**+ * The garage and the race, with no dependency on the ViewModel so it can be rendered from a+ * `@Preview` — see `src/screenshotTest`.+ */+@Composable+fun KartGameScreen(+    state: KartUiState,+    phase: RacePhase,+    actions: KartGameActions,+    onOpenSettings: () -> Unit,+    onOpenGameCenter: () -> Unit,+) {+    val daily = state.mode == GameMode.DAILY+    AppScaffold(+        title = {+            GameModeChooser(+                selected = state.mode,+                options = GameMode.entries,+                // The ladder mode folds the cup into its label, so the bar needs no second title.+                label = { mode ->+                    when (mode) {+                        GameMode.CASUAL -> state.cup?.let {+                            stringResource(R.string.cup_title, it.name)+                        } ?: stringResource(R.string.app_name)++                        GameMode.DAILY -> stringResource(R.string.mode_daily)+                    }+                },+                menuLabel = { mode ->+                    stringResource(+                        when (mode) {+                            GameMode.CASUAL -> R.string.mode_casual+                            GameMode.DAILY -> R.string.mode_daily+                        },+                    )+                },+                onSelect = actions::setGameMode,+            )+        },+        alignment = AppBarAlignment.Center,+        actions = {+            GameTopBarActions(+                onOpenGameCenter = onOpenGameCenter,+                onOpenSettings = onOpenSettings,+            )+        },+        scrollBehavior = appBarScrollBehavior(),+    ) { padding ->+        Column(+            Modifier+                .fillMaxSize()+                .padding(padding)+                .verticalScroll(rememberScrollState())+                .padding(horizontal = Spacing.md),+            horizontalAlignment = Alignment.CenterHorizontally,+            verticalArrangement = Arrangement.spacedBy(Spacing.md),+        ) {+            if (daily) {+                DailyStreakText(state.dailyStreak)+            }++            when (val p = phase) {+                is RacePhase.Lobby -> LobbyBody(state, p, daily, actions)+                is RacePhase.Countdown -> CountdownBody(p)+                is RacePhase.Racing -> RacingBody(p)+                is RacePhase.Results -> ResultsBody(p, actions)+            }+        }+    }+}++@Composable+private fun LobbyBody(+    state: KartUiState,+    phase: RacePhase.Lobby,+    daily: Boolean,+    actions: KartGameActions,+) {+    val cup = state.cup+    if (cup == null) {+        Box(+            Modifier+                .fillMaxWidth()+                .padding(Spacing.xxl),+            contentAlignment = Alignment.Center,+        ) {+            Text(+                stringResource(R.string.garage_loading),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                textAlign = TextAlign.Center,+            )+        }+    } else {+        Text(+            stringResource(R.string.cup_tracks, cup.trackCount),+            style = MaterialTheme.typography.titleLarge,+            color = MaterialTheme.colorScheme.primary,+        )+        if (state.progress.racesWon > 0) {+            Text(+                stringResource(R.string.races_won, state.progress.racesWon),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        val seats = phase.lobby.slots.size+        if (seats > 0) {+            Text(+                stringResource(R.string.lobby_seats, seats),+                style = MaterialTheme.typography.bodyMedium,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+        if (daily && state.dailyDone) {+            Text(+                stringResource(R.string.daily_come_back_tomorrow),+                style = MaterialTheme.typography.bodyMedium,+                textAlign = TextAlign.Center,+            )+        } else {+            Button(+                onClick = { actions.startRace() },+                modifier = Modifier.fillMaxWidth(),+            ) { Text(stringResource(R.string.start_race)) }+            if (!daily) {+                Text(+                    stringResource(R.string.how_to_play),+                    style = MaterialTheme.typography.bodySmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                    textAlign = TextAlign.Center,+                )+            }+        }+    }+}++@Composable+private fun CountdownBody(phase: RacePhase.Countdown) {+    Text(+        "${phase.secondsLeft}",+        style = MaterialTheme.typography.displayLarge,+        color = MaterialTheme.colorScheme.primary,+    )+    Text(+        stringResource(R.string.countdown_hint),+        style = MaterialTheme.typography.bodyMedium,+        color = MaterialTheme.colorScheme.onSurfaceVariant,+        textAlign = TextAlign.Center,+    )+}++@Composable+private fun RacingBody(phase: RacePhase.Racing) {+    Text(+        stringResource(R.string.race_lap, phase.playerLap + 1, phase.totalLaps),+        style = MaterialTheme.typography.titleLarge,+        color = MaterialTheme.colorScheme.primary,+    )+    phase.order.forEachIndexed { place, id ->+        Column(Modifier.fillMaxWidth()) {+            Text(+                stringResource(R.string.race_place, place + 1, displayName(id)),+                style = MaterialTheme.typography.bodyMedium,+            )+            LinearProgressIndicator(+                progress = { phase.lapProgress[id] ?: 0f },+                modifier = Modifier.fillMaxWidth(),+            )+        }+    }+}++/** Short label for a seat: players keep their join name, AI karts show as rivals. */+private fun displayName(id: String): String = if (id.startsWith("ai-")) "Rival ${id.removePrefix("ai-")}" else "You"++@Composable+private fun ResultsBody(phase: RacePhase.Results, actions: KartGameActions) {+    Text(+        stringResource(R.string.results_title),+        style = MaterialTheme.typography.titleLarge,+        color = MaterialTheme.colorScheme.primary,+    )+    phase.order.forEachIndexed { place, id ->+        Text(+            stringResource(R.string.race_place, place + 1, displayName(id)),+            style = MaterialTheme.typography.bodyMedium,+            color = if (id == phase.winner) MaterialTheme.colorScheme.primary+            else MaterialTheme.colorScheme.onSurface,+        )+    }+    OutlinedButton(+        onClick = { actions.backToLobby() },+        modifier = Modifier.fillMaxWidth(),+    ) { Text(stringResource(R.string.back_to_lobby)) }+}
games/kart/src/main/java/com/vayunmathur/games/kart/ui/SettingsPage.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/SettingsPage.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/SettingsPage.ktnew file mode 100644index 0000000000..40c35ec459--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/SettingsPage.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.kart.ui++import android.Manifest+import android.os.Build+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.kart.platform.KartViewModel+import com.vayunmathur.games.kart.platform.SettingsActions+import com.vayunmathur.games.kart.platform.SettingsUiState+import com.vayunmathur.library.ui.DailyReminderSettingsSection+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.rememberPermissionRequest++/** Binds [KartViewModel] to the stateless [SettingsScreen]. */+@Composable+fun SettingsPage(viewModel: KartViewModel, onBack: () -> Unit) {+    val reminderEnabled by viewModel.reminderEnabled.collectAsState()+    val reminderMinutes by viewModel.reminderMinutesOfDay.collectAsState()+    val requestNotifications = rememberPermissionRequest(Manifest.permission.POST_NOTIFICATIONS)++    SettingsScreen(+        state = SettingsUiState(+            reminderEnabled = reminderEnabled,+            reminderHour = (reminderMinutes / 60).toInt(),+            reminderMinute = (reminderMinutes % 60).toInt(),+        ),+        actions = object : SettingsActions {+            override fun setReminderEnabled(enabled: Boolean) {+                // Asked for lazily, on opt-in only, so the screen never blocks on a prompt.+                if (enabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+                    requestNotifications()+                }+                viewModel.setReminderEnabled(enabled)+            }++            override fun setReminderTime(hour: Int, minute: Int) =+                viewModel.setReminderTime(hour, minute)+        },+        onBack = onBack,+    )+}++/** The settings screen, ViewModel-free so a preview can render it. */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun SettingsScreen(state: SettingsUiState, actions: SettingsActions, onBack: () -> Unit) {+    DetailScaffold(+        title = stringResource(UiR.string.settings),+        onNavigateBack = onBack,+        scrollBehavior = appBarScrollBehavior(),+    ) {+        DailyReminderSettingsSection(+            enabled = state.reminderEnabled,+            hour = state.reminderHour,+            minute = state.reminderMinute,+            onEnabledChange = { actions.setReminderEnabled(it) },+            onTimeChange = { hour, minute -> actions.setReminderTime(hour, minute) },+        )+    }+}
games/kart/src/main/res/values/strings.xml
diff --git a/games/kart/src/main/res/values/strings.xml b/games/kart/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..dd56d80e0f--- /dev/null+++ b/games/kart/src/main/res/values/strings.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">+    <!-- Manifest / TopAppBar: App name. Noun, singular -->+    <string name="app_name" translatable="false">Kart</string>++    <!-- GameModeDropdown: Mode playing the cup progression. Noun plural -->+    <string name="mode_casual">Cups</string>+    <!-- GameModeDropdown: Mode playing today's shared event. Adjective -->+    <string name="mode_daily">Daily</string>++    <!-- KartGameScreen TopAppBar: Current cup in the progression. %1$s = cup name, e.g. Mushroom Cup -->+    <string name="cup_title"><xliff:g id="cup" example="Mushroom Cup">%1$s</xliff:g></string>+    <!-- KartGameScreen: How many tracks this cup holds. %1$d = track count, e.g. 4 -->+    <string name="cup_tracks"><xliff:g id="count" example="4">%1$d</xliff:g> tracks</string>+    <!-- KartGameScreen: Lifetime race wins. %1$d = win count, e.g. 6 -->+    <string name="races_won"><xliff:g id="count" example="6">%1$d</xliff:g> race wins</string>+    <!-- KartGameScreen: Starts the race flow. Verb phrase -->+    <string name="start_race">Start Race</string>+    <!-- KartGameScreen: Shown while the cup has not loaded yet. Sentence -->+    <string name="garage_loading">Warming up the engines…</string>+    <!-- KartGameScreen: Shown after clearing the daily, since there is only one per day. Sentence -->+    <string name="daily_come_back_tomorrow">Finished! Come back tomorrow for a new event.</string>+    <!-- KartGameScreen: Hint under the race button explaining what is coming. Sentence -->+    <string name="how_to_play">Connect a phone as a controller, or plug in a gamepad</string>+    <!-- KartGameScreen: Seats taken in the lobby. %1$d = seat count, e.g. 2 -->+    <string name="lobby_seats"><xliff:g id="count" example="2">%1$d</xliff:g> driver(s) in the lobby</string>+    <!-- KartGameScreen: Shown during the countdown. Sentence -->+    <string name="countdown_hint">Get ready… controls go live at GO</string>+    <!-- KartGameScreen: Current lap in the race. %1$d = current lap, e.g. 2. %2$d = total laps, e.g. 3 -->+    <string name="race_lap">Lap <xliff:g id="current" example="2">%1$d</xliff:g> of <xliff:g id="total" example="3">%2$d</xliff:g></string>+    <!-- KartGameScreen: One standings row. %1$d = place, e.g. 1. %2$s = driver name -->+    <string name="race_place"><xliff:g id="place" example="1">%1$d</xliff:g>. <xliff:g id="name" example="You">%2$s</xliff:g></string>+    <!-- KartGameScreen: Results header. Noun phrase -->+    <string name="results_title">Final Standings</string>+    <!-- KartGameScreen: Back to the lobby from results. Verb phrase -->+    <string name="back_to_lobby">Back to Lobby</string>+</resources>
games/kart/src/main/res/xml/data_extraction_rules.xml
diff --git a/games/kart/src/main/res/xml/data_extraction_rules.xml b/games/kart/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 0000000000..d137deb223--- /dev/null+++ b/games/kart/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,34 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+  Kart. Audited state: filesDir/datastore/settings.preferences_pb, holding the+  current cup, the lifetime cleared/won counters, the best lap, and the daily+  day it belongs to; plus filesDir/datastore_default.preferences_pb, the shared+  DataStoreUtils file holding the DailyChallengeStore("kart_daily") streak, the+  daily reminder settings and the AchievementsManager unlocks. No+  SharedPreferences, no Room database, nothing written to external storage -+  achievements.json is a read-only APK asset. Back everything up; it is a few+  KB of pure user progress.+  SCOPE: kart declares android:backupAgent=".platform.AppBackupAgent" and does+  NOT set android:fullBackupOnly, so Android uses key/value backup and the+  <cloud-backup> section below is NOT consulted. Cloud content is exactly+  AppBackupAgent's datastoreNames = ["settings", "datastore_default"], which is+  the same data this file would have sent. <device-transfer> IS governed here,+  and these rules become the cloud control too if the backupAgent is ever+  removed.+-->+<data-extraction-rules>+    <cloud-backup>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </cloud-backup>+    <device-transfer>+        <include domain="root" path="." />+        <include domain="file" path="." />+        <include domain="database" path="." />+        <include domain="sharedpref" path="." />+        <include domain="external" path="." />+    </device-transfer>+</data-extraction-rules>
games/kart/src/screenshotTest/kotlin/com/vayunmathur/games/kart/MetadataPreviews.kt
diff --git a/games/kart/src/screenshotTest/kotlin/com/vayunmathur/games/kart/MetadataPreviews.kt b/games/kart/src/screenshotTest/kotlin/com/vayunmathur/games/kart/MetadataPreviews.ktnew file mode 100644index 0000000000..2485a5c8c5--- /dev/null+++ b/games/kart/src/screenshotTest/kotlin/com/vayunmathur/games/kart/MetadataPreviews.kt@@ -0,0 +1,109 @@+package com.vayunmathur.games.kart++import androidx.compose.runtime.Composable+import androidx.compose.ui.tooling.preview.Preview+import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.kart.data.CUPS+import com.vayunmathur.games.kart.data.GameMode+import com.vayunmathur.games.kart.data.KartProgress+import com.vayunmathur.games.kart.platform.KartGameActions+import com.vayunmathur.games.kart.platform.KartUiState+import com.vayunmathur.games.kart.platform.RacePhase+import com.vayunmathur.games.kart.ui.KartGameScreen+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.sdk.controller.LobbyState+import com.vayunmathur.sdk.controller.PlayerSlot++/** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */+private const val PHONE = "spec:width=411dp,height=891dp,dpi=420"++/**+ * The store listing images.+ *+ * Previews must be members of a class and carry both `@PreviewTest` and `@Preview`, or the screenshot+ * engine discovers no tests. The `PreviewN` names set the order they appear in the listing, because+ * the collector sorts by filename. Run `./gradlew :games:kart:metadata`.+ *+ * The garage screen has no polling `LaunchedEffect`, so a preview settles on the first frame.+ */+class MetadataPreviews {++    @PreviewTest+    @Preview(name = "1-garage", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview1Garage() {+        // The opening cup with a few wins on the board, so the shot shows the+        // progress line under the track count.+        Garage(+            KartUiState(+                cup = CUPS[0],+                progress = KartProgress(currentCup = 0, racesWon = 6),+            ),+            RacePhase.Lobby(LobbyState(gameId = "kart")),+        )+    }++    @PreviewTest+    @Preview(name = "2-racing", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview2Racing() {+        // Mid-race: the standings the placeholder engine produces, so the listing shows the+        // game beyond the garage.+        Garage(+            KartUiState(cup = CUPS[0]),+            RacePhase.Racing(+                order = listOf("you", "ai-0", "ai-1"),+                lapProgress = mapOf("you" to 0.6f, "ai-0" to 0.7f, "ai-1" to 0.4f),+                playerLap = 1,+                totalLaps = 3,+            ),+        )+    }++    @PreviewTest+    @Preview(name = "3-late-cup", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview3LateCup() {+        // The last cup, so the listing shows the progression reaches past the opener.+        Garage(+            KartUiState(+                cup = CUPS[2],+                progress = KartProgress(currentCup = 2, cupsCleared = 2, racesWon = 11),+            ),+            RacePhase.Lobby(+                LobbyState(+                    slots = listOf(PlayerSlot("p1", "You", remote = false)),+                    gameId = "kart",+                ),+            ),+        )+    }++    @PreviewTest+    @Preview(name = "4-daily", device = PHONE, showSystemUi = true)+    @Composable+    fun Preview4Daily() {+        Garage(+            KartUiState(+                cup = CUPS[1],+                mode = GameMode.DAILY,+            ),+            RacePhase.Lobby(LobbyState(gameId = "kart")),+            streak = 4,+        )+    }++    @Composable+    private fun Garage(state: KartUiState, phase: RacePhase, streak: Long = 0) {+        // Layoutlib has no wallpaper to sample, so Material You falls back to the default palette.+        DynamicTheme(darkTheme = true) {+            KartGameScreen(+                state = state.copy(dailyStreak = streak),+                phase = phase,+                actions = KartGameActions.Noop,+                onOpenSettings = {},+                onOpenGameCenter = {},+            )+        }+    }+}
games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.ktnew file mode 100644index 0000000000..59f9eb2e84--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt@@ -0,0 +1,146 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class KartRaceTest {++    private fun input(+        seq: Long = 1,+        buttons: Long = 0L,+        axes: List<Float> = listOf(0f, -1f, 0f, 0f, 0f, 0f),+    ) = ControllerInput(playerId = "p1", seq = seq, buttons = buttons, axes = axes)++    @Test+    fun fullThrottleAdvances() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        race.setControl("p1", GameInputLoop.normalize(input()))+        race.tick(1f)+        assertTrue(race.lapProgress("p1") > 0f)+    }++    @Test+    fun neutralStaysPut() {+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        race.setControl("p1", KartControl.NEUTRAL)+        race.tick(5f)+        assertEquals(0f, race.lapProgress("p1"))+    }++    @Test+    fun steeringScrubsSpeed() {+        val straight = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        straight.setControl("p1", KartControl(throttle = 1f, steering = 0f))+        straight.tick(1f)+        val turning = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        turning.setControl("p1", KartControl(throttle = 1f, steering = 1f))+        turning.tick(1f)+        assertTrue(turning.lapProgress("p1") < straight.lapProgress("p1"))+    }++    @Test+    fun aiFinishesAlone() {+        // No human input at all: the AI still completes laps, so a solo race always ends.+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 1, laps = 1)+        repeat(120) { race.tick(1f) }+        assertTrue(race.finished)+    }++    @Test+    fun winnerIsFirstAcross() {+        val race = PlaceholderRace(playerIds = listOf("p1", "p2"), aiCount = 0, laps = 1)+        race.setControl("p1", KartControl(throttle = 1f))+        race.setControl("p2", KartControl(throttle = 0.5f))+        repeat(120) { race.tick(1f) }+        assertTrue(race.finished)+        assertEquals("p1", race.winner())+        assertEquals(listOf("p1", "p2"), race.leaderboard())+    }++    @Test+    fun deadzoneHoldsCenter() {+        assertEquals(0f, GameInputLoop.curve(0.1f))+        assertEquals(0f, GameInputLoop.curve(-0.14f))+    }++    @Test+    fun curveReachesFullThrow() {+        assertEquals(1f, GameInputLoop.curve(1f))+        assertEquals(-1f, GameInputLoop.curve(-1f))+    }++    @Test+    fun stickUpIsThrottle() {+        // Left stick pushed fully up: stickY = -1.+        val control = GameInputLoop.normalize(input(axes = listOf(0f, -1f, 0f, 0f, 0f, 0f)))+        assertEquals(1f, control.throttle)+        assertEquals(0f, control.brake)+    }++    @Test+    fun stickDownIsBrake() {+        val control = GameInputLoop.normalize(input(axes = listOf(0f, 1f, 0f, 0f, 0f, 0f)))+        assertEquals(0f, control.throttle)+        assertTrue(control.brake > 0f)+    }++    @Test+    fun shoulderIsDriftAndAIsItem() {+        val control = GameInputLoop.normalize(+            input(buttons = ControllerButton.RIGHT_SHOULDER.bit or ControllerButton.A.bit),+        )+        assertTrue(control.drift)+        assertTrue(control.itemUse)+    }++    @Test+    fun dpadSteersAtRest() {+        val control = GameInputLoop.normalize(+            input(buttons = ControllerButton.DPAD_LEFT.bit, axes = List(6) { 0f }),+        )+        assertTrue(control.steering < 0f)+    }++    @Test+    fun itemFiresOncePerPress() {+        // The loop reports the button state every tick; the race latches the rising edge, so a+        // held button fires once no matter how many ticks it spans.+        val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        race.setControl("p1", KartControl(throttle = 1f, itemUse = true))+        assertTrue(race.useItem("p1"))+        assertEquals(false, race.useItem("p1"))+        assertEquals(false, race.useItem("p1"))+        // Release and press again: a fresh edge, a fresh fire.+        race.setControl("p1", KartControl(throttle = 1f, itemUse = false))+        assertEquals(false, race.useItem("p1"))+        race.setControl("p1", KartControl(throttle = 1f, itemUse = true))+        assertTrue(race.useItem("p1"))+    }++    @Test+    fun driftKeepsMoreSpeedThanGrip() {+        // Full lock while drifting must beat full lock on grip, or drift is decoration.+        val drift = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        drift.setControl("p1", KartControl(throttle = 1f, steering = 1f, drift = true))+        drift.tick(1f)+        val grip = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        grip.setControl("p1", KartControl(throttle = 1f, steering = 1f, drift = false))+        grip.tick(1f)+        assertTrue(drift.lapProgress("p1") > grip.lapProgress("p1"))+    }++    @Test+    fun driftStillScrubs() {+        // …but not for free: drifting through full lock is slower than driving straight.+        val drift = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        drift.setControl("p1", KartControl(throttle = 1f, steering = 1f, drift = true))+        drift.tick(1f)+        val straight = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+        straight.setControl("p1", KartControl(throttle = 1f, steering = 0f))+        straight.tick(1f)+        assertTrue(drift.lapProgress("p1") < straight.lapProgress("p1"))+    }+}
library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt
diff --git a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.ktindex c08100c640..baf522e615 100644--- a/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt+++ b/library/src/main/java/com/vayunmathur/library/util/GameHubCompose.kt@@ -34,6 +34,7 @@ private fun gameDisplayName(gameId: String): String = when (gameId) {     "minesweeper" -> "Minesweeper"     "nonogram" -> "Nonogram"     "arrows" -> "Arrows"+    "kart" -> "Kart"     else -> gameId.replaceFirstChar { it.uppercase() } } 
library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.ktindex f41eebb9d9..49405484e9 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/Icons.kt@@ -1627,6 +1627,17 @@ fun IconFlag(modifier: Modifier = Modifier, tint: Color = LocalContentColor.curr fun IconMine(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.Brightness7, "Mine", modifier, tint) +/**+ * A checkered flag — the kart racer.+ *+ * Material has no kart or checkered flag; `SportsEsports` (the gamepad) is the closest+ * glyph that reads as a game rather than a sport. Named for what it means here rather+ * than what it is called upstream, as `IconMine` (Brightness7) already is.+ */+@Composable+fun IconKart(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.SportsEsports, "Kart", modifier, tint)+ // --- Music detection --- /** A single quaver - music is playing. */ @Composable@@ -1674,3 +1685,23 @@ fun IconBatteryCharging(modifier: Modifier = Modifier, tint: Color = LocalConten @Composable fun IconDoNotDisturb(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =     AppIcon(Icons.Filled.DoNotDisturbOn, "Do not disturb", modifier, tint)++/**+ * Globe - online (Lichess) play in the chess app's Online Play tab.+ *+ * Named for what it means here rather than what it is called upstream, as+ * `IconMine` (Brightness7) and `IconKart` (SportsEsports) already are.+ */+@Composable+fun IconOnline(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.Public, "Online play", modifier, tint)++/**+ * Clock face - the game clocks in the chess app's online game screen.+ *+ * Named for what it means here rather than what it is called upstream, as+ * `IconMine` (Brightness7) and `IconKart` (SportsEsports) already are.+ */+@Composable+fun IconClock(modifier: Modifier = Modifier, tint: Color = LocalContentColor.current) =+    AppIcon(Icons.Filled.AccessTime, "Clock", modifier, tint)
metadata_data/games-kart.md
diff --git a/metadata_data/games-kart.md b/metadata_data/games-kart.mdnew file mode 100644index 0000000000..5f9b76662a--- /dev/null+++ b/metadata_data/games-kart.md@@ -0,0 +1,10 @@+A TV-first kart racer played with phones as controllers++Features:+- Race cups of four tracks against AI drivers+- Phones with the games hub app join as controllers over the local network+- Physical Android gamepads work on the TV too, side by side with phones+- A fresh daily event, generated on device from the date+- Items, drift boosts, and a chase camera once the 3D engine lands++100% offline
metadata_data/photos/games-kart/1.png
diff --git a/metadata_data/photos/games-kart/1.png b/metadata_data/photos/games-kart/1.pngnew file mode 100644index 0000000000..904ea9c73dBinary files /dev/null and b/metadata_data/photos/games-kart/1.png differ
metadata_data/photos/games-kart/2.png
diff --git a/metadata_data/photos/games-kart/2.png b/metadata_data/photos/games-kart/2.pngnew file mode 100644index 0000000000..82ca3aa022Binary files /dev/null and b/metadata_data/photos/games-kart/2.png differ
metadata_data/photos/games-kart/3.png
diff --git a/metadata_data/photos/games-kart/3.png b/metadata_data/photos/games-kart/3.pngnew file mode 100644index 0000000000..8e3cb00c6aBinary files /dev/null and b/metadata_data/photos/games-kart/3.png differ
metadata_data/photos/games-kart/4.png
diff --git a/metadata_data/photos/games-kart/4.png b/metadata_data/photos/games-kart/4.pngnew file mode 100644index 0000000000..5436a3211dBinary files /dev/null and b/metadata_data/photos/games-kart/4.png differ
sdk/controller/AGENTS.md
diff --git a/sdk/controller/AGENTS.md b/sdk/controller/AGENTS.mdnew file mode 100644index 0000000000..ac9322544f--- /dev/null+++ b/sdk/controller/AGENTS.md@@ -0,0 +1,43 @@+# AGENTS.md — sdk/controller/ (':sdk:controller')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `sdk/controller/` + allowed shared modules. Do not root-scan.++<!-- last-reviewed: 2026-10-17 -->+- Gradle: :sdk:controller / dir: sdk/controller/+- Package roots present: (public controller SDK — one package)+- Entry files: ControllerContract.kt + ControllerModels.kt (no MainActivity/Route — SDK)+- Deps: :library (Hkdf key schedule), :library:e2ee-p2p (E2ee AES-GCM; PQC sealing stays in the hosting app)+- Metadata: metadata_data/sdk-controller.md (absent — SDKs have none by design)+- Rust: no / screenshotTest: no++## Overview+**Purpose:** Public SDK for phone-as-controller play on TV — the contract side; the TV game's+`ControllerHost` is the sink side. Generic by design: buttons are a bitmask, sticks are normalized+axes, and nothing here names a kart. A future TV game reuses this SDK as-is.+**Consumers:** Kart TV (`ControllerHost`) + hub-hosted `ControllerPad` (`ControllerClient`); any+future TV game.+**Entry points:** `ControllerContract.kt` → `ControllerModels.kt` → `ControllerHost.kt` /+`ControllerClient.kt`.+**Gotchas:** Contract changes must stay compatible with host + client simultaneously — version the+contract, never break it silently. `UDP later is a transport swap`: seq/replay/rate-limits are+baked in so only `ControllerSocket` changes underneath.++## Key files+- com/vayunmathur/sdk/controller/ControllerContract.kt — version, service type, cadence, limits+- com/vayunmathur/sdk/controller/ControllerModels.kt — input/buttons/axes/lobby/join/rumble messages+- com/vayunmathur/sdk/controller/ControllerFraming.kt — int32be framing + AES-GCM codec+- com/vayunmathur/sdk/controller/ControllerKeys.kt — HKDF key schedule, pairing gate, transcript+- com/vayunmathur/sdk/controller/ControllerSocket.kt — TCP socket, both ends+- com/vayunmathur/sdk/controller/ControllerDiscovery.kt — mDNS browse (phone side)+- com/vayunmathur/sdk/controller/ControllerAdvertiser.kt — mDNS register (TV side)+- com/vayunmathur/sdk/controller/ControllerHost.kt — N player slots, replay window, rate limit+- com/vayunmathur/sdk/controller/ControllerInputGate.kt — per-player replay + rate-limit policy (JVM-testable)+- com/vayunmathur/sdk/controller/ControllerPad.kt — reusable phone-as-controller UI (stick/buttons, PIN, lobby, rumble)+- com/vayunmathur/sdk/controller/ControllerClient.kt — connect/pair/join/input emit++## Verify (this module only)+```+/gradlew :sdk:controller:compileReleaseKotlin+./gradlew :sdk:controller:lint+./gradlew :sdk:controller:testDebugUnitTest+```
sdk/controller/build.gradle.kts
diff --git a/sdk/controller/build.gradle.kts b/sdk/controller/build.gradle.ktsnew file mode 100644index 0000000000..4beed3a206--- /dev/null+++ b/sdk/controller/build.gradle.kts@@ -0,0 +1,12 @@+plugins {+    id("common-conventions-library")+}++dependencies {+    // Hkdf: the whole key schedule expands from one 32-byte session secret.+    implementation(project(":library"))+    implementation(project(":library:e2ee-p2p"))+    // ControllerPad is built from the shared wrappers (Text/Button/OutlinedTextField), so the+    // phone UI restyles with everything else. Acyclic: :library:ui never depends back on SDKs.+    implementation(project(":library:ui"))+}
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.ktnew file mode 100644index 0000000000..16928826d8--- /dev/null+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerAdvertiser.kt@@ -0,0 +1,179 @@+package com.vayunmathur.sdk.controller++import android.content.Context+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import com.vayunmathur.library.log.Log++private const val TAG = "ControllerAdvertiser"++/**+ * How many instance names to try before giving up.+ *+ * Only reachable on platforms that actually report a failed registration.+ */+private const val MAX_NAME_ATTEMPTS = 5++/**+ * Distinguishes our mDNS instance name from the device name.+ *+ * Android 14's `MdnsRecordRepository.addService` rejects a registration whose *instance name* is+ * already taken **without comparing the service type**, so `onRegistrationFailed` may never fire+ * and the app cannot tell it is invisible. Suffixing the instance name sidesteps it, and costs+ * nothing visible because the phone renders TXT `fn` and only falls back to the instance name when+ * that attribute is missing.+ */+private const val INSTANCE_TAG = "Game Host"++/** The mDNS instance name for [friendlyName] on the [attempt]th try. */+private fun instanceLabel(friendlyName: String, attempt: Int): String =+    if (attempt <= 1) "$friendlyName ($INSTANCE_TAG)" else "$friendlyName ($INSTANCE_TAG $attempt)"++/**+ * TXT attributes on the registration.+ *+ * The phone needs a readable name and a version check before it connects to anything, plus which+ * game the lobby is for, so all three go in the record rather than in `HOST_HELLO`. The public+ * bundle is *not* here: it is kilobytes, and putting it in TXT would mean trusting an+ * unauthenticated mDNS record for the key the whole session seals to.+ */+private const val TXT_FRIENDLY_NAME = "fn"+private const val TXT_PROTOCOL_VERSION = "pv"+private const val TXT_ID = "id"+private const val TXT_GAME_ID = "gameId"++/**+ * Announces this TV as `_gamepad._tcp` on the LAN.+ *+ * The registration half of [ControllerDiscovery], kept to the same shape including its Android 16+ * trap: with Local Network Protections, `registerService` throws `SecurityException` unless+ * `ACCESS_LOCAL_NETWORK` has been granted, and a host that failed to advertise is indistinguishable+ * from one nobody has tried to connect to. [localNetworkBlocked] exists so the lobby screen can say+ * which of the two happened.+ */+class ControllerAdvertiser(context: Context) {++    private val nsdManager: NsdManager? =+        context.getSystemService(Context.NSD_SERVICE) as? NsdManager++    private var listener: NsdManager.RegistrationListener? = null++    /**+     * Bumped by [unadvertise] so a conflict retry scheduled by a registration we have since torn+     * down cannot resurrect it.+     */+    private var generation = 0++    /** True when the platform refused the registration, not when nothing has connected. */+    var localNetworkBlocked: Boolean = false+        private set++    /** The instance name the platform settled on, which it may rename on a conflict. */+    var registeredName: String? = null+        private set++    /**+     * Advertise [friendlyName] on [port]. Safe to call repeatedly; re-advertising replaces the prior+     * registration rather than stacking a second one.+     */+    fun advertise(friendlyName: String, deviceId: String, port: Int, gameId: String) {+        val manager = nsdManager ?: run {+            Log.status(TAG, "NsdManager unavailable - this TV cannot announce itself")+            return+        }+        unadvertise()+        register(manager, friendlyName, deviceId, port, gameId, attempt = 1)+    }++    /**+     * Register the [attempt]th candidate instance name, retrying under a numbered variant when the+     * platform reports a conflict. Only the mDNS instance name varies - TXT `fn` always carries+     * [friendlyName], which is what the phone displays, so renaming is invisible to the user.+     */+    private fun register(+        manager: NsdManager,+        friendlyName: String,+        deviceId: String,+        port: Int,+        gameId: String,+        attempt: Int,+    ) {+        val issuedAt = generation+        val instanceName = instanceLabel(friendlyName, attempt)+        val serviceInfo = NsdServiceInfo().apply {+            serviceName = instanceName+            serviceType = ControllerContract.GAMEPAD_SERVICE_TYPE+            setPort(port)+            setAttribute(TXT_FRIENDLY_NAME, friendlyName)+            setAttribute(TXT_PROTOCOL_VERSION, ControllerContract.CONTROLLER_PROTOCOL_VERSION.toString())+            setAttribute(TXT_ID, deviceId)+            setAttribute(TXT_GAME_ID, gameId)+        }+        val registration = object : NsdManager.RegistrationListener {+            override fun onServiceRegistered(info: NsdServiceInfo) {+                registeredName = info.serviceName+                localNetworkBlocked = false+                Log.status(+                    TAG,+                    "advertised ${ControllerContract.GAMEPAD_SERVICE_TYPE} as ${info.serviceName} " ++                        "on port $port (game $gameId)",+                )+            }++            override fun onRegistrationFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {+                registeredName = null+                if (issuedAt != generation) return+                if (attempt >= MAX_NAME_ATTEMPTS) {+                    Log.status(+                        TAG,+                        "registration failed: $errorCode - gave up after $attempt names, " ++                            "so this TV is invisible",+                    )+                    listener = null+                    return+                }+                val next = instanceLabel(friendlyName, attempt + 1)+                Log.status(TAG, "registration failed: $errorCode for '$instanceName', retrying as '$next'")+                register(manager, friendlyName, deviceId, port, gameId, attempt + 1)+            }++            override fun onServiceUnregistered(serviceInfo: NsdServiceInfo) = Unit++            override fun onUnregistrationFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {+                Log.status(TAG, "unregistration failed: $errorCode")+            }+        }+        listener = registration+        try {+            manager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, registration)+        } catch (e: SecurityException) {+            // Android 16+ Local Network Protections. Nothing about the record is wrong; the OS+            // blocks mDNS outright until ACCESS_LOCAL_NETWORK is granted, and until then this TV is+            // simply not on anybody's list.+            Log.error(TAG, "mDNS blocked - ACCESS_LOCAL_NETWORK not granted, so this TV is invisible", e)+            localNetworkBlocked = true+            listener = null+        } catch (e: IllegalArgumentException) {+            Log.status(TAG, "registerService threw", e)+            listener = null+        } catch (e: IllegalStateException) {+            Log.status(TAG, "registerService threw", e)+            listener = null+        }+    }++    fun unadvertise() {+        generation+++        val manager = nsdManager ?: return+        val active = listener ?: return+        try {+            manager.unregisterService(active)+        } catch (_: IllegalArgumentException) {+            // Already unregistered or never registered; the fields below are cleared either way.+        } catch (_: IllegalStateException) {+            // Manager torn down; the fields below are cleared either way.+        }+        listener = null+        registeredName = null+    }+}
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.ktnew file mode 100644index 0000000000..af4741f4c0--- /dev/null+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt@@ -0,0 +1,243 @@+package com.vayunmathur.sdk.controller++import com.vayunmathur.library.log.Log+import java.util.Base64+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch++private const val TAG = "ControllerClient"++/** JVM Base64, so the pairing path round-trips in a plain JVM test. */+private object ClientBase64 {+    fun encode(bytes: ByteArray): String = Base64.getEncoder().encodeToString(bytes)+    fun decode(text: String): ByteArray? = runCatching { Base64.getDecoder().decode(text) }.getOrNull()+}++/** Where a phone stands in the join flow. */+enum class ClientState {+    IDLE,+    CONNECTING,+    /** Waiting for the user to type the six digits the TV is showing. */+    AWAITING_CODE,+    PAIRED,+    JOINED,+    FAILED,+}++/**+ * The phone side of the controller protocol: connect, pair, join, and emit input at+ * [ControllerContract.INPUT_HZ].+ *+ * The secret is generated here and sealed to the TV's bundle with the caller's [sealToBundle];+ * the SDK never touches PQC itself, so the native library stays in `:library:e2ee-p2p`. Device+ * keys persist through [loadDeviceKey]/[saveDeviceKey] keyed by host id.+ */+class ControllerClient(+    private val senderId: String,+    private val senderName: String,+    private val sealToBundle: (bundle: ByteArray, secret: ByteArray) -> ByteArray?,+    private val loadDeviceKey: (hostId: String) -> ByteArray?,+    private val saveDeviceKey: (hostId: String, key: ByteArray) -> Unit,+) {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private val _state = MutableStateFlow(ClientState.IDLE)+    val state: StateFlow<ClientState> = _state.asStateFlow()++    private val _lobby = MutableStateFlow(LobbyState())+    /** The latest lobby snapshot the TV broadcast. Replaces wholesale. */+    val lobby: StateFlow<LobbyState> = _lobby.asStateFlow()++    private var socket: ControllerSocket? = null+    private var seq = 0L++    /**+     * Connect to [host] and run the handshake. Returns the state the attempt ended in: PAIRED+     * when the code path is needed (the caller then calls [proveCode]), JOINED for a remembered+     * device, FAILED otherwise.+     */+    fun connect(host: ControllerHostInfo) {+        scope.launch { runHandshake(host) }+    }++    /** Prove the six digits on the TV screen. Only valid in [ClientState.AWAITING_CODE]. */+    fun proveCode(code: String) {+        scope.launch { runCodeProof(code) }+    }++    /** Take a seat. Only valid once paired. */+    fun join(displayName: String) {+        scope.launch {+            val socket = socket ?: return@launch+            socket.send(ControllerJoin(displayName))+            val joined = socket.receive()+            // The TV answers a JOIN by broadcasting the lobby; anything else is a refusal.+            if (joined?.message is ControllerLobby) {+                _state.value = ClientState.JOINED+                runLoop(socket)+            } else {+                _state.value = ClientState.FAILED+                close()+            }+        }+    }++    /** One input sample, with the next sequence number. Drops when not joined. */+    fun sendInput(+        buttons: Long = 0L,+        axes: List<Float> = List(AXIS_COUNT) { 0f },+        hatX: Int = 0,+        hatY: Int = 0,+        touchX: Float? = null,+        touchY: Float? = null,+    ) {+        if (_state.value != ClientState.JOINED) return+        val socket = socket ?: return+        val input = ControllerInput(+            playerId = senderId,+            seq = ++seq,+            buttons = buttons,+            axes = axes,+            hatX = hatX,+            hatY = hatY,+            touchX = touchX,+            touchY = touchY,+            clientTimestampMs = android.os.SystemClock.uptimeMillis(),+        )+        scope.launch { socket.send(ControllerInputFrame(input)) }+    }++    fun leave() {+        scope.launch {+            socket?.send(ControllerLeave())+            close()+        }+    }++    fun close() {+        runCatching { socket?.close() }+        socket = null+        _state.value = ClientState.IDLE+        scope.cancel()+    }++    private var pendingKeys: ControllerKeys? = null+    private var pendingTranscript: ControllerTranscript? = null+    private var pendingHostId: String? = null+    private var pendingWantsCode = false++    private fun runHandshake(host: ControllerHostInfo) {+        _state.value = ClientState.CONNECTING+        val socket = ControllerSocket()+        this.socket = socket+        try {+            socket.connect(host.host, host.port)+        } catch (e: Exception) {+            Log.status(TAG, "connect to ${host.friendlyName} failed", e)+            _state.value = ClientState.FAILED+            return+        }+        val transcript = ControllerTranscript()+        pendingTranscript = transcript+        pendingHostId = host.id+        val remembered = loadDeviceKey(host.id)+        val helloBody = socket.send(+            ControllerHello(+                senderName = senderName,+                senderId = senderId,+                paired = remembered != null,+            ),+        ) ?: return failed(socket)+        transcript.add(helloBody)+        val hostHello = socket.receive() ?: return failed(socket)+        transcript.add(hostHello.body)+        val hostHelloMsg = hostHello.message as? ControllerHostHello ?: return failed(socket)+        if (hostHelloMsg.version != ControllerContract.CONTROLLER_PROTOCOL_VERSION) {+            Log.status(TAG, "refusing version ${hostHelloMsg.version} from ${hostHelloMsg.hostName}")+            return failed(socket)+        }+        val bundle = ClientBase64.decode(hostHelloMsg.publicBundle) ?: return failed(socket)+        val secret = ControllerKeys.newSecret()+        val sealed = sealToBundle(bundle, secret) ?: return failed(socket)+        val keys = ControllerKeys.of(secret)+        pendingKeys = keys+        val sealedBody = socket.send(ControllerSealedSecret(ClientBase64.encode(sealed)))+            ?: return failed(socket)+        transcript.add(sealedBody)+        socket.codec.useSessionKey(keys.control)+        val required = socket.receive() ?: return failed(socket)+        val requiredMsg = required.message as? ControllerPairRequired ?: return failed(socket)+        pendingWantsCode = requiredMsg.code+        if (!requiredMsg.code && remembered != null) {+            // Remembered device: prove it now, no code on screen.+            val proof = keys.deviceProof(remembered, transcript.value())+            socket.send(ControllerPairProof(ClientBase64.encode(proof))) ?: return failed(socket)+            val ok = socket.receive() ?: return failed(socket)+            if (ok.message !is ControllerPairOk) return failed(socket)+            _state.value = ClientState.PAIRED+        } else {+            _state.value = ClientState.AWAITING_CODE+        }+    }++    private fun runCodeProof(code: String) {+        if (_state.value != ClientState.AWAITING_CODE) return+        if (!ControllerPairCode.isWellFormed(code)) return+        val socket = socket ?: return failed()+        val keys = pendingKeys ?: return failed()+        val transcript = pendingTranscript ?: return failed()+        val proof = keys.pairProof(code, transcript.value())+        socket.send(ControllerPairProof(ClientBase64.encode(proof))) ?: return failed()+        val ok = socket.receive() ?: return failed()+        val okMsg = ok.message as? ControllerPairOk ?: run {+            _state.value = ClientState.AWAITING_CODE+            return+        }+        okMsg.deviceKey?.let { ClientBase64.decode(it)?.let { key ->+            pendingHostId?.let { saveDeviceKey(it, key) }+        } }+        _state.value = ClientState.PAIRED+    }++    private fun runLoop(socket: ControllerSocket) {+        scope.launch {+            launch {+                // The heartbeat mirror: PING while joined, so a quiet lobby still produces traffic+                // inside the host's 60 s read bound. State-guarded, so it ends with the session+                // rather than pinging a dead socket.+                while (_state.value == ClientState.JOINED) {+                    kotlinx.coroutines.delay(ControllerContract.PING_INTERVAL_MS)+                    if (_state.value == ClientState.JOINED) socket.send(ControllerPing)+                }+            }+            while (true) {+                val received = socket.receive() ?: break+                when (val msg = received.message) {+                    is ControllerLobby -> _lobby.value = msg.lobby+                    is ControllerRumble -> onRumble(msg.rumble)+                    is ControllerPing -> socket.send(ControllerPing)+                    is ControllerBye -> break+                    else -> Log.status(TAG, "unexpected ${msg::class.simpleName} from host")+                }+            }+            _state.value = ClientState.IDLE+        }+    }++    /** Renders [RumbleFeedback] on the vibrator. Set by the hosting app; the default logs. */+    var onRumble: (RumbleFeedback) -> Unit = { rumble ->+        Log.status(TAG, "rumble ${rumble.durationMs}ms")+    }++    private fun failed(socket: ControllerSocket? = this.socket) {+        runCatching { socket?.close() }+        _state.value = ClientState.FAILED+    }+}
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerContract.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerContract.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerContract.ktnew file mode 100644index 0000000000..17708e7561--- /dev/null+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerContract.kt@@ -0,0 +1,60 @@+package com.vayunmathur.sdk.controller++/**+ * The wire contract for the generic phone-as-controller protocol.+ *+ * Kart-agnostic by design: buttons are a bitmask, sticks are normalized axes, and nothing here+ * names a kart, a track, or an item. A future TV game reuses this SDK by assigning its own+ * meaning to the same buttons and axes.+ *+ * Transport: TCP, JSON frames, 20-30 Hz input cadence. UDP later is a transport swap: [seq] and+ * [clientTimestampMs]/[serverTimestampMs] plus idempotent apply are reserved from v1 so the+ * sequence/snapshot discipline does not have to be reinvented.+ */+object ControllerContract {++    /**+     * The protocol version in every [ControllerHello] and [ControllerHostHello].+     *+     * Checked on both sides and refused on mismatch, rather than negotiated down. Two of our own+     * builds that disagree about the wire format are a bug to fix, not a compatibility matrix to+     * maintain - both halves ship from this repo at the same version.+     */+    const val CONTROLLER_PROTOCOL_VERSION = 1++    /** The mDNS service type the TV registers and phones browse for. `_macast._tcp` is untouched. */+    const val GAMEPAD_SERVICE_TYPE = "_gamepad._tcp"++    /**+     * How often a connected phone emits input while it has anything to say.+     *+     * 30 Hz keeps a 60 Hz tick fed every other frame; the host interpolates between samples rather+     * than stepping.+     */+    const val INPUT_HZ = 30++    /**+     * Per-player inbound rate limit, in messages per second.+     *+     * A well-behaved phone sends [INPUT_HZ]; 40 leaves headroom for jitter without letting a+     * faulty or hostile client flood the tick. Over the limit, the host drops rather than applies.+     */+    const val MAX_INPUT_PER_SECOND = 40++    /**+     * How many player slots the host offers.+     *+     * Four plays a full Kart grid with room for AI; eight is the ceiling before the lobby UI and+     * the tick budget both get silly.+     */+    const val MAX_PLAYERS = 8++    /**+     * How often each end says PING while a session is open.+     *+     * A read timeout is the only liveness check either end has, and it cannot tell a quiet lobby+     * from a dead one. Both ends echo PING, so a session with no input and no lobby change still+     * produces traffic well inside the 60 s read bound - even while a human is reading six digits.+     */+    const val PING_INTERVAL_MS = 20_000L+}
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.ktnew file mode 100644index 0000000000..6208bedb20--- /dev/null+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerDiscovery.kt@@ -0,0 +1,194 @@+package com.vayunmathur.sdk.controller++import android.content.Context+import android.net.nsd.NsdManager+import android.net.nsd.NsdServiceInfo+import com.vayunmathur.library.log.Log+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.callbackFlow+import kotlinx.coroutines.flow.update++private const val TAG = "ControllerDiscovery"++/** Friendly name, e.g. "Living Room TV". */+private const val TXT_FRIENDLY_NAME = "fn"++/** The protocol version the host speaks. */+private const val TXT_PROTOCOL_VERSION = "pv"++/** The host's own stable id. Stable across renames, unlike the instance name. */+private const val TXT_ID = "id"++/** The game this lobby is for, e.g. "kart" - informational, so a phone can label what it found. */+private const val TXT_GAME_ID = "gameId"++/** One TV hosting a controller lobby, as resolved from mDNS. */+data class ControllerHostInfo(+    val id: String,+    val instanceName: String,+    val friendlyName: String,+    val host: String,+    val port: Int,+    val protocolVersion: Int,+    val gameId: String,+)++/**+ * mDNS discovery of controller hosts on the LAN.+ *+ * Browse-only - nothing is advertised, because a phone is not itself a host. The shape is+ * `:cast`'s `CastDiscoveryManager` retargeted at [ControllerContract.GAMEPAD_SERVICE_TYPE]:+ * the `callbackFlow` + `DiscoveryListener` pairing, `_hosts.update {}` because resolve callbacks+ * land on several threads, and [localNetworkBlocked] - on Android 16 a missing+ * `ACCESS_LOCAL_NETWORK` grant makes `discoverServices` throw `SecurityException`, and that is+ * otherwise indistinguishable from an empty network.+ */+class ControllerDiscovery(context: Context) {++    private val nsdManager: NsdManager? =+        context.getSystemService(Context.NSD_SERVICE) as? NsdManager++    private var discoveryListener: NsdManager.DiscoveryListener? = null++    private val _hosts = MutableStateFlow<List<ControllerHostInfo>>(emptyList())+    val hosts: StateFlow<List<ControllerHostInfo>> = _hosts.asStateFlow()++    /** True when the platform refused the browse, not when the network is simply empty. */+    private val _localNetworkBlocked = MutableStateFlow(false)+    val localNetworkBlocked: StateFlow<Boolean> = _localNetworkBlocked.asStateFlow()++    /**+     * Browse [ControllerContract.GAMEPAD_SERVICE_TYPE] and emit each resolved host.+     *+     * Cancelling the collection stops the browse. Hosts also accumulate in [hosts], which is what+     * the list observes, so a caller that only wants the state can collect and drop.+     */+    fun discover(): Flow<ControllerHostInfo> = callbackFlow {+        val manager = nsdManager ?: run {+            Log.status(TAG, "NsdManager unavailable - cannot browse for hosts")+            close()+            return@callbackFlow+        }+        val listener = object : NsdManager.DiscoveryListener {+            override fun onDiscoveryStarted(serviceType: String) {+                _localNetworkBlocked.value = false+            }++            override fun onServiceFound(service: NsdServiceInfo) {+                try {+                    manager.resolveService(service, object : NsdManager.ResolveListener {+                        override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {+                            Log.status(TAG, "resolve failed for ${info.serviceName}: $errorCode")+                        }++                        override fun onServiceResolved(info: NsdServiceInfo) {+                            val host = toHostInfo(info) ?: return+                            trySend(host)+                            // update, not value =: resolve callbacks arrive on several threads+                            // and a read-modify-write would drop hosts found at once.+                            _hosts.update { merge(it, host) }+                        }+                    })+                } catch (e: SecurityException) {+                    Log.status(TAG, "resolveService threw for ${service.serviceName}", e)+                } catch (e: IllegalArgumentException) {+                    Log.status(TAG, "resolveService threw for ${service.serviceName}", e)+                }+            }++            override fun onServiceLost(service: NsdServiceInfo) {+                // Only the instance name is available here, so match on it rather than on the+                // UUID; the two are one-to-one for the lifetime of a registration.+                val name = service.serviceName ?: return+                _hosts.update { hosts -> hosts.filterNot { it.instanceName == name } }+            }++            override fun onDiscoveryStopped(serviceType: String) = Unit++            override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) {+                Log.status(TAG, "startDiscovery failed: $errorCode")+                close()+            }++            override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {+                Log.status(TAG, "stopDiscovery failed: $errorCode")+            }+        }+        discoveryListener = listener+        try {+            manager.discoverServices(+                ControllerContract.GAMEPAD_SERVICE_TYPE,+                NsdManager.PROTOCOL_DNS_SD,+                listener,+            )+        } catch (e: SecurityException) {+            // Android 16+ Local Network Protections. Nothing is wrong with the request; the+            // OS blocks mDNS outright until ACCESS_LOCAL_NETWORK is granted.+            Log.error(TAG, "mDNS browse blocked - ACCESS_LOCAL_NETWORK not granted", e)+            _localNetworkBlocked.value = true+            discoveryListener = null+            close()+            return@callbackFlow+        } catch (e: IllegalArgumentException) {+            Log.status(TAG, "discoverServices threw", e)+            discoveryListener = null+            close(e)+            return@callbackFlow+        }+        awaitClose {+            try {+                discoveryListener?.let { manager.stopServiceDiscovery(it) }+            } catch (_: IllegalArgumentException) {+            } catch (_: SecurityException) {+            }+            discoveryListener = null+        }+    }++    fun clear() {+        _hosts.value = emptyList()+    }++    private fun textAttribute(info: NsdServiceInfo, key: String): String? =+        runCatching { info.attributes[key]?.toString(Charsets.UTF_8) }+            .getOrNull()+            ?.takeIf { it.isNotBlank() }++    /**+     * Turn a resolved record into a [ControllerHostInfo], or null when it is not usable.+     *+     * A host and a port are both mandatory - the TV binds an ephemeral control port, so there is no+     * sensible default to fall back to. The name has one, because a TV with an odd TXT record is+     * still joinable.+     */+    private fun toHostInfo(info: NsdServiceInfo): ControllerHostInfo? {+        val host = info.host?.hostAddress ?: return null+        val instance = info.serviceName ?: return null+        val port = info.port.takeIf { it > 0 } ?: return null+        return ControllerHostInfo(+            id = textAttribute(info, TXT_ID) ?: instance,+            instanceName = instance,+            friendlyName = textAttribute(info, TXT_FRIENDLY_NAME) ?: instance,+            host = host,+            port = port,+            protocolVersion = textAttribute(info, TXT_PROTOCOL_VERSION)?.toIntOrNull() ?: 0,+            gameId = textAttribute(info, TXT_GAME_ID).orEmpty(),+        )+    }++    /**+     * Replace by [ControllerHostInfo.id] rather than append.+     *+     * A host re-announces itself whenever its record changes, and every announcement resolves, so+     * appending would show the same TV three times.+     */+    private fun merge(current: List<ControllerHostInfo>, host: ControllerHostInfo): List<ControllerHostInfo> {+        val index = current.indexOfFirst { it.id == host.id }+        if (index < 0) return current + host+        return current.toMutableList().apply { this[index] = host }+    }+}
a/sdk/controller/src/main/java/com/vayunmathur/sdk/contro
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/contro

Diff truncated.