kart: native 3D engine, hub Play on TV, PQC identity
- Commit
b26d86edb24f0f55728addb47b375c0376e54281- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-18 03:14 UTC (1 month ago)
- Parents
239d4b1
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 090973b880..3e0122032a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2432,6 +2432,17 @@ dependencies = [ "elliptic-curve 0.13.8", ] +[[package]]+name = "kart_engine"+version = "0.1.0"+dependencies = [+ "ash",+ "glam",+ "jni",+ "serde",+ "serde_json",+]+ [[package]] name = "keccak" version = "0.1.6"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex fd83498e9d..8a945cbfbc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -24,6 +24,7 @@ members = [ "web/src/main/rust", "share/src/main/rust", "games/voxels/src/main/rust",+ "games/kart/src/main/rust", "code/src/main/rust", "library/tilecodec/src/main/rust", "scripts/maps/dem_ingest",
games/hub/build.gradle.kts
diff --git a/games/hub/build.gradle.kts b/games/hub/build.gradle.ktsindex a8a5fd1fae..8f913bd555 100644--- a/games/hub/build.gradle.kts+++ b/games/hub/build.gradle.kts@@ -20,5 +20,10 @@ dependencies { implementation(project(":library:ui")) implementation(project(":library:room")) implementation(project(":sdk:games"))+ // "Play on TV": the generic phone-as-controller SDK (pad UI + discovery ++ // client) plus PQC sealing for the handshake's session secret.+ implementation(project(":sdk:controller"))+ implementation(project(":library:e2ee-p2p"))+ implementation(libs.androidx.datastore.preferences) implementRoom(libs) }
games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlindex 66622e86c7..3eb70e6bbc 100644--- a/games/hub/src/main/AndroidManifest.xml+++ b/games/hub/src/main/AndroidManifest.xml@@ -8,6 +8,12 @@ android:name="com.vayunmathur.games.hub.permission.WRITE_GAME_DATA" android:protectionLevel="signature" /> + <!-- "Play on TV": TCP control + mDNS discovery for the phone-as-controller session. -->+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />+ <uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />+ <uses-permission android:name="android.permission.VIBRATE" />+ <queries> <package android:name="com.vayunmathur.games.chess" /> <package android:name="com.vayunmathur.games.pipes" />
games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.ktindex d24357b0b9..20b08a3575 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt@@ -19,6 +19,7 @@ import com.vayunmathur.games.hub.ui.screens.ActivityFeedScreen import com.vayunmathur.games.hub.ui.screens.DashboardPage import com.vayunmathur.games.hub.ui.screens.GameDetailScreen import com.vayunmathur.games.hub.ui.screens.GamesListPage+import com.vayunmathur.games.hub.ui.screens.PlayOnTvScreen import com.vayunmathur.games.hub.ui.screens.ProfilePage import com.vayunmathur.games.hub.ui.screens.SettingsScreen import com.vayunmathur.games.hub.viewmodel.GameHubViewModel@@ -53,6 +54,8 @@ sealed interface MainRoute : NavKey { @Serializable data class AchievementsForGame(val gameId: String) : MainRoute @Serializable data object Activity : MainRoute @Serializable data object Settings : MainRoute+ /** The phone-as-controller screen (hub hosts the SDK ControllerPad). */+ @Serializable data object PlayOnTv : MainRoute } @Composable@@ -88,6 +91,9 @@ fun HubNavigation( backStack = backStack ) }+ entry<MainRoute.PlayOnTv> {+ PlayOnTvScreen(backStack = backStack)+ } } }
games/hub/src/main/java/com/vayunmathur/games/hub/network/PlayOnTvSession.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/network/PlayOnTvSession.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/network/PlayOnTvSession.ktnew file mode 100644index 0000000000..d80401d010--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/network/PlayOnTvSession.kt@@ -0,0 +1,213 @@+package com.vayunmathur.games.hub.network++import android.content.Context+import android.os.Build+import android.os.VibrationEffect+import android.os.VibratorManager+import android.util.Base64+import androidx.datastore.preferences.core.byteArrayPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.e2ee.Pqc+import com.vayunmathur.library.log.Log+import com.vayunmathur.sdk.controller.ClientState+import com.vayunmathur.sdk.controller.ControllerClient+import com.vayunmathur.sdk.controller.ControllerDiscovery+import com.vayunmathur.sdk.controller.ControllerHostInfo+import com.vayunmathur.sdk.controller.ControllerPadState+import com.vayunmathur.sdk.controller.RumbleFeedback+import java.util.UUID+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking++private const val TAG = "PlayOnTvSession"++private val Context.controllerStore by preferencesDataStore(name = "hub_controller")++/**+ * The hub's "Play on TV" session: the phone side of the generic controller protocol.+ *+ * Owns a [ControllerDiscovery] (browse `_gamepad._tcp`) and a [ControllerClient] (connect, pair,+ * join, emit), and reduces their flows into one [ControllerPadState] the screen renders. Rumble+ * from the TV plays on the vibrator; the default rumble display in `ControllerPad` shows the+ * duration alongside.+ *+ * Secrets follow the same rule as the kart TV host: the per-TV device keys live in their own+ * `hub_controller` DataStore file, NOT in the shared `datastore_default` that [com.vayunmathur.games.hub.util.AppBackupAgent]+ * ships to cloud. A restored backup must not silently inherit this phone's pairings.+ * Sealing to the TV's bundle is plain `Pqc.encryptTo` (the cast `SecretSealing` shape, without+ * depending on `:cast:protocol`); the phone holds no long-term PQC identity of its own — the+ * session secret is fresh per connection and the device key is the only thing persisted.+ */+class PlayOnTvSession(context: Context) {++ private val appContext = context.applicationContext++ private val discovery = ControllerDiscovery(appContext)++ /**+ * This phone's stable sender id. The TV keys remembered devices by it, so a fresh id every+ * screen-open would force the pair-code path every time. Read synchronously: a single+ * DataStore file read, once per screen open, off the composition hot path (the screen+ * `remember`s the session, which blocks composition for ~ms only on a cold file read).+ */+ private val senderId: String = runBlocking(Dispatchers.IO) {+ val stored = appContext.controllerStore.data+ .map { it[byteArrayPreferencesKey(KEY_SENDER)] }+ .first()?.let { Base64.encodeToString(it, Base64.NO_WRAP) }+ if (stored != null) return@runBlocking stored+ val fresh = UUID.randomUUID().toString()+ runCatching {+ appContext.controllerStore.edit {+ it[byteArrayPreferencesKey(KEY_SENDER)] = fresh.toByteArray(Charsets.UTF_8)+ }+ }+ fresh+ }++ private val client = ControllerClient(+ senderId = senderId,+ senderName = Build.MODEL ?: "Phone",+ sealToBundle = { bundle, secret ->+ runCatching { Pqc.encryptTo(bundle, secret) }.getOrNull()+ },+ loadDeviceKey = { hostId -> loadDeviceKey(hostId) },+ saveDeviceKey = { hostId, key -> saveDeviceKey(hostId, key) },+ )++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)++ private val _lastRumble = MutableStateFlow<RumbleFeedback?>(null)++ /** The pad state the screen renders. Collect with the lifecycle. */+ val state: StateFlow<ControllerPadState> = combine(+ client.state,+ discovery.hosts,+ discovery.localNetworkBlocked,+ client.lobby,+ _lastRumble,+ ) { clientState, hosts, blocked, lobby, rumble ->+ ControllerPadState(+ clientState = clientState,+ hosts = hosts,+ localNetworkBlocked = blocked,+ lobby = lobby,+ lastRumble = rumble,+ )+ }.stateIn(scope, SharingStarted.Eagerly, ControllerPadState())++ private var discoverJob: Job? = null++ init {+ client.onRumble = { rumble ->+ _lastRumble.value = rumble+ playRumble(rumble)+ }+ startDiscovery()+ }++ /** Connect to [host]. The client's handshake moves IDLE → CONNECTING → AWAITING_CODE/PAIRED. */+ fun connect(host: ControllerHostInfo) {+ client.connect(host)+ }++ /** Prove the six digits on the TV screen. Only valid in [ClientState.AWAITING_CODE]. */+ fun proveCode(code: String) {+ client.proveCode(code)+ }++ /** Take a seat. Only valid once paired. */+ fun join(displayName: String) {+ client.join(displayName)+ }++ /** One input sample at the pad's emit cadence. Drops when not joined. */+ fun sendInput(buttons: Long, axes: List<Float>, hatX: Int, hatY: Int) {+ client.sendInput(buttons = buttons, axes = axes, hatX = hatX, hatY = hatY)+ }++ /** Leave the lobby. The client returns to IDLE. */+ fun leave() {+ client.leave()+ }++ /**+ * Re-run discovery. Cancels the in-flight browse first (a second concurrent `discover()`+ * would register a second NSD listener and double-report every TV), clears the list so gone+ * TVs disappear, and starts over.+ */+ fun rescan() {+ discovery.clear()+ startDiscovery()+ }++ /** Tear down: close the client and stop the browse. Called when the screen leaves. */+ fun close() {+ discoverJob?.cancel()+ discoverJob = null+ runCatching { client.close() }+ scope.cancel()+ }++ private fun startDiscovery() {+ discoverJob?.cancel()+ discoverJob = scope.launch(Dispatchers.IO) {+ discovery.discover().collectLatest { /* hosts accumulate in discovery.hosts */ }+ }+ }++ private fun playRumble(rumble: RumbleFeedback) {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return+ val manager = runCatching {+ appContext.getSystemService(VibratorManager::class.java)+ }.getOrNull() ?: return+ val vibrator = runCatching { manager.defaultVibrator }.getOrNull() ?: return+ val duration = rumble.durationMs.coerceIn(1, 1_000).toLong()+ val amplitude = (rumble.highFreq.coerceIn(0f, 1f) * 255).toInt().coerceIn(1, 255)+ runCatching {+ vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))+ }.onFailure { e -> Log.status(TAG, "rumble failed", e) }+ }++ private fun loadDeviceKey(hostId: String): ByteArray? =+ runCatching {+ runBlocking(Dispatchers.IO) {+ appContext.controllerStore.data+ .map { it[byteArrayPreferencesKey(deviceKeyName(hostId))] }+ .first()+ }+ }.getOrNull()++ private fun saveDeviceKey(hostId: String, key: ByteArray) {+ // Fire-and-forget: pairing already succeeded; persistence only affects the NEXT session.+ CoroutineScope(Dispatchers.IO).launch {+ runCatching {+ // Refuse to persist a degenerate key: an empty key proves nothing and would+ // wedge the next session into the no-code path against a TV that forgot us.+ if (key.isEmpty()) return@launch+ appContext.controllerStore.edit {+ it[byteArrayPreferencesKey(deviceKeyName(hostId))] = key+ }+ }+ }+ }++ private fun deviceKeyName(hostId: String): String = "hub_device_$hostId"++ private companion object {+ const val KEY_SENDER = "hub_sender_id"+ }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.ktindex 86c11f5909..f8e909e8b2 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt@@ -39,6 +39,7 @@ import com.vayunmathur.games.hub.viewmodel.GameHubViewModel import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.IconNavigation import com.vayunmathur.library.ui.MaterialTheme@@ -51,6 +52,9 @@ import com.vayunmathur.library.util.sharedContainer import androidx.compose.ui.res.stringResource import com.vayunmathur.games.hub.R +/** The game id whose detail offers the hub-hosted phone controller. */+private const val KART_GAME_ID = "kart"+ @Composable fun GameDetailScreen( gameId: String,@@ -100,6 +104,10 @@ fun GameDetailScreen( } } item { Button(onClick = { launchGame(context, g) }, enabled = isInstalled, modifier = Modifier.fillMaxWidth()) { Text(if (isInstalled) stringResource(R.string.play_1, g.displayName) else stringResource(R.string.not_installed)) } }+ // Kart runs on TV with phones as controllers: the hub hosts the controller pad.+ if (gameId == KART_GAME_ID) {+ item { OutlinedButton(onClick = { backStack.add(MainRoute.PlayOnTv) }, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.play_on_tv)) } }+ } item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { StatCard(label = stringResource(com.vayunmathur.games.hub.R.string.playtime), value = formatPlaytime(g.totalPlaytimeMs), modifier = Modifier.weight(1f)) StatCard(label = stringResource(com.vayunmathur.games.hub.R.string.sessions), value = "${sessions.size}", modifier = Modifier.weight(1f))
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/PlayOnTvScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/PlayOnTvScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/PlayOnTvScreen.ktnew file mode 100644index 0000000000..1fc8cbfaf3--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/PlayOnTvScreen.kt@@ -0,0 +1,53 @@+package com.vayunmathur.games.hub.ui.screens++import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.MainRoute+import com.vayunmathur.games.hub.network.PlayOnTvSession+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.sdk.controller.ControllerPad++/**+ * "Play on TV": this phone as a controller for a TV-hosted game.+ *+ * The session owns discovery + client + rumble and reduces them to one+ * [com.vayunmathur.sdk.controller.ControllerPadState]; this screen only binds+ * it to the reusable SDK [ControllerPad] and tears the session down on leave.+ * The callbacks map one-to-one onto the session (`onConnect` → `connect`,+ * `onProveCode` → `proveCode`, …), exactly as the SDK's pad contract documents.+ */+@Composable+fun PlayOnTvScreen(+ backStack: NavBackStack<MainRoute>,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val session = remember { PlayOnTvSession(context) }+ DisposableEffect(session) { onDispose { session.close() } }+ val state by session.state.collectAsStateWithLifecycle()++ AppScaffold(+ title = "Play on TV",+ backStack = backStack,+ scrollBehavior = appBarScrollBehavior(),+ ) { padding ->+ ControllerPad(+ state = state,+ onConnect = session::connect,+ onProveCode = session::proveCode,+ onJoin = session::join,+ onInput = session::sendInput,+ onLeave = session::leave,+ onRescan = session::rescan,+ modifier = modifier.padding(padding),+ )+ }+}
games/hub/src/main/res/values/strings.xml
diff --git a/games/hub/src/main/res/values/strings.xml b/games/hub/src/main/res/values/strings.xmlindex 7dea28d1fd..a0f8fa18b2 100644--- a/games/hub/src/main/res/values/strings.xml+++ b/games/hub/src/main/res/values/strings.xml@@ -124,4 +124,7 @@ <string name="best_streak">Best streak</string> <string name="last">Last</string> <string name="search_games">Search games</string>++ <!-- Kart detail: opens the hub-hosted phone controller for the TV game. -->+ <string name="play_on_tv">Play on TV</string> </resources>
games/kart/build.gradle.kts
diff --git a/games/kart/build.gradle.kts b/games/kart/build.gradle.ktsindex 15cd393b44..9c4a8de0ac 100644--- a/games/kart/build.gradle.kts+++ b/games/kart/build.gradle.kts@@ -15,9 +15,25 @@ android { } } +androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++// Native 3D racer engine (Sunset Oval track, kart physics, chase cam, items ++// AI). Same arrangement as games/voxels: the crate builds into rustJniLibs and+// KartNative.isAvailable gates every call, so devices without the .so run the+// placeholder race. Listing images are hand-captured (Layoutlib can't render+// the Vulkan surface); see the plan's verification notes.+rustNativeLib("kart_engine", "kart")+ dependencies { implementation(project(":sdk:games")) implementation(project(":sdk:controller")) implementation(project(":library:work"))+ implementation(project(":library:e2ee-p2p")) implementation(libs.androidx.datastore.preferences) }
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.ktindex 0b3532bcfe..801267e6d6 100644--- 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.kt@@ -15,8 +15,11 @@ 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+import kotlinx.coroutines.runBlocking private const val TAG = "KartHost" private const val PREFS = "kart_host"@@ -28,62 +31,81 @@ private const val KEY_HOST_ID = "host_id" * * 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.+ * half. When [pairingStore] is present, device keys and the host id live in the same non-backed-up+ * file as the identity, so a restored backup can neither impersonate this TV nor silently inherit+ * its paired phones; without it (tests) they fall back to private prefs. Either way the host id+ * is a stable id 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.+ *+ * Construction is synchronous (the lobby/idle flows exist from `init`), but the [ControllerHost]+ * itself is built in [start] once the suspend host id resolves — before that the lobby reads+ * empty and handshakes cannot arrive because nothing is advertised yet. */ class KartHost( private val context: Context, private val publicBundle: () -> ByteArray?, private val unsealSecret: (ByteArray) -> ByteArray?,+ private val pairingStore: KartPairingStore? = null, ) { 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- }+ private var inner: ControllerHost? = null - val host = ControllerHost(- gameId = "kart",- hostId = hostId,- providePublicBundle = publicBundle,- unsealSecret = unsealSecret,- loadDeviceKey = ::loadDeviceKey,- saveDeviceKey = ::saveDeviceKey,- )+ private val _lobby = MutableStateFlow(LobbyState(gameId = "kart"))+ /** Mirrors the inner host's lobby once [start] builds it; empty before that. */+ val lobby: StateFlow<LobbyState> = _lobby.asStateFlow() - val lobby: StateFlow<LobbyState> = host.lobby- val inputs: StateFlow<Map<String, ControllerInput>> = host.inputs+ private val _inputs = MutableStateFlow<Map<String, ControllerInput>>(emptyMap())+ /** Mirrors the inner host's inputs once [start] builds it; empty before that. */+ val inputs: StateFlow<Map<String, ControllerInput>> = _inputs.asStateFlow()++ /** The inner host, for the race loop. Null until [start]. */+ val host: ControllerHost?+ get() = inner private val advertiser = ControllerAdvertiser(context) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private var server: ServerSocket? = null+ private var started = false - /** The pair code on screen, if a phone is mid-handshake. */- val pairingCode: String? get() = host.pairingCode+ /** The pair code on screen, if a phone is mid-handshake. Null until [start]. */+ val pairingCode: String? get() = inner?.pairingCode /**- * Start advertising and accepting. Safe to call repeatedly; restarts the accept loop rather- * than stacking a second one.+ * Resolve the host id, build the [ControllerHost], and start advertising + accepting. Safe to+ * call repeatedly; the second call is a no-op rather than a second lobby. */- fun start() {- scope.launch { acceptLoop() }+ suspend fun start() {+ if (started) return+ started = true+ val hostId = pairingStore?.deviceId() ?: legacyHostId()+ val host = ControllerHost(+ gameId = "kart",+ hostId = hostId,+ providePublicBundle = publicBundle,+ unsealSecret = unsealSecret,+ loadDeviceKey = ::loadDeviceKey,+ saveDeviceKey = ::saveDeviceKey,+ )+ inner = host+ scope.launch { host.lobby.collect { _lobby.value = it } }+ scope.launch { host.inputs.collect { _inputs.value = it } }+ scope.launch { acceptLoop(hostId, host) } } fun stop() { runCatching { server?.close() } server = null advertiser.unadvertise()- host.close()+ inner?.close()+ inner = null scope.cancel() } - private fun acceptLoop() {+ private fun acceptLoop(hostId: String, host: ControllerHost) { val server = try { ServerSocket(0).also { this.server = it } } catch (e: Exception) {@@ -109,12 +131,26 @@ class KartHost( } } - private fun loadDeviceKey(senderId: String): ByteArray? =- prefs.getString(deviceKeyOf(senderId), null)?.let {+ private fun legacyHostId(): String = prefs.getString(KEY_HOST_ID, null) ?: run {+ val fresh = java.util.UUID.randomUUID().toString()+ prefs.edit { putString(KEY_HOST_ID, fresh) }+ fresh+ }++ private fun loadDeviceKey(senderId: String): ByteArray? {+ pairingStore?.let {+ return runBlocking(Dispatchers.IO) { it.deviceKey(senderId) }+ }+ return prefs.getString(deviceKeyOf(senderId), null)?.let { runCatching { Base64.decode(it, Base64.NO_WRAP) }.getOrNull() }+ } private fun saveDeviceKey(senderId: String, key: ByteArray) {+ pairingStore?.let {+ runBlocking(Dispatchers.IO) { it.remember(senderId, key) }+ return+ } prefs.edit { putString(deviceKeyOf(senderId), Base64.encodeToString(key, Base64.NO_WRAP)) } }
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.ktindex ba52e12df4..bb8d5173f2 100644--- 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.kt@@ -8,16 +8,23 @@ 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.+ * Native calls are no-ops behind [isAvailable] = false (no `libkart_engine`+ * on this device), and the game runs on [com.vayunmathur.games.kart.domain.PlaceholderRace]+ * instead. The signatures below are the contract the Rust engine implements,+ * so the Kotlin side never changes shape when native lands - only this object's body does.+ *+ * Surface lifecycle mirrors voxels: the view calls surfaceCreated/Changed/+ * Destroyed, the engine spawns its own 60 Hz render thread and ticks the race+ * there. Drive samples feed per seat per tick; the race itself (seats, AI,+ * items, laps) is started with the grid order and read back as standings JSON+ * for the HUD, so the placeholder and native stay swappable. */ @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")+ nativeInit() Log.status("KartNative", "libkart_engine loaded") true } catch (t: Throwable) {@@ -25,6 +32,15 @@ object KartNative { false } + /**+ * Start (or restart) the native race. `playerIds` is the grid in seat order;+ * the engine fills the rest with AI. No-op without the library.+ */+ fun startRace(playerIds: List<String>) {+ if (!isAvailable) return+ nativeStartRace(playerIds.joinToString(","))+ }+ /** 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@@ -44,8 +60,35 @@ object KartNative { /** Snapshot for the HUD/standings: JSON `[{player,lap,progress,place}]`. */ fun getStandingsJson(): String = if (isAvailable) nativeGetStandingsJson() else "[]" + /** Surface lifecycle, called by KartSurfaceView. No-ops without the library. */+ fun surfaceCreated(surface: android.view.Surface) {+ if (!isAvailable) return+ nativeSurfaceCreated(surface)+ }++ fun surfaceChanged(width: Int, height: Int) {+ if (!isAvailable) return+ nativeSurfaceChanged(width, height)+ }++ fun surfaceDestroyed() {+ if (!isAvailable) return+ nativeSurfaceDestroyed()+ }++ fun onDestroy() {+ if (!isAvailable) return+ nativeOnDestroy()+ }++ private external fun nativeInit(): Boolean+ private external fun nativeStartRace(playerIdsCsv: String) 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+ private external fun nativeSurfaceCreated(surface: android.view.Surface)+ private external fun nativeSurfaceChanged(width: Int, height: Int)+ private external fun nativeSurfaceDestroyed()+ private external fun nativeOnDestroy() }
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.ktnew file mode 100644index 0000000000..0b66c0b313--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartPairingStore.kt@@ -0,0 +1,78 @@+package com.vayunmathur.games.kart.platform++import android.content.Context+import androidx.datastore.preferences.core.byteArrayPreferencesKey+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.stringPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.e2ee.E2eeKeyStore+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.map++private val Context.kartIdentityStore by preferencesDataStore(name = "kart_identity")++/**+ * The TV's long-term secrets: its own ML-KEM identity, and one device key per paired phone.+ *+ * Follows the cast/tv `PairingStore` shape (an [E2eeKeyStore] for+ * `PqcIdentity.loadOrCreate`, plus remembered device keys), with one deliberate+ * difference: keys live in their own `kart_identity` DataStore file, NOT in the+ * shared `datastore_default` that [AppBackupAgent] ships to cloud. Restoring+ * identity keys onto a different TV would let that TV impersonate this one to+ * an already-paired phone, with no code shown to give it away — so the file+ * stays off the backup list by living outside `datastoreNames`.+ *+ * Suspend getters throughout (never the snapshot): this is read on a cold+ * lobby start, where an eagerly-mirrored snapshot has not hydrated.+ */+class KartPairingStore(private val context: Context) : E2eeKeyStore {++ // --- E2eeKeyStore, for PqcIdentity.loadOrCreate ---++ override suspend fun getBytes(name: String): ByteArray? =+ context.kartIdentityStore.data.map { it[byteArrayPreferencesKey("kart_$name")] }.first()++ override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+ context.kartIdentityStore.edit {+ val key = byteArrayPreferencesKey("kart_$name")+ if (onlyIfAbsent && it.contains(key)) return@edit+ it[key] = value+ }+ }++ // --- remembered phones ---++ /** The device key for [senderId], or null when this phone has never paired. */+ suspend fun deviceKey(senderId: String): ByteArray? =+ context.kartIdentityStore.data.map { it[byteArrayPreferencesKey(deviceKeyName(senderId))] }.first()++ suspend fun remember(senderId: String, deviceKey: ByteArray) {+ context.kartIdentityStore.edit { it[byteArrayPreferencesKey(deviceKeyName(senderId))] = deviceKey }+ }++ /**+ * This TV's own stable id, generated once.+ *+ * Not derived from the ML-KEM bundle: the id is published in the mDNS+ * record, and a public identifier derived from a key is one more thing to+ * have to think about. A random id says nothing.+ */+ suspend fun deviceId(): String {+ val existing = context.kartIdentityStore.data.map { it[stringPreferencesKey(KEY_DEVICE_ID)] }.first()+ if (existing != null) return existing+ val id = java.util.UUID.randomUUID().toString()+ context.kartIdentityStore.edit {+ if (!it.contains(stringPreferencesKey(KEY_DEVICE_ID))) {+ it[stringPreferencesKey(KEY_DEVICE_ID)] = id+ }+ }+ // Re-read, so two hosts starting at once agree on which id won.+ return context.kartIdentityStore.data.map { it[stringPreferencesKey(KEY_DEVICE_ID)] }.first() ?: id+ }++ private fun deviceKeyName(senderId: String): String = "kart_paired_$senderId"++ private companion object {+ const val KEY_DEVICE_ID = "kart_device_id"+ }+}
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.ktindex 6dd800c483..12b823f30f 100644--- 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.kt@@ -60,14 +60,30 @@ class KartViewModel(application: Application) : AndroidViewModel(application), } /**- * 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.+ * The TV lobby, backed by a real post-quantum identity.+ *+ * The identity loads off the main thread (keygen on first run touches the+ * native PQC library): until it lands, [KartHost] refuses handshakes+ * cleanly — the same posture the `{ null }` scaffold had, but only for+ * the cold-start window rather than forever. The device-key persistence+ * lives in [KartPairingStore] alongside the identity, outside the backup+ * set, so a remembered phone re-pairs silently across restarts. */+ private val pairingStore = KartPairingStore(application)++ @Volatile+ private var pqcIdentity: com.vayunmathur.e2ee.PqcIdentity? = null+ private val kartHost = KartHost( context = application,- publicBundle = { null },- unsealSecret = { null },+ publicBundle = { pqcIdentity?.publicBundle },+ unsealSecret = { sealed ->+ val identity = pqcIdentity ?: return@KartHost null+ runCatching { identity.decrypt(sealed) }+ .getOrNull()+ ?.takeIf { it.size == com.vayunmathur.sdk.controller.ControllerKeys.SECRET_BYTES }+ },+ pairingStore = pairingStore, ) private val _racePhase = MutableStateFlow<RacePhase>(RacePhase.Lobby(kartHost.lobby.value))@@ -84,7 +100,14 @@ class KartViewModel(application: Application) : AndroidViewModel(application), init { achievementsManager.checkExistingAchievements() - viewModelScope.launch { kartHost.start() }+ // Load (or mint) the PQC identity off the main thread, then open the+ // lobby. First run pays keygen; every later start reads persisted keys.+ viewModelScope.launch {+ pqcIdentity = runCatching {+ com.vayunmathur.e2ee.PqcIdentity.loadOrCreate(pairingStore, prefix = "kartTv")+ }.getOrNull()+ kartHost.start()+ } viewModelScope.launch { kartHost.lobby.collectLatest { lobby ->@@ -158,7 +181,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), // 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")+ kartHost.host?.addLocalPlayer(seat, "You") viewModelScope.launch { for (count in COUNTDOWN_SECONDS downTo 1) { _racePhase.value = RacePhase.Countdown(count)@@ -177,7 +200,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), */ fun onLocalStick(playerId: String, x: Float, y: Float) { if (_racePhase.value !is RacePhase.Racing) return- kartHost.host.onLocalInput(+ kartHost.host?.onLocalInput( com.vayunmathur.sdk.controller.ControllerInput( playerId = playerId, seq = 0L,@@ -188,22 +211,76 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** 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)+ 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)+ 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+ if (KartNative.isAvailable) {+ beginNativeRace(seat, seats)+ } else {+ beginPlaceholderRace(seat, seats)+ }+ }++ /**+ * The native race: the Rust engine owns the sim (seats, AI, items, laps) and ticks itself on+ * its own render thread; this loop only feeds inputs and polls standings for the HUD.+ */+ private fun beginNativeRace(seat: String, seats: List<String>) {+ KartNative.startRace(seats)+ kartHost.host?.startRace()+ val itemLatch = mutableMapOf<String, Boolean>()+ tickJob?.cancel()+ tickJob = viewModelScope.launch {+ while (isActive) {+ delay(TICK_MS)+ val latest = kartHost.inputs.value+ for (id in seats) {+ val sample = latest[id] ?: continue+ val control = GameInputLoop.normalize(sample)+ val index = seats.indexOf(id)+ KartNative.onDriveInput(index, control.throttle, control.steering, control.brake)+ KartNative.setDrift(index, control.drift)+ // Rising edge per seat: holding item fires once (the engine+ // consumes the edge on its next step).+ val fire = control.itemUse && itemLatch[id] != true+ itemLatch[id] = control.itemUse+ if (fire) KartNative.useItem(index)+ }+ val standings = parseStandings(KartNative.getStandingsJson())+ if (standings.isEmpty()) continue+ if (standings.any { it.lap >= RACE_LAPS }) {+ val ordered = standings.sortedBy { it.place }+ finishRace(+ winner = ordered.first().player,+ order = ordered.map { it.player },+ )+ return@launch+ }+ val ordered = standings.sortedBy { it.place }+ _racePhase.value = RacePhase.Racing(+ order = ordered.map { it.player },+ lapProgress = ordered.associate { it.player to it.progress },+ playerLap = ordered.firstOrNull { it.player == seat }?.lap ?: 0,+ totalLaps = RACE_LAPS,+ )+ }+ }+ }++ private fun beginPlaceholderRace(seat: String, seats: List<String>) { val newRace = PlaceholderRace(playerIds = seats) race = newRace- kartHost.host.startRace()+ kartHost.host?.startRace() tickJob?.cancel() tickJob = viewModelScope.launch { var lastMs = android.os.SystemClock.uptimeMillis()@@ -231,7 +308,11 @@ class KartViewModel(application: Application) : AndroidViewModel(application), } newRace.tick(dt) if (newRace.finished) {- finishRace(newRace)+ val order = newRace.leaderboard()+ finishRace(+ winner = newRace.winner() ?: order.first(),+ order = order,+ ) return@launch } val order = newRace.leaderboard()@@ -244,13 +325,10 @@ class KartViewModel(application: Application) : AndroidViewModel(application), } } }-- private fun finishRace(finished: PlaceholderRace) {+ private fun finishRace(winner: String, order: List<String>) { tickJob?.cancel() tickJob = null- kartHost.host.endRace()- val winner = finished.winner() ?: finished.leaderboard().first()- val order = finished.leaderboard()+ kartHost.host?.endRace() _racePhase.value = RacePhase.Results(winner = winner, order = order) val state = _uiState.value viewModelScope.launch {@@ -267,6 +345,43 @@ class KartViewModel(application: Application) : AndroidViewModel(application), race = null } + /**+ * One native standings row. Parsed by hand (not kotlinx.serialization): the engine emits a+ * fixed tiny shape and the game must never crash the tick on a malformed frame.+ */+ private data class NativeStanding(+ val player: String,+ val lap: Int,+ val progress: Float,+ val place: Int,+ )++ private fun parseStandings(json: String): List<NativeStanding> {+ val text = json.trim()+ if (!text.startsWith("[") || !text.endsWith("]")) return emptyList()+ val rows = text.removePrefix("[").removeSuffix("]").split("},")+ if (rows.size == 1 && rows[0].isBlank()) return emptyList()+ return rows.mapNotNull { row ->+ val obj = row.trim().removeSuffix("}").removePrefix("{")+ fun field(name: String): String? {+ val key = "\"$name\":"+ val at = obj.indexOf(key)+ if (at < 0) return null+ val rest = obj.substring(at + key.length).trim()+ return if (rest.startsWith("\"")) {+ rest.removePrefix("\"").substringBefore("\"")+ } else {+ rest.substringBefore(",").trim()+ }+ }+ val player = field("player") ?: return@mapNotNull null+ val lap = field("lap")?.toIntOrNull() ?: return@mapNotNull null+ val progress = field("progress")?.toFloatOrNull() ?: return@mapNotNull null+ val place = field("place")?.toIntOrNull() ?: return@mapNotNull null+ NativeStanding(player, lap, progress, place)+ }+ }+ /** 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)
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.ktindex 1ef56cca15..25127fc10b 100644--- 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.kt@@ -5,6 +5,7 @@ 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.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll@@ -13,6 +14,8 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.viewinterop.AndroidView import com.vayunmathur.games.kart.R import com.vayunmathur.games.kart.data.GameMode import com.vayunmathur.games.kart.platform.KartGameActions@@ -185,6 +188,20 @@ private fun CountdownBody(phase: RacePhase.Countdown) { @Composable private fun RacingBody(phase: RacePhase.Racing) {+ // The native 3D viewport sits behind the standings HUD. With no+ // libkart_engine it is never composed and the HUD is the whole screen;+ // in a @Preview (Layoutlib) a SurfaceView is a blank rect, so listing+ // images keep rendering the HUD exactly as before.+ if (com.vayunmathur.games.kart.util.KartNative.isAvailable) {+ AndroidView(+ factory = { ctx ->+ // No opaque background: a SurfaceView shows its Vulkan layer+ // through a transparent hole in the window.+ KartSurfaceView(ctx)+ },+ modifier = Modifier.fillMaxWidth().height(240.dp),+ )+ } Text( stringResource(R.string.race_lap, phase.playerLap + 1, phase.totalLaps), style = MaterialTheme.typography.titleLarge,
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartSurfaceView.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartSurfaceView.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartSurfaceView.ktnew file mode 100644index 0000000000..edd8f24ec1--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartSurfaceView.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.kart.ui++import android.content.Context+import android.util.AttributeSet+import android.view.SurfaceHolder+import android.view.SurfaceView+import com.vayunmathur.games.kart.util.KartNative+import com.vayunmathur.library.log.Log++/**+ * The native 3D viewport: a SurfaceView the Rust engine draws into.+ *+ * Same arrangement as the voxels `VoxelSurfaceView`: the view owns nothing but+ * the surface lifecycle, the engine owns the render thread, and every JNI+ * call is guarded by [KartNative.isAvailable] so a device without+ * `libkart_engine` shows the placeholder race instead of crashing.+ */+class KartSurfaceView @JvmOverloads constructor(+ context: Context,+ attrs: AttributeSet? = null,+) : SurfaceView(context, attrs), SurfaceHolder.Callback {+ private var ready = false++ init {+ holder.addCallback(this)+ }++ // JNI boundary: native throws unchecked exceptions, all logged here.+ @Suppress("TooGenericExceptionCaught")+ override fun surfaceCreated(holder: SurfaceHolder) {+ if (!KartNative.isAvailable) return+ // JNI boundary: native throws unchecked exceptions, all logged here.+ try {+ KartNative.surfaceCreated(holder.surface)+ ready = true+ } catch (e: RuntimeException) {+ Log.error("KartSurface", "surfaceCreated failed", e)+ }+ }++ @Suppress("TooGenericExceptionCaught")+ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ if (!KartNative.isAvailable || !ready) return+ try {+ KartNative.surfaceChanged(width, height)+ } catch (e: RuntimeException) {+ Log.error("KartSurface", "surfaceChanged failed", e)+ }+ }++ @Suppress("TooGenericExceptionCaught")+ override fun surfaceDestroyed(holder: SurfaceHolder) {+ if (!KartNative.isAvailable) return+ try {+ KartNative.surfaceDestroyed()+ ready = false+ } catch (e: RuntimeException) {+ Log.error("KartSurface", "surfaceDestroyed failed", e)+ }+ }+}
games/kart/src/main/rust/Cargo.toml
diff --git a/games/kart/src/main/rust/Cargo.toml b/games/kart/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..e14d75d9e3--- /dev/null+++ b/games/kart/src/main/rust/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "kart_engine"+version = "0.1.0"+edition = "2021"+description = "Kart TV racer engine: Sunset Oval track mesh, arcade kart physics, chase cam, items + AI, Vulkan renderer"+license = "GPL-2.0-only"++[lib]+name = "kart_engine"+crate-type = ["cdylib", "rlib"]++[dependencies]+jni.workspace = true+ash = { workspace = true, default-features = false, features = ["loaded"] }+glam = { workspace = true, features = ["serde"] }+serde = { workspace = true, features = ["derive"] }+serde_json.workspace = true
games/kart/src/main/rust/build.rs
diff --git a/games/kart/src/main/rust/build.rs b/games/kart/src/main/rust/build.rsnew file mode 100644index 0000000000..b44ca7f074--- /dev/null+++ b/games/kart/src/main/rust/build.rs@@ -0,0 +1,100 @@+use std::path::PathBuf;+use std::process::Command;++/// Compile the kart shaders to SPIR-V with glslc when available.+///+/// Same arrangement as games/voxels: `include_bytes!` in vulkan/pipeline.rs+/// requires the `.spv` files to exist even when no glslc is installed, so a+/// minimal valid module is written as a fallback (it draws nothing useful, but+/// the crate still builds and the CPU-side race sim still ticks).+fn main() {+ let shaders_dir = PathBuf::from("shaders");+ let pairs = [("kart.vert", "kart.vert.spv"), ("kart.frag", "kart.frag.spv")];++ if let Some(glslc) = find_glslc() {+ println!("cargo:warning=Found glslc at {}", glslc.display());+ for (src, spv) in &pairs {+ let _ = Command::new(&glslc)+ .arg("-o")+ .arg(shaders_dir.join(spv))+ .arg(shaders_dir.join(src))+ .status();+ }+ }++ for (src, spv) in &pairs {+ let out = shaders_dir.join(spv);+ if !out.exists() {+ let bytes = if src.ends_with(".vert") {+ minimal_vert_spv()+ } else {+ minimal_frag_spv()+ };+ std::fs::write(&out, bytes).ok();+ }+ println!("cargo:rerun-if-changed=shaders/{src}");+ }+ println!("cargo:rerun-if-changed=build.rs");+}++/// glslc ships with the NDK (shader-tools) on every host OS; fall back to+/// PATH. The Windows path is read from the same SDK the Gradle build uses.+fn find_glslc() -> Option<PathBuf> {+ let mut candidates: Vec<PathBuf> = Vec::new();+ let sdk = std::env::var("ANDROID_HOME")+ .or_else(|_| std::env::var("ANDROID_SDK_ROOT"))+ .ok();+ if let Some(sdk) = sdk {+ for tag in ["windows-x86_64", "linux-x86_64", "darwin-x86_64"] {+ candidates.push(+ PathBuf::from(&sdk)+ .join("ndk")+ .join("29.0.14206865")+ .join("shader-tools")+ .join(tag)+ .join(if tag.starts_with("windows") {+ "glslc.exe"+ } else {+ "glslc"+ }),+ );+ }+ }+ for mac_linux in [+ "/Users/vayun/devmate-android-toolchain/android-sdk/ndk/29.0.14206865/shader-tools/darwin-x86_64/glslc",+ "/Users/vayun/devmate-android-toolchain/android-sdk/ndk/29.0.14206865/shader-tools/linux-x86_64/glslc",+ ] {+ candidates.push(PathBuf::from(mac_linux));+ }+ for c in candidates {+ if c.exists() {+ return Some(c);+ }+ }+ let probe = if cfg!(windows) { "where" } else { "which" };+ if Command::new(probe)+ .arg("glslc")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+ {+ return Some(PathBuf::from("glslc"));+ }+ None+}++fn minimal_vert_spv() -> Vec<u8> {+ vec![+ 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00,+ 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,+ 0x01, 0x00, 0x00, 0x00,+ ]+}++fn minimal_frag_spv() -> Vec<u8> {+ vec![+ 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00,+ 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,+ 0x01, 0x00, 0x00, 0x00,+ ]+}
games/kart/src/main/rust/shaders/kart.frag
diff --git a/games/kart/src/main/rust/shaders/kart.frag b/games/kart/src/main/rust/shaders/kart.fragnew file mode 100644index 0000000000..d63c8b147b--- /dev/null+++ b/games/kart/src/main/rust/shaders/kart.frag@@ -0,0 +1,25 @@+#version 450+// Flat shading plus distance fog: one fixed sun direction, no shadow maps.+// Karts read as solid boxes against the track; the fog melts the far side of+// the oval into the sky clear color so the pop-in line never shows.+layout(location = 0) in vec3 vColor;+layout(location = 1) in vec3 vWorld;++layout(location = 0) out vec4 outColor;++layout(set = 0, binding = 0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ vec3 camPos;+} ubo;++const vec3 SKY = vec3(0.45, 0.68, 0.94);++void main() {+ vec3 up = vec3(0.0, 1.0, 0.0);+ float ndl = 0.72 + 0.28 * clamp(dot(up, normalize(ubo.sunDir)), 0.0, 1.0);+ vec3 col = vColor * ndl;+ float dist = length(vWorld - ubo.camPos);+ float fog = 1.0 - exp(-dist * 0.0045);+ outColor = vec4(mix(col, SKY, clamp(fog, 0.0, 1.0)), 1.0);+}
games/kart/src/main/rust/shaders/kart.frag.spv
diff --git a/games/kart/src/main/rust/shaders/kart.frag.spv b/games/kart/src/main/rust/shaders/kart.frag.spvnew file mode 100644index 0000000000..d27f8d838eBinary files /dev/null and b/games/kart/src/main/rust/shaders/kart.frag.spv differ
games/kart/src/main/rust/shaders/kart.vert
diff --git a/games/kart/src/main/rust/shaders/kart.vert b/games/kart/src/main/rust/shaders/kart.vertnew file mode 100644index 0000000000..344a00b880--- /dev/null+++ b/games/kart/src/main/rust/shaders/kart.vert@@ -0,0 +1,24 @@+#version 450+// Unlit vertex-color kart shader: the mesh carries the art (asphalt gray,+// grass green, per-kart box colors), so no textures and no samplers.+layout(location = 0) in vec3 inPos;+layout(location = 1) in vec3 inColor;++layout(location = 0) out vec3 vColor;+layout(location = 1) out vec3 vWorld;++layout(set = 0, binding = 0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ vec3 camPos;+} ubo;++void main() {+ vColor = inColor;+ vWorld = inPos;+ vec4 clip = ubo.viewProj * vec4(inPos, 1.0);+ // Vulkan Y flip: NDC Y points down, and the flip inverts winding (hence+ // CULL_NONE in the pipeline) — same arrangement as games/voxels.+ clip.y = -clip.y;+ gl_Position = clip;+}
games/kart/src/main/rust/shaders/kart.vert.spv
diff --git a/games/kart/src/main/rust/shaders/kart.vert.spv b/games/kart/src/main/rust/shaders/kart.vert.spvnew file mode 100644index 0000000000..9f20d208d4Binary files /dev/null and b/games/kart/src/main/rust/shaders/kart.vert.spv differ
games/kart/src/main/rust/src/engine.rs
diff --git a/games/kart/src/main/rust/src/engine.rs b/games/kart/src/main/rust/src/engine.rsnew file mode 100644index 0000000000..68dea96cef--- /dev/null+++ b/games/kart/src/main/rust/src/engine.rs@@ -0,0 +1,400 @@+//! Engine state: the race, the renderer, and the tick that binds them.+//!+//! The Kotlin loop owns cadence (one `tick_and_render` per frame from the+//! render thread in `lib.rs`); this module owns everything inside it: advance+//! the race at a fixed 60 Hz step, rebuild the dynamic mesh, update the+//! chase camera, draw. Everything fallible returns `Option`/`Result` — the+//! JNI boundary logs and keeps the placeholder running rather than crashing.++use crate::mesh::{self, KartVertex};+use crate::physics::DriveInput;+use crate::race::Race;+use crate::vulkan::context::{ANativeWindow, VulkanContext};+use crate::vulkan::renderer::KartRenderer;+use std::sync::{Mutex, OnceLock};+use std::time::Instant;++/// Fixed physics step: the race advances in 60 Hz slices no matter the frame rate.+const STEP: f32 = 1.0 / 60.0;++/// Engine state, behind the global lock (same shape as voxels' `ENGINE`).+pub struct EngineState {+ /// The live race (created by `start_race`).+ pub race: Option<Race>,+ /// The renderer (created by `create_renderer`).+ pub renderer: Option<KartRenderer>,+ /// Static track vertex count (from the last `upload_track`).+ pub track_count: usize,+ /// Pending human inputs by seat, written by the JNI setters and consumed+ /// by the tick. Kept whole (not per-field) so a drift edge and a drive+ /// sample arriving in either order merge into one control.+ pub pending: Vec<DriveInput>,+ /// Live window handle (released on destroy).+ pub window_ptr: Option<*mut ANativeWindow>,+ /// Surface size.+ pub width: u32,+ /// Surface size.+ pub height: u32,+ /// When the engine started (for tick pacing).+ pub last_tick: Instant,+ /// Leftover fractional step time.+ pub accumulator: f32,+ /// False once the surface is gone: the render thread exits.+ pub running: bool,+}++// SAFETY: guarded by the mutex; the raw window pointer is only touched on the+// render thread between create and destroy, like voxels' `EngineState`.+unsafe impl Send for EngineState {}++static ENGINE: OnceLock<Mutex<Option<EngineState>>> = OnceLock::new();++fn engine_lock() -> &'static Mutex<Option<EngineState>> {+ ENGINE.get_or_init(|| Mutex::new(None))+}++/// Run `f` on the engine state, if it exists.+pub fn with_engine<F, R>(f: F) -> Option<R>+where+ F: FnOnce(&mut EngineState) -> R,+{+ let mut guard = engine_lock().lock().ok()?;+ let state = guard.as_mut()?;+ Some(f(state))+}++/// Start (or restart) a race with these human seat ids. Uploads the track+/// mesh when a renderer is already live.+pub fn start_race(human_ids: Vec<String>) {+ with_engine(|s| {+ let mut race = Race::new(&human_ids);+ race.cam_seat = 0;+ s.pending = vec![DriveInput::default(); race.seat_count()];+ s.race = Some(race);+ s.accumulator = 0.0;+ if let Some(r) = s.renderer.as_mut() {+ let mesh = mesh::build_track_mesh();+ s.track_count = mesh.len();+ unsafe { r.upload_track(&mesh) };+ }+ });+}++/// Grow `pending` to `n` seats (no-op when already sized). Seats never shrink+/// mid-race: a phone that joined late drives from the next race.+fn ensure_pending(s: &mut EngineState, n: usize) {+ while s.pending.len() < n {+ s.pending.push(DriveInput::default());+ }+}++/// Feed one human drive sample. Merges with (never clears) the drift/item+/// edges the setters wrote since the last tick, so arrival order is free.+pub fn on_drive_input(player: usize, throttle: f32, steering: f32, brake: f32) {+ with_engine(|s| {+ ensure_pending(s, player + 1);+ if let Some(p) = s.pending.get_mut(player) {+ p.throttle = throttle.clamp(0.0, 1.0);+ p.steering = steering.clamp(-1.0, 1.0);+ p.brake = brake.clamp(0.0, 1.0);+ }+ });+}++/// Set the drift shoulder for one seat. Sticky until the next tick consumes+/// it (the Kotlin fan-in re-sends the hold every tick while held).+pub fn set_drift(player: usize, held: bool) {+ with_engine(|s| {+ ensure_pending(s, player + 1);+ if let Some(p) = s.pending.get_mut(player) {+ p.drift = held;+ }+ });+}++/// Fire one seat's held item. Edge-triggered: the tick consumes and clears+/// it, so holding the button does not fire twice.+pub fn use_item(player: usize) {+ with_engine(|s| {+ ensure_pending(s, player + 1);+ if let Some(p) = s.pending.get_mut(player) {+ p.item = true;+ }+ });+}++/// Snapshot for the HUD/standings: JSON `[{player,lap,progress,place}]`.+pub fn standings_json() -> String {+ with_engine(|s| {+ s.race.as_ref().map(|race| {+ let standings = race.standings();+ let mut out = String::from("[");+ for (place, (id, lap, progress)) in standings.iter().enumerate() {+ if place > 0 {+ out.push(',');+ }+ out.push_str(&format!(+ "{{\"player\":\"{}\",\"lap\":{},\"progress\":{:.4},\"place\":{}}}",+ escape(id),+ lap,+ progress,+ place + 1+ ));+ }+ out.push(']');+ out+ })+ })+ .flatten()+ .unwrap_or_else(|| "[]".into())+}++fn escape(s: &str) -> String {+ s.replace('\\', "\\\\").replace('"', "\\\"")+}++/// Create the renderer for a live window. Fails cleanly (None) — the Kotlin+/// side keeps the placeholder when this returns false.+///+/// # Safety+/// `window` must be a live `ANativeWindow` adopted from the JNI surface (the+/// caller acquired it via `ANativeWindow_acquire`); ownership moves here.+pub unsafe fn create_renderer(window: *mut ANativeWindow, width: i32, height: i32) -> bool {+ with_engine(|state| {+ state.window_ptr = Some(window);+ state.width = width.max(1) as u32;+ state.height = height.max(1) as u32;+ let ctx = match unsafe { VulkanContext::new(window, width, height) } {+ Ok(c) => c,+ Err(_) => return false,+ };+ let renderer = match unsafe {+ KartRenderer::new(ctx, state.width, state.height)+ } {+ Ok(r) => r,+ Err(_) => return false,+ };+ // A race may already be live (surface recreated on rotation): upload.+ if state.race.is_some() {+ let mesh = mesh::build_track_mesh();+ state.track_count = mesh.len();+ unsafe { renderer.upload_track(&mesh) };+ }+ state.renderer = Some(renderer);+ state.running = true;+ true+ })+ .unwrap_or(false)+}++/// Resize: recreate the swapchain at the new size. If recreation fails the+/// renderer is dropped and the next frame re-creates it (placeholder covers).+pub fn resize_renderer(width: i32, height: i32) {+ with_engine(|state| {+ state.width = width.max(1) as u32;+ state.height = height.max(1) as u32;+ if let Some(mut r) = state.renderer.take() {+ let window = match state.window_ptr {+ Some(w) => w,+ None => {+ unsafe { r.destroy() };+ return;+ }+ };+ let ctx = match unsafe { VulkanContext::new(window, width, height) } {+ Ok(c) => c,+ Err(_) => {+ unsafe { r.destroy() };+ return;+ }+ };+ match unsafe { KartRenderer::new(ctx, state.width, state.height) } {+ Ok(fresh) => {+ let mesh = mesh::build_track_mesh();+ state.track_count = mesh.len();+ unsafe { fresh.upload_track(&mesh) };+ state.renderer = Some(fresh);+ unsafe { r.destroy() };+ }+ Err(_) => {+ state.renderer = Some(r);+ }+ }+ }+ });+}++/// Destroy the renderer (surface gone). The race survives: rotation+/// re-creates the surface and `create_renderer` re-uploads.+pub fn destroy_renderer() {+ with_engine(|state| {+ if let Some(mut r) = state.renderer.take() {+ unsafe { r.destroy() };+ state.running = false;+ }+ if let Some(win) = state.window_ptr.take() {+ unsafe { crate::vulkan::context::ANativeWindow_release(win) };+ }+ });+}++/// Destroy everything (activity gone).+pub fn destroy_engine() {+ let mut guard = match engine_lock().lock() {+ Ok(g) => g,+ Err(_) => return,+ };+ if let Some(mut state) = guard.take() {+ if let Some(mut r) = state.renderer.take() {+ unsafe { r.destroy() };+ // The context owns instance/device; release them too.+ r.ctx.destroy();+ }+ if let Some(win) = state.window_ptr.take() {+ unsafe { crate::vulkan::context::ANativeWindow_release(win) };+ }+ }+}++/// One frame: step the race at fixed 60 Hz slices, rebuild the dynamic mesh,+/// update the chase camera, draw. Called from the render thread.+pub fn tick_and_render() {+ with_engine(|s| {+ let now = Instant::now();+ let frame_dt = now+ .duration_since(s.last_tick)+ .as_secs_f32()+ .clamp(0.0, 0.25);+ s.last_tick = now;+ let renderer = match s.renderer.as_mut() {+ Some(r) => r,+ None => return,+ };+ let race = match s.race.as_mut() {+ Some(r) => r,+ None => return,+ };+ // Fixed-step the sim so physics never depends on frame rate.+ s.accumulator += frame_dt;+ let mut steps = 0;+ while s.accumulator >= STEP && steps < 5 {+ // Publish the pending human samples, then clear the item edges+ // (drift stays sticky: the Kotlin side re-sends the hold).+ for (seat, input) in s.pending.iter().enumerate() {+ race.set_input(seat, *input);+ }+ for p in s.pending.iter_mut() {+ p.item = false;+ }+ race.tick(STEP);+ s.accumulator -= STEP;+ steps += 1;+ }+ // Dynamic mesh: karts + shells + boxes.+ let mut dynamic: Vec<KartVertex> = Vec::new();+ for (seat, (x, z, yaw, ai)) in race.kart_transforms().iter().enumerate() {+ mesh::build_kart_mesh(&mut dynamic, *x, *z, *yaw, seat, *ai, 0.0, false);+ }+ for (x, z) in race.shell_positions() {+ mesh::build_shell_mesh(&mut dynamic, x, z, race.ticks);+ }+ for (x, z) in race.box_positions() {+ mesh::build_box_mesh(&mut dynamic, x, z, race.ticks);+ }+ // Chase camera → view-projection.+ let (cam_pos, look) = race.camera();+ let view_proj = view_proj_for(+ cam_pos,+ look,+ renderer.width,+ renderer.height,+ renderer.swap.pre_rotation(),+ );+ let track_count = s.track_count;+ let _ = unsafe { renderer.draw(view_proj, cam_pos, track_count, &dynamic) };+ });+}++/// View-projection for the chase camera: look-at + perspective + surface+/// pre-rotation. Aspect swaps on ROTATE_90/270 panels.+pub fn view_proj_for(+ cam_pos: [f32; 3],+ look: [f32; 3],+ width: u32,+ height: u32,+ pre_rotation: (bool, f32),+) -> [[f32; 4]; 4] {+ use glam::{Mat4, Vec3};+ let (swap_aspect, rot) = pre_rotation;+ let (w, h) = if swap_aspect {+ (height.max(1) as f32, width.max(1) as f32)+ } else {+ (width.max(1) as f32, height.max(1) as f32)+ };+ let view = Mat4::look_at_rh(Vec3::from(cam_pos), Vec3::from(look), Vec3::Y);+ let proj = Mat4::perspective_rh(70.0_f32.to_radians(), w / h.max(1.0), 0.1, 800.0);+ let rot_m = Mat4::from_rotation_z(rot);+ (rot_m * proj * view).to_cols_array_2d()+}++/// Create the engine state if absent (called once from JNI init).+pub fn ensure_engine() {+ let mut guard = match engine_lock().lock() {+ Ok(g) => g,+ Err(_) => return,+ };+ if guard.is_none() {+ *guard = Some(EngineState {+ race: None,+ renderer: None,+ track_count: 0,+ pending: Vec::new(),+ window_ptr: None,+ width: 0,+ height: 0,+ last_tick: Instant::now(),+ accumulator: 0.0,+ running: false,+ });+ }+}++/// Whether the render thread should keep running.+pub fn is_running() -> bool {+ with_engine(|s| s.running).unwrap_or(false)+}++/// Whether a renderer is live.+pub fn has_renderer() -> bool {+ with_engine(|s| s.renderer.is_some()).unwrap_or(false)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn camera_matrix_is_finite() {+ let m = view_proj_for([0.0, 4.0, 20.0], [0.0, 1.0, 0.0], 1280, 720, (false, 0.0));+ for row in &m {+ for v in row {+ assert!(v.is_finite());+ }+ }+ }++ #[test]+ fn race_flows_without_renderer() {+ ensure_engine();+ start_race(vec!["p1".to_string()]);+ on_drive_input(0, 1.0, 0.0, 0.0);+ with_engine(|s| {+ let race = s.race.as_mut().unwrap();+ for _ in 0..600 {+ race.tick(STEP);+ }+ });+ let json = standings_json();+ assert!(json.starts_with('[') && json.contains("p1"));+ }+}
games/kart/src/main/rust/src/items.rs
diff --git a/games/kart/src/main/rust/src/items.rs b/games/kart/src/main/rust/src/items.rsnew file mode 100644index 0000000000..4c62c44f8f--- /dev/null+++ b/games/kart/src/main/rust/src/items.rs@@ -0,0 +1,202 @@+//! Items and AI: what makes a race a race rather than a time trial.+//!+//! One item type per tier: a boost mushroom for the back of the pack, a+//! green shell that spins whoever it touches. AI drivers follow the racing+//! line with per-driver pace and wobble, and fire shells forward when they+//! hold one — beatable but not statues, mirroring the placeholder's 0.78 pace.++use crate::physics::{DriveInput, KartBody};+use crate::track;++/// Races per item box respawn in seconds.+pub const BOX_RESPAWN: f32 = 8.0;+/// Shell travel speed in m/s, slightly above kart top speed.+pub const SHELL_SPEED: f32 = 46.0;+/// Shell lifetime in seconds before it fizzles.+pub const SHELL_LIFE: f32 = 6.0;+/// Item-box grab radius in metres.+pub const BOX_RADIUS: f32 = 3.5;+/// AI pace as a fraction of top speed, before the per-driver wobble.+pub const AI_PACE: f32 = 0.78;++/// What a kart is holding. One slot: firing spends it.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum HeldItem {+ /// Empty slot.+ #[default]+ None,+ /// Short boost, fired with the item button.+ Mushroom,+ /// Shell fired forward along the kart's nose.+ Shell,+}++/// A pickup box on the centerline. Taken boxes respawn on a timer.+#[derive(Debug, Clone)]+pub struct ItemBox {+ /// Arc position of the box.+ pub track_s: f32,+ /// Lane offset in metres (alternates left/right down the track).+ pub lane: f32,+ /// Seconds until it comes back after being taken.+ pub respawn_left: f32,+}++/// A live shell: owner, position, heading, remaining life.+#[derive(Debug, Clone)]+pub struct Shell {+ /// Who fired it (immune to their own shell for the first half second).+ pub owner: usize,+ /// World position.+ pub x: f32,+ /// World position.+ pub z: f32,+ /// Heading; travels straight.+ pub yaw: f32,+ /// Seconds left before it fizzles.+ pub life: f32,+ /// Grace timer for the owner.+ pub grace: f32,+}++/// Assign an item by race position: leaders get mushrooms (defence), the back+/// gets shells (attack). Position 0 is the leader.+pub fn deal_item(position: usize, kart_count: usize) -> HeldItem {+ if kart_count <= 1 {+ return HeldItem::Mushroom;+ }+ let back_half = position * 2 >= kart_count;+ if back_half {+ HeldItem::Shell+ } else {+ HeldItem::Mushroom+ }+}++/// One AI driver: pace wobble plus a steering lookahead.+#[derive(Debug, Clone)]+pub struct AiDriver {+ /// 0.92..1.0 per-driver pace multiplier (mirrors the placeholder wobble).+ pub wobble: f32,+ /// Current steering output -1..1, smoothed so AI karts don't jitter.+ pub steer: f32,+}++impl AiDriver {+ /// Create driver `index` of `count`: spread the wobble across the field.+ pub fn new(index: usize, count: usize) -> Self {+ let spread = if count <= 1 {+ 0.0+ } else {+ index as f32 / (count - 1) as f32+ };+ Self {+ wobble: 0.90 + 0.08 * (1.0 - spread),+ steer: 0.0,+ }+ }++ /// Drive one tick: steer toward a lookahead point on the racing line,+ /// hold the throttle at pace, drift when the corner is tight.+ pub fn control(&mut self, kart: &KartBody) -> DriveInput {+ let ahead_s = track::advance(kart.track_s, 12.0);+ let ahead = track::point_at(ahead_s);+ let dx = ahead.x - kart.x;+ let dz = ahead.z - kart.z;+ let desired = dx.atan2(-dz);+ let err = track::wrap_angle(desired - kart.yaw);+ let target = (err * 1.6).clamp(-1.0, 1.0);+ // Low-pass the wheel: AI karts corner, they don't vibrate.+ self.steer += (target - self.steer) * 0.18;+ let tight = err.abs() > 0.45;+ DriveInput {+ throttle: AI_PACE * self.wobble,+ steering: self.steer,+ brake: 0.0,+ drift: tight,+ item: false,+ }+ }+}++/// Tick all live shells: move, age, and spin whoever they touch (except the+/// owner during grace). Returns the indices of karts that were hit.+pub fn tick_shells(shells: &mut Vec<Shell>, karts: &[KartBody], dt: f32) -> Vec<usize> {+ let mut hits = Vec::new();+ shells.retain_mut(|s| {+ s.life -= dt;+ if s.life <= 0.0 {+ return false;+ }+ s.grace -= dt;+ s.x += s.yaw.sin() * SHELL_SPEED * dt;+ s.z += -s.yaw.cos() * SHELL_SPEED * dt;+ for (i, k) in karts.iter().enumerate() {+ if i == s.owner && s.grace > 0.0 {+ continue;+ }+ let dx = k.x - s.x;+ let dz = k.z - s.z;+ if dx.hypot(dz) < crate::physics::HIT_RADIUS {+ hits.push(i);+ return false;+ }+ }+ true+ });+ hits+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn leaders_defend_back_attacks() {+ assert_eq!(deal_item(0, 8), HeldItem::Mushroom);+ assert_eq!(deal_item(7, 8), HeldItem::Shell);+ }++ #[test]+ fn ai_stays_on_track() {+ let mut kart = KartBody::spawn(0.0, 0.0);+ kart.speed = crate::physics::TOP_SPEED * AI_PACE;+ let mut ai = AiDriver::new(0, 4);+ for _ in 0..1200 {+ let c = ai.control(&kart);+ kart.tick(&c, 1.0 / 60.0);+ }+ let p = track::point_at(kart.track_s);+ assert!(+ track::on_track(kart.x, kart.z, &p),+ "ai off at s={} ({},{})",+ kart.track_s,+ kart.x,+ kart.z+ );+ }++ #[test]+ fn shell_hits_a_kart_ahead() {+ let owner = KartBody::spawn(0.0, 0.0);+ let mut victim = KartBody::spawn(10.0, 0.0);+ victim.speed = 0.0;+ let mut shells = vec![Shell {+ owner: 0,+ x: owner.x,+ z: owner.z,+ yaw: owner.yaw,+ life: SHELL_LIFE,+ grace: 0.0,+ }];+ let karts = vec![owner, victim];+ let mut hit = false;+ for _ in 0..120 {+ if !tick_shells(&mut shells, &karts, 1.0 / 60.0).is_empty() {+ hit = true;+ break;+ }+ }+ assert!(hit, "shell never reached the kart ahead");+ }+}
games/kart/src/main/rust/src/lib.rs
diff --git a/games/kart/src/main/rust/src/lib.rs b/games/kart/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..1183f9e185--- /dev/null+++ b/games/kart/src/main/rust/src/lib.rs@@ -0,0 +1,209 @@+//! kart_engine: Sunset Oval racer — track, physics, items, AI, Vulkan.+//!+//! The JNI surface mirrors the Kotlin `KartNative` object exactly: FQNs are+//! frozen (`com.vayunmathur.games.kart.util.KartNative`), so the package+//! exception marker on the Kotlin file covers this seam too. jni 0.22 API:+//! native methods receive `EnvUnowned` and adapt via `with_env`.++pub mod engine;+pub mod items;+pub mod mesh;+pub mod physics;+pub mod race;+pub mod track;+pub mod vulkan;++use jni::objects::{JClass, JObject, JString};+use jni::sys::{jboolean, jfloat, jint, jstring};+use jni::{Env, EnvUnowned};++#[cfg(target_os = "android")]+use std::os::raw::c_void as CVoid;++fn get_string(env: &Env, s: &JString) -> Option<String> {+ s.try_to_string(env).ok()+}++/// Adopt the engine state (idempotent; called once from `KartNative` init).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeInit<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jboolean {+ let _ = &mut env;+ engine::ensure_engine();+ true+}++/// Start (or restart) a race. `player_ids_csv` is the comma-separated human+/// seat ids in grid order; AI fills the rest of the grid.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeStartRace<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ player_ids_csv: JString<'l>,+) {+ engine::ensure_engine();+ let ids: Vec<String> = env+ .with_env(|env| -> jni::errors::Result<Vec<String>> {+ match get_string(env, &player_ids_csv) {+ Some(csv) => Ok(csv+ .split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect()),+ None => Ok(Vec::new()),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>();+ engine::start_race(ids);+}++/// One player's drive sample for this tick (throttle/steering/brake+/// normalized; drift and item arrive via their own setters and merge).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeOnDriveInput<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ player: jint,+ throttle: jfloat,+ steering: jfloat,+ brake: jfloat,+) {+ if player >= 0 {+ engine::on_drive_input(player as usize, throttle, steering, brake);+ }+}++/// Drift shoulder held (sticky until the tick consumes the frame).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeSetDrift<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ player: jint,+ held: jboolean,+) {+ if player >= 0 {+ engine::set_drift(player as usize, held != jni::sys::JNI_FALSE);+ }+}++/// Fire the held item (edge-triggered).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeUseItem<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ player: jint,+) {+ if player >= 0 {+ engine::use_item(player as usize);+ }+}++/// Snapshot for the HUD/standings: JSON `[{player,lap,progress,place}]`.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeGetStandingsJson<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jstring {+ env.with_env(|env| -> jni::errors::Result<jstring> {+ let null = std::ptr::null_mut();+ match env.new_string(engine::standings_json()) {+ Ok(s) => Ok(s.into_raw()),+ Err(_) => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Surface ready: adopt the window, build the renderer, start the 60 Hz+/// render thread. A second call (rotation) rebuilds against the new surface.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeSurfaceCreated<'l>(+ env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface: JObject<'l>,+) {+ engine::ensure_engine();+ #[cfg(target_os = "android")]+ {+ let env_raw = env.as_raw() as *mut CVoid;+ let surf_raw = surface.as_raw() as *mut CVoid;+ let window = unsafe { vulkan::context::ANativeWindow_fromSurface(env_raw, surf_raw) };+ if window.is_null() {+ return;+ }+ unsafe { vulkan::context::ANativeWindow_acquire(window) };+ if !unsafe { engine::create_renderer(window, 1280, 720) } {+ unsafe { vulkan::context::ANativeWindow_release(window) };+ return;+ }+ std::thread::spawn(|| {+ let mut last = std::time::Instant::now();+ loop {+ if !engine::has_renderer() {+ break;+ }+ engine::tick_and_render();+ let elapsed = last.elapsed();+ let target = std::time::Duration::from_millis(16);+ if elapsed < target {+ std::thread::sleep(target - elapsed);+ }+ last = std::time::Instant::now();+ if !engine::is_running() {+ break;+ }+ }+ });+ }+ #[cfg(not(target_os = "android"))]+ {+ let _ = (env, surface);+ }+}++/// Surface resized: recreate the swapchain at the new size.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeSurfaceChanged<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ width: jint,+ height: jint,+) {+ engine::resize_renderer(width, height);+}++/// Surface gone: destroy the renderer, stop the thread. The race survives.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeSurfaceDestroyed<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+) {+ engine::destroy_renderer();+}++/// Activity gone: destroy everything.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeOnDestroy<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+) {+ engine::destroy_engine();+}++#[cfg(test)]+mod tests {+ use crate::mesh::build_track_mesh;+ use crate::race::Race;++ #[test]+ fn engine_smoke() {+ let mesh = build_track_mesh();+ assert!(!mesh.is_empty());+ let mut race = Race::new(&["p1".to_string()]);+ race.tick(1.0 / 60.0);+ assert!(!race.standings().is_empty());+ }+}
games/kart/src/main/rust/src/mesh.rs
diff --git a/games/kart/src/main/rust/src/mesh.rs b/games/kart/src/main/rust/src/mesh.rsnew file mode 100644index 0000000000..598aae98ed--- /dev/null+++ b/games/kart/src/main/rust/src/mesh.rs@@ -0,0 +1,295 @@+//! Track + kart meshes: flat-shaded vertex-color triangles, no textures.+//!+//! The oval is a triangle strip swept along the centerline: asphalt quads in+//! the middle, grass skirts on both sides out to the draw distance, and a+//! low outer wall so karts read as contained. Karts are box bodies (body ++//! cabin + four wheels) tinted per seat; shells and item boxes are small+//! spinning markers. Everything is rebuilt only when the race starts — per+//! frame the renderer re-uploads the dynamic parts (karts, shells).++use crate::track;++/// One vertex: position + flat color. Matches `kart.vert` locations 0/1.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct KartVertex {+ /// World position.+ pub pos: [f32; 3],+ /// Flat RGB.+ pub color: [f32; 3],+}++/// Asphalt gray.+pub const ASPHALT: [f32; 3] = [0.22, 0.23, 0.25];+/// Start/finish checker: alternating squares near s = 0.+pub const CHECKER_A: [f32; 3] = [0.92, 0.92, 0.92];+/// Start/finish checker dark squares.+pub const CHECKER_B: [f32; 3] = [0.08, 0.08, 0.08];+/// Grass green (two tones checkerboarded so speed reads).+pub const GRASS_A: [f32; 3] = [0.24, 0.55, 0.25];+/// Grass green dark.+pub const GRASS_B: [f32; 3] = [0.19, 0.47, 0.21];+/// Outer wall red/white.+pub const WALL_A: [f32; 3] = [0.80, 0.16, 0.16];+/// Outer wall white.+pub const WALL_B: [f32; 3] = [0.92, 0.92, 0.92];+/// Item-box cyan.+pub const BOX_COLOR: [f32; 3] = [0.15, 0.75, 0.85];+/// Shell green.+pub const SHELL_COLOR: [f32; 3] = [0.25, 0.80, 0.30];+/// Per-seat kart body colors (up to 8 seats).+pub const KART_COLORS: [[f32; 3]; 8] = [+ [0.85, 0.20, 0.20],+ [0.20, 0.45, 0.85],+ [0.20, 0.70, 0.30],+ [0.90, 0.75, 0.15],+ [0.70, 0.30, 0.85],+ [0.90, 0.45, 0.15],+ [0.20, 0.80, 0.80],+ [0.85, 0.85, 0.85],+];+/// AI karts read as rivals: darkened version of the seat color.+pub const AI_DARKEN: f32 = 0.55;++/// Metres between centerline samples for the mesh sweep.+pub const MESH_STEP: f32 = 4.0;+/// Grass skirt extent on each side of the asphalt, in metres.+pub const GRASS_EXTENT: f32 = 40.0;+/// Wall height in metres.+pub const WALL_HEIGHT: f32 = 1.2;++/// Push a quad (two triangles) into `out`.+fn quad(+ out: &mut Vec<KartVertex>,+ a: [f32; 3],+ b: [f32; 3],+ c: [f32; 3],+ d: [f32; 3],+ color: [f32; 3],+) {+ for p in [a, b, c, c, b, d] {+ out.push(KartVertex { pos: p, color });+ }+}++/// Push an axis-aligned box centred at (`x`, `y`, `z`) into `out`.+fn box_at(out: &mut Vec<KartVertex>, x: f32, y: f32, z: f32, sx: f32, sy: f32, sz: f32, color: [f32; 3]) {+ let x0 = x - sx / 2.0;+ let x1 = x + sx / 2.0;+ let y0 = y;+ let y1 = y + sy;+ let z0 = z - sz / 2.0;+ let z1 = z + sz / 2.0;+ // Top.+ quad(+ out,+ [x0, y1, z0],+ [x1, y1, z0],+ [x0, y1, z1],+ [x1, y1, z1],+ color,+ );+ // Front (+Z face toward the viewer on the top straight).+ quad(+ out,+ [x0, y0, z1],+ [x1, y0, z1],+ [x0, y1, z1],+ [x1, y1, z1],+ darken(color, 0.85),+ );+ // Back.+ quad(+ out,+ [x1, y0, z0],+ [x0, y0, z0],+ [x1, y1, z0],+ [x0, y1, z0],+ darken(color, 0.85),+ );+ // Left.+ quad(+ out,+ [x0, y0, z0],+ [x0, y0, z1],+ [x0, y1, z0],+ [x0, y1, z1],+ darken(color, 0.7),+ );+ // Right.+ quad(+ out,+ [x1, y0, z1],+ [x1, y0, z0],+ [x1, y1, z1],+ [x1, y1, z0],+ darken(color, 0.7),+ );+}++fn darken(c: [f32; 3], k: f32) -> [f32; 3] {+ [c[0] * k, c[1] * k, c[2] * k]+}++/// Build the static track mesh: asphalt + start line + grass + walls.+pub fn build_track_mesh() -> Vec<KartVertex> {+ let mut out = Vec::new();+ let steps = (track::TRACK_LENGTH / MESH_STEP).ceil() as usize;+ for i in 0..steps {+ let s0 = i as f32 * MESH_STEP;+ let s1 = ((i + 1) as f32 * MESH_STEP).min(track::TRACK_LENGTH);+ let p0 = track::point_at(s0);+ let p1 = track::point_at(s1);+ let hw = track::HALF_WIDTH;+ // Asphalt quad.+ let a0 = [p0.x - p0.nx * hw, 0.0, p0.z - p0.nz * hw];+ let b0 = [p0.x + p0.nx * hw, 0.0, p0.z + p0.nz * hw];+ let a1 = [p1.x - p1.nx * hw, 0.0, p1.z - p1.nz * hw];+ let b1 = [p1.x + p1.nx * hw, 0.0, p1.z + p1.nz * hw];+ // Start/finish checker for the first two quads.+ let color = if s0 < MESH_STEP * 2.0 {+ if i % 2 == 0 { CHECKER_A } else { CHECKER_B }+ } else {+ ASPHALT+ };+ quad(&mut out, a0, b0, a1, b1, color);+ // Grass skirts: 2 bands per side, checkerboarded.+ for side in [-1.0, 1.0] {+ for band in 0..2 {+ let g0 = hw + band as f32 * GRASS_EXTENT / 2.0;+ let g1 = hw + (band + 1) as f32 * GRASS_EXTENT / 2.0;+ let c0 = [p0.x + p0.nx * side * g0, -0.05, p0.z + p0.nz * side * g0];+ let d0 = [p0.x + p0.nx * side * g1, -0.05, p0.z + p0.nz * side * g1];+ let c1 = [p1.x + p1.nx * side * g0, -0.05, p1.z + p1.nz * side * g0];+ let d1 = [p1.x + p1.nx * side * g1, -0.05, p1.z + p1.nz * side * g1];+ let g = if (i + band + (if side > 0.0 { 1 } else { 0 })) % 2 == 0 {+ GRASS_A+ } else {+ GRASS_B+ };+ if side > 0.0 {+ quad(&mut out, c0, d0, c1, d1, g);+ } else {+ quad(&mut out, d0, c0, d1, c1, g);+ }+ }+ }+ // Outer walls at the asphalt edge (both sides), red/white blocks.+ let wall = if i % 2 == 0 { WALL_A } else { WALL_B };+ for side in [-1.0, 1.0] {+ let w0 = hw + 0.6;+ let e0 = [p0.x + p0.nx * side * w0, 0.0, p0.z + p0.nz * side * w0];+ let e1 = [p1.x + p1.nx * side * w0, 0.0, p1.z + p1.nz * side * w0];+ let f0 = [e0[0], WALL_HEIGHT, e0[2]];+ let f1 = [e1[0], WALL_HEIGHT, e1[2]];+ quad(&mut out, e0, e1, f0, f1, wall);+ }+ }+ out+}++/// Build one kart mesh at (`x`, `z`, `yaw`) with seat color `seat`.+/// `spin` rotates the body (item-hit feedback); `boost` stretches it slightly.+pub fn build_kart_mesh(+ mut out: &mut Vec<KartVertex>,+ x: f32,+ z: f32,+ yaw: f32,+ seat: usize,+ ai: bool,+ spin: f32,+ boost: bool,+) {+ let mut color = KART_COLORS[seat % KART_COLORS.len()];+ if ai {+ color = darken(color, AI_DARKEN);+ }+ let yaw = yaw + spin;+ let (fx, fz) = (yaw.sin(), -yaw.cos());+ let (rx, rz) = (-fz, fx);+ // Local-to-world: forward 2.6 m, right 1.6 m.+ let put = |lx: f32, y: f32, lz: f32| -> [f32; 3] {+ [x + rx * lx + fx * lz, y, z + rz * lx + fz * lz]+ };+ let stretch = if boost { 1.12 } else { 1.0 };+ // Body: low box.+ let body = color;+ let y0 = 0.35;+ let (hx, hz) = (1.6 / 2.0, 2.6 * stretch / 2.0);+ let corners = [+ put(-hx, y0, -hz),+ put(hx, y0, -hz),+ put(-hx, y0, hz),+ put(hx, y0, hz),+ ];+ let top = [+ put(-hx, y0 + 0.55, -hz),+ put(hx, y0 + 0.55, -hz),+ put(-hx, y0 + 0.55, hz),+ put(hx, y0 + 0.55, hz),+ ];+ quad(&mut out, top[0], top[1], top[2], top[3], body);+ quad(&mut out, corners[2], corners[3], top[2], top[3], darken(body, 0.9));+ quad(&mut out, corners[1], corners[0], top[1], top[0], darken(body, 0.85));+ quad(&mut out, corners[0], corners[2], top[0], top[2], darken(body, 0.75));+ quad(&mut out, corners[3], corners[1], top[3], top[1], darken(body, 0.75));+ // Cabin: smaller darker box on top.+ let cabin = darken(color, 0.6);+ let (cx, cz) = (1.0 / 2.0, 1.1 / 2.0);+ let cc = [+ put(-cx, y0 + 0.55, -cz),+ put(cx, y0 + 0.55, -cz),+ put(-cx, y0 + 0.55, cz),+ put(cx, y0 + 0.55, cz),+ ];+ let ct = [+ put(-cx, y0 + 1.15, -cz),+ put(cx, y0 + 1.15, -cz),+ put(-cx, y0 + 1.15, cz),+ put(cx, y0 + 1.15, cz),+ ];+ quad(&mut out, ct[0], ct[1], ct[2], ct[3], cabin);+ quad(&mut out, cc[0], cc[2], ct[0], ct[2], darken(cabin, 0.85));+ quad(&mut out, cc[3], cc[1], ct[3], ct[1], darken(cabin, 0.85));+ // Wheels: four dark boxes.+ let wheel = [0.10, 0.10, 0.10];+ for (wx, wz) in [(-0.85, -0.85), (0.85, -0.85), (-0.85, 0.85), (0.85, 0.85)] {+ let c = put(wx, 0.0, wz * stretch);+ box_at(&mut out, c[0], c[1], c[2], 0.42, 0.5, 0.42, wheel);+ }+ let _ = corners;+}++/// Build one item box marker (floating cube, bobbed by `ticks`).+pub fn build_box_mesh(out: &mut Vec<KartVertex>, x: f32, z: f32, ticks: u64) {+ let bob = 0.9 + 0.25 * ((ticks as f32 / 30.0).sin());+ box_at(out, x, bob, z, 1.2, 1.2, 1.2, BOX_COLOR);+}++/// Build one shell marker (low spinning tetra-ish box).+pub fn build_shell_mesh(out: &mut Vec<KartVertex>, x: f32, z: f32, ticks: u64) {+ let _ = ticks;+ box_at(out, x, 0.35, z, 0.9, 0.7, 0.9, SHELL_COLOR);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn track_mesh_is_nonempty_and_flat() {+ let mesh = build_track_mesh();+ assert!(!mesh.is_empty());+ for v in mesh.iter().take(1000) {+ assert!(v.pos[1] <= WALL_HEIGHT + 0.01, "y={}", v.pos[1]);+ }+ }++ #[test]+ fn kart_mesh_has_body_cabin_wheels() {+ let mut out = Vec::new();+ build_kart_mesh(&mut out, 0.0, 0.0, 0.0, 0, false, 0.0, false);+ // Body top (6) + front/back/sides (24) + cabin (12) + 4 wheels (4x30).+ assert!(out.len() >= 100, "verts={}", out.len());+ }+}
games/kart/src/main/rust/src/physics.rs
diff --git a/games/kart/src/main/rust/src/physics.rs b/games/kart/src/main/rust/src/physics.rsnew file mode 100644index 0000000000..73952f82ca--- /dev/null+++ b/games/kart/src/main/rust/src/physics.rs@@ -0,0 +1,260 @@+//! Arcade kart physics: one rigid body per seat, integrated on the race tick.+//!+//! The model is deliberately light: karts steer by heading (no slip angle),+//! drift is a grip/charge tradeoff, and off-track pays a flat penalty. The+//! constants mirror the placeholder ([`crate::race`] re-exports its tuning),+//! so the software race and the native engine drive the same line at the same+//! pace and the Kotlin side can swap them behind `KartNative.isAvailable`.+//!+//! Coordinates: +X right, +Z toward the viewer on the top straight, Y up.+//! A kart with yaw `y` faces `(sin y, -cos y)` in (x, z).++use crate::track;++/// Top speed in m/s at full throttle on asphalt. A 640 m lap takes ~25 s.+pub const TOP_SPEED: f32 = 40.0;+/// Seconds 0 → top speed at full throttle. Also the drag time constant:+///+/// the tick integrates `speed += (accel - braking) * dt - speed * dt /+/// ACCEL_TIME`, so sustained speed settles exactly at `TOP_SPEED * throttle`.+/// An AI pace of 0.78 then genuinely runs at 78% (mirroring the placeholder's+/// `AI_PACE`), and lifting off coasts down over a couple of seconds.+pub const ACCEL_TIME: f32 = 2.2;+/// Seconds top speed → standstill at full brake.+pub const BRAKE_TIME: f32 = 1.1;+/// Yaw rate in rad/s at full steering lock and full speed.+pub const TURN_RATE: f32 = 2.4;+/// Fraction of speed kept through full lock while drifting (0.88: drifting+/// trades grip for boost charge, not raw pace — matches the placeholder).+pub const DRIFT_KEEP: f32 = 0.88;+/// Fraction lost through full lock without drifting (~18% scrub).+pub const GRIP_SCRUB: f32 = 0.18;+/// Seconds of continuous drift to earn a boost.+pub const DRIFT_CHARGE_TIME: f32 = 1.2;+/// Boost top-speed multiplier while the charge burns.+pub const BOOST_MULT: f32 = 1.35;+/// Seconds a drift boost burns.+pub const BOOST_TIME: f32 = 1.6;+/// World-space radius that counts as a kart-kart hit.+pub const HIT_RADIUS: f32 = 2.2;++/// One frame of control for one kart, already normalized by the Kotlin+/// fan-in (`GameInputLoop.normalize`): throttle/brake 0..1, steering -1..1,+/// drift held, item edge.+#[derive(Debug, Clone, Copy, Default)]+pub struct DriveInput {+ /// 0..1 forward pedal.+ pub throttle: f32,+ /// -1..1, left negative.+ pub steering: f32,+ /// 0..1 brake pedal.+ pub brake: f32,+ /// Right/left shoulder held.+ pub drift: bool,+ /// Item button, edge-triggered by the caller.+ pub item: bool,+}++/// A kart body: where it is, where it points, how fast it goes.+#[derive(Debug, Clone)]+pub struct KartBody {+ /// World position (y stays 0: the oval is flat).+ pub x: f32,+ /// World position (y stays 0: the oval is flat).+ pub z: f32,+ /// Heading; forward is `(sin yaw, -cos yaw)`.+ pub yaw: f32,+ /// Forward speed in m/s, never negative (braking holds at standstill).+ pub speed: f32,+ /// Arc distance along the centerline; the source of laps and progress.+ pub track_s: f32,+ /// Completed laps.+ pub lap: u32,+ /// Seconds of continuous drift this corner. Resets on release.+ pub drift_charge: f32,+ /// Seconds of boost burn remaining.+ pub boost_left: f32,+ /// Seconds of spin (item hit) remaining; steering is locked while > 0.+ pub spin_left: f32,+}++impl KartBody {+ /// Spawn on the grid: staggered behind the start/finish line, facing -X+ /// down the top straight.+ pub fn spawn(track_s: f32, lane: f32) -> Self {+ let p = track::point_at(track_s);+ Self {+ x: p.x + p.nx * lane,+ z: p.z + p.nz * lane,+ yaw: track::tangent_yaw(&p),+ speed: 0.0,+ track_s,+ lap: 0,+ drift_charge: 0.0,+ boost_left: 0.0,+ spin_left: 0.0,+ }+ }++ /// Advance one tick of `dt` seconds. Clamped to one second: a hitch costs+ /// a frozen frame, never a teleport.+ pub fn tick(&mut self, input: &DriveInput, dt: f32) {+ let dt = dt.clamp(0.0, 1.0);+ if dt <= 0.0 {+ return;+ }+ let throttle = input.throttle.clamp(0.0, 1.0);+ let brake = input.brake.clamp(0.0, 1.0);+ let steering = input.steering.clamp(-1.0, 1.0);++ if self.spin_left > 0.0 {+ // Spun out: bleed speed, rotate, ignore the wheel.+ self.spin_left -= dt;+ self.speed = (self.speed - TOP_SPEED * 1.5 * dt).max(0.0);+ self.yaw += 7.0 * dt;+ } else {+ let grip_loss = steering.abs()+ * if input.drift {+ 1.0 - DRIFT_KEEP+ } else {+ GRIP_SCRUB+ };+ let mut top = TOP_SPEED * (1.0 - grip_loss);+ if self.boost_left > 0.0 {+ self.boost_left -= dt;+ top *= BOOST_MULT;+ }+ // Asphalt vs grass: the track sample at our position decides.+ let p = track::point_at(self.track_s);+ // Re-project: nearest sample by lateral distance is approximated+ // by the current arc position (karts move < 1 m per tick at 60 Hz,+ // so the sample never goes stale within a tick).+ if !track::on_track(self.x, self.z, &p) {+ top *= track::OFF_TRACK_KEEP;+ }+ let accel = TOP_SPEED / ACCEL_TIME * throttle;+ let braking = TOP_SPEED / BRAKE_TIME * brake;+ self.speed += (accel - braking) * dt;+ // Linear drag with time constant ACCEL_TIME: sustained speed+ // settles at TOP * throttle, so an AI pace of 0.78 genuinely runs+ // at 78% (mirroring the placeholder's AI_PACE), and coasting to a+ // standstill takes a couple of seconds rather than forever.+ self.speed -= self.speed * dt / ACCEL_TIME;+ self.speed = self.speed.clamp(0.0, top.max(0.0));++ // Steering authority scales with speed (a parked kart turns in+ // place slowly, a fast one bites). Drift keeps angle at speed.+ let authority = (self.speed / TOP_SPEED).clamp(0.15, 1.0);+ let rate = TURN_RATE * authority * if input.drift { 1.35 } else { 1.0 };+ self.yaw += steering * rate * dt;++ if input.drift && steering.abs() > 0.35 && self.speed > TOP_SPEED * 0.4 {+ self.drift_charge += dt;+ if self.drift_charge >= DRIFT_CHARGE_TIME {+ self.drift_charge = 0.0;+ self.boost_left = BOOST_TIME;+ }+ } else {+ self.drift_charge = 0.0;+ }+ }++ let (fx, fz) = (self.yaw.sin(), -self.yaw.cos());+ self.x += fx * self.speed * dt;+ self.z += fz * self.speed * dt;+ // Snap the arc position back to the centerline: project forward along+ // the tangent from the old sample. (A full closest-point solve runs in+ // the renderer path only when standings need exact progress.)+ let p = track::point_at(self.track_s);+ let along = (self.x - p.x) * p.tx + (self.z - p.z) * p.tz;+ let advanced = track::advance(self.track_s, along);+ if advanced < self.track_s {+ self.lap += 1;+ }+ self.track_s = advanced;+ }++ /// Fire the held item. Returns true on the rising edge (the caller owns+ /// the latch), applying the boost or shell via the race state.+ pub fn boost_now(&mut self) {+ self.boost_left = BOOST_TIME;+ }++ /// Spin from a shell hit. Steering locks until it burns off.+ pub fn spin(&mut self) {+ self.spin_left = 1.2;+ self.boost_left = 0.0;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn flat_out() -> DriveInput {+ DriveInput {+ throttle: 1.0,+ ..Default::default()+ }+ }++ #[test]+ fn reaches_top_speed_and_holds_line() {+ // Steer with the track (a lookahead like the AI): the top straight+ // is only 200 m, so a kart that never turns runs wide onto the grass+ // and settles at the off-track equilibrium instead.+ let mut k = KartBody::spawn(8.0, 0.0);+ for _ in 0..1800 {+ let ahead = track::point_at(track::advance(k.track_s, 12.0));+ let desired = (ahead.x - k.x).atan2(-(ahead.z - k.z));+ let err = track::wrap_angle(desired - k.yaw);+ k.tick(+ &DriveInput {+ throttle: 1.0,+ steering: (err * 1.6).clamp(-1.0, 1.0),+ ..Default::default()+ },+ 1.0 / 60.0,+ );+ }+ assert!(k.speed > TOP_SPEED * 0.85, "speed={}", k.speed);+ assert!(k.lap >= 1, "lap={} s={}", k.lap, k.track_s);+ let p = track::point_at(k.track_s);+ assert!(track::on_track(k.x, k.z, &p), "ran off at {}", k.track_s);+ }++ #[test]+ fn drift_charges_then_boosts() {+ let mut k = KartBody::spawn(0.0, 0.0);+ k.speed = TOP_SPEED;+ let drift = DriveInput {+ throttle: 1.0,+ steering: 0.8,+ drift: true,+ ..Default::default()+ };+ for _ in 0..90 {+ k.tick(&drift, 1.0 / 60.0);+ }+ assert!(k.boost_left > 0.0, "no boost after 1.5 s of drift");+ }++ #[test]+ fn spin_bleeds_speed() {+ let mut k = KartBody::spawn(0.0, 0.0);+ k.speed = TOP_SPEED;+ k.spin();+ k.tick(&flat_out(), 0.5);+ assert!(k.speed < TOP_SPEED * 0.6, "speed={}", k.speed);+ }++ #[test]+ fn lap_increments_past_the_line() {+ let mut k = KartBody::spawn(track::TRACK_LENGTH - 5.0, 0.0);+ k.speed = TOP_SPEED;+ for _ in 0..120 {+ k.tick(&flat_out(), 1.0 / 60.0);+ }+ assert!(k.lap >= 1, "lap={} s={}", k.lap, k.track_s);+ }+}
games/kart/src/main/rust/src/race.rs
diff --git a/games/kart/src/main/rust/src/race.rs b/games/kart/src/main/rust/src/race.rsnew file mode 100644index 0000000000..f76b0f850d--- /dev/null+++ b/games/kart/src/main/rust/src/race.rs@@ -0,0 +1,357 @@+//! The race: seats, laps, items, AI, and the chase camera.+//!+//! The Kotlin loop owns the tick cadence (one `tick_and_render` per frame);+//! this module owns everything inside it. AI seats (`ai-N`) mirror the+//! placeholder's shape (`playerIds` humans first, then AI), so standings JSON+//! reads the same whichever engine backs the race.++use crate::items::{AiDriver, HeldItem, ItemBox, Shell, deal_item, tick_shells};+use crate::physics::{DriveInput, KartBody};+use crate::track;++/// Laps per race. Mirrors the placeholder and the ViewModel's `RACE_LAPS`.+pub const RACE_LAPS: u32 = 3;+/// AI seats per race. Mirrors the placeholder's `aiCount = 3`.+pub const AI_COUNT: usize = 3;+/// Maximum seats (humans + AI). Mirrors the controller protocol's 8.+pub const MAX_SEATS: usize = 8;+/// Item boxes around the loop, alternating lanes.+pub const BOX_COUNT: usize = 6;+/// Chase-cam distance behind the kart in metres.+pub const CAM_DIST: f32 = 9.0;+/// Chase-cam height above the track in metres.+pub const CAM_HEIGHT: f32 = 4.2;+/// Chase-cam look-ahead in front of the kart in metres.+pub const CAM_LOOK_AHEAD: f32 = 7.0;++/// One seat: a human's latest input, or an AI driver.+pub struct Seat {+ /// Seat id: a human player id or `ai-N`.+ pub id: String,+ /// The body on track.+ pub kart: KartBody,+ /// Latest human input (ignored for AI seats).+ pub input: DriveInput,+ /// Item button state last tick: the rising-edge latch for firing.+ pub item_held: bool,+ /// What this seat is holding.+ pub held: HeldItem,+ /// The AI brain, present for `ai-N` seats only.+ pub ai: Option<AiDriver>,+}++/// The whole race. Tick with [`Race::tick`]; read with [`Race::standings`].+pub struct Race {+ seats: Vec<Seat>,+ boxes: Vec<ItemBox>,+ shells: Vec<Shell>,+ /// Ticks since race start (at 60 Hz: 3600 is one minute).+ pub ticks: u64,+ /// True once any kart has finished `RACE_LAPS`.+ pub finished: bool,+ /// Seat index the chase camera follows (the local human, else seat 0).+ pub cam_seat: usize,+}++impl Race {+ /// New race: `human_ids` take the front grid slots, AI fills the rest.+ pub fn new(human_ids: &[String]) -> Self {+ let humans = human_ids.len().min(MAX_SEATS);+ // Up to AI_COUNT rivals round out the grid (never past MAX_SEATS).+ let ai = AI_COUNT.min(MAX_SEATS - humans);+ let mut seats = Vec::with_capacity(humans + ai);+ let grid = (humans + ai).max(1);+ for (i, id) in human_ids.iter().take(humans).enumerate() {+ let lane = grid_lane(i, grid);+ // Grid sits just past the start/finish line on the top straight+ // (s = back): the first wrap then completes one real lap. Behind+ // the line would be the end of the right cap, facing a curve.+ let ahead = 8.0 + (i as f32) * 6.0;+ seats.push(Seat {+ id: id.clone(),+ kart: KartBody::spawn(ahead, lane),+ input: DriveInput::default(),+ item_held: false,+ held: HeldItem::None,+ ai: None,+ });+ }+ for n in 0..ai {+ let i = humans + n;+ let lane = grid_lane(i, grid);+ let ahead = 8.0 + (i as f32) * 6.0;+ seats.push(Seat {+ id: format!("ai-{n}"),+ kart: KartBody::spawn(ahead, lane),+ input: DriveInput::default(),+ item_held: false,+ held: HeldItem::None,+ ai: Some(AiDriver::new(n, ai.max(1))),+ });+ }+ let boxes = (0..BOX_COUNT)+ .map(|i| ItemBox {+ track_s: track::TRACK_LENGTH * (i as f32 + 0.5) / BOX_COUNT as f32,+ lane: if i % 2 == 0 { -4.0 } else { 4.0 },+ respawn_left: 0.0,+ })+ .collect();+ Self {+ seats,+ boxes,+ shells: Vec::new(),+ ticks: 0,+ finished: false,+ cam_seat: 0,+ }+ }++ /// Seat count (humans + AI).+ pub fn seat_count(&self) -> usize {+ self.seats.len()+ }++ /// Feed one human sample. Unknown ids are ignored: a phone that joined+ /// mid-race drives from the next race, never this one.+ pub fn set_input(&mut self, seat: usize, input: DriveInput) {+ if let Some(s) = self.seats.get_mut(seat) {+ if s.ai.is_none() {+ s.input = input;+ }+ }+ }++ /// Index of the seat with this id, if it is racing.+ pub fn seat_of(&self, id: &str) -> Option<usize> {+ self.seats.iter().position(|s| s.id == id)+ }++ /// Advance one tick of `dt` seconds: karts, boxes, shells, laps.+ pub fn tick(&mut self, dt: f32) {+ let dt = dt.clamp(0.0, 0.25);+ self.ticks += 1;+ for b in &mut self.boxes {+ if b.respawn_left > 0.0 {+ b.respawn_left -= dt;+ }+ }+ // Order first: items deal by race position.+ let mut order: Vec<usize> = (0..self.seats.len()).collect();+ order.sort_by(|&a, &b| {+ progress_key(&self.seats[b].kart)+ .partial_cmp(&progress_key(&self.seats[a].kart))+ .unwrap_or(std::cmp::Ordering::Equal)+ });+ for (pos, &si) in order.iter().enumerate() {+ // Read the seat's state first (immutable borrows end here).+ let seat_count = self.seats.len();+ let (control, should_fire, held_item, kx, kz) = {+ let seat = &mut self.seats[si];+ let mut control = if let Some(ai) = &mut seat.ai {+ let mut c = ai.control(&seat.kart);+ // AI fires shells at the kart ahead, mushrooms on straights.+ if seat.held == HeldItem::Shell && pos > 0 {+ c.item = true;+ } else if seat.held == HeldItem::Mushroom {+ let p = track::point_at(seat.kart.track_s);+ if track::heading_error(seat.kart.yaw, &p).abs() < 0.1 {+ c.item = true;+ }+ }+ c+ } else {+ seat.input+ };+ // Rising edge: holding the button does not fire twice.+ let fire = control.item && !seat.item_held;+ seat.item_held = control.item;+ control.item = false;+ (control, fire, seat.held, seat.kart.x, seat.kart.z)+ };+ // Tick the body (mutable borrow of one seat only).+ {+ let seat = &mut self.seats[si];+ seat.kart.tick(&control, dt);+ if seat.kart.lap >= RACE_LAPS {+ self.finished = true;+ }+ }+ if should_fire {+ self.fire_item(si);+ }+ // Item boxes: nearest box within radius and off cooldown deals.+ if held_item == HeldItem::None {+ for b in &mut self.boxes {+ if b.respawn_left > 0.0 {+ continue;+ }+ let p = track::point_at(b.track_s);+ let bx = p.x + p.nx * b.lane;+ let bz = p.z + p.nz * b.lane;+ if (kx - bx).hypot(kz - bz) < crate::items::BOX_RADIUS {+ self.seats[si].held = deal_item(pos, seat_count);+ b.respawn_left = crate::items::BOX_RESPAWN;+ break;+ }+ }+ }+ }+ let karts: Vec<KartBody> = self.seats.iter().map(|s| s.kart.clone()).collect();+ for hit in tick_shells(&mut self.shells, &karts, dt) {+ if let Some(s) = self.seats.get_mut(hit) {+ s.kart.spin();+ }+ }+ }++ /// Fire seat `si`'s held item (no-op when empty).+ fn fire_item(&mut self, si: usize) {+ let seat = match self.seats.get_mut(si) {+ Some(s) => s,+ None => return,+ };+ match seat.held {+ HeldItem::None => {}+ HeldItem::Mushroom => {+ seat.kart.boost_now();+ seat.held = HeldItem::None;+ }+ HeldItem::Shell => {+ let (x, z, yaw) = (seat.kart.x, seat.kart.z, seat.kart.yaw);+ self.shells.push(Shell {+ owner: si,+ x: x + yaw.sin() * 3.0,+ z: z - yaw.cos() * 3.0,+ yaw,+ life: crate::items::SHELL_LIFE,+ grace: 0.5,+ });+ seat.held = HeldItem::None;+ }+ }+ }++ /// Standings: (seat id, lap, 0..1 lap progress), leaders first.+ pub fn standings(&self) -> Vec<(String, u32, f32)> {+ let mut v: Vec<(String, u32, f32)> = self+ .seats+ .iter()+ .map(|s| {+ let lap = s.kart.lap.min(RACE_LAPS);+ let frac = (s.kart.track_s / track::TRACK_LENGTH).clamp(0.0, 1.0);+ (s.id.clone(), lap, frac)+ })+ .collect();+ v.sort_by(|a, b| {+ (b.1, b.2)+ .partial_cmp(&(a.1, a.2))+ .unwrap_or(std::cmp::Ordering::Equal)+ });+ v+ }++ /// Winner once finished: the first across the line.+ pub fn winner(&self) -> Option<String> {+ if !self.finished {+ return None;+ }+ self.standings().first().map(|(id, _, _)| id.clone())+ }++ /// Chase camera: position and look-at for the followed kart.+ pub fn camera(&self) -> ([f32; 3], [f32; 3]) {+ let seat = self.seats.get(self.cam_seat).or(self.seats.first());+ match seat {+ None => ([0.0, 8.0, 20.0], [0.0, 0.0, 0.0]),+ Some(s) => {+ let (fx, fz) = (s.kart.yaw.sin(), -s.kart.yaw.cos());+ let pos = [+ s.kart.x - fx * CAM_DIST,+ CAM_HEIGHT,+ s.kart.z - fz * CAM_DIST,+ ];+ let look = [+ s.kart.x + fx * CAM_LOOK_AHEAD,+ 1.0,+ s.kart.z + fz * CAM_LOOK_AHEAD,+ ];+ (pos, look)+ }+ }+ }++ /// Kart world transforms for the renderer: (x, z, yaw, is_ai).+ pub fn kart_transforms(&self) -> Vec<(f32, f32, f32, bool)> {+ self.seats+ .iter()+ .map(|s| (s.kart.x, s.kart.z, s.kart.yaw, s.ai.is_some()))+ .collect()+ }++ /// Live shell positions for the renderer: (x, z).+ pub fn shell_positions(&self) -> Vec<(f32, f32)> {+ self.shells.iter().map(|s| (s.x, s.z)).collect()+ }++ /// Item-box world positions (only the live ones) for the renderer.+ pub fn box_positions(&self) -> Vec<(f32, f32)> {+ self.boxes+ .iter()+ .filter(|b| b.respawn_left <= 0.0)+ .map(|b| {+ let p = track::point_at(b.track_s);+ (p.x + p.nx * b.lane, p.z + p.nz * b.lane)+ })+ .collect()+ }+}++/// Total progress in laps (fractional) for ordering.+fn progress_key(k: &KartBody) -> f32 {+ k.lap as f32 + k.track_s / track::TRACK_LENGTH+}++/// Grid lane stagger: alternate ±3 m so karts don't spawn stacked.+fn grid_lane(i: usize, _grid: usize) -> f32 {+ if i % 2 == 0 {+ -3.0+ } else {+ 3.0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn grid_then_race_then_winner() {+ let ids = vec!["p1".to_string()];+ let mut race = Race::new(&ids);+ assert!(race.seat_count() > ids.len(), "AI should fill the grid");+ let drive = DriveInput {+ throttle: 1.0,+ ..Default::default()+ };+ for _ in 0..60 * 120 {+ race.set_input(0, drive);+ race.tick(1.0 / 60.0);+ if race.finished {+ break;+ }+ }+ assert!(race.finished, "nobody finished 3 laps in 2 minutes");+ assert!(race.winner().is_some());+ }++ #[test]+ fn camera_follows_seat_zero() {+ let race = Race::new(&["p1".to_string()]);+ let (pos, look) = race.camera();+ assert!(pos[1] > 0.0, "camera under the track");+ assert!(+ (pos[0] - look[0]).hypot(pos[2] - look[2]) > CAM_DIST * 0.5,+ "camera on top of the kart"+ );+ }+}
games/kart/src/main/rust/src/track.rs
diff --git a/games/kart/src/main/rust/src/track.rs b/games/kart/src/main/rust/src/track.rsnew file mode 100644index 0000000000..6a6dd14b64--- /dev/null+++ b/games/kart/src/main/rust/src/track.rs@@ -0,0 +1,210 @@+//! Sunset Oval: the only track. A rounded-rectangle loop built from two+//! straights and two semicircle end caps, centred on the origin.+//!+//! The centerline is parameterized by arc length ([TRACK_LENGTH] metres), so+//! progress, laps, and AI steering all share one notion of "where on the+//! track". The half-width decides asphalt vs grass; karts outside it pay the+//! off-track penalty from physics.+//!+//! Yaw convention (shared with physics and the camera): a kart with yaw `y`+//! faces `(sin y, -cos y)` in (x, z), so yaw 0 is -Z and positive yaw turns+//! toward +X.++/// Total metres of centerline per lap. Derived from the geometry below+/// (`2 * STRAIGHT + 2 * PI * RADIUS` ≈ 777 m), never hand-set: a length that+/// disagrees with the segments truncates the last cap and the wrap joint jumps.+pub const TRACK_LENGTH: f32 = 2.0 * STRAIGHT + 2.0 * std::f32::consts::PI * RADIUS;+/// Straight section length in metres (two of them).+pub const STRAIGHT: f32 = 200.0;+/// End-cap radius in metres. `2 * STRAIGHT + 2 * PI * RADIUS` is the length.+pub const RADIUS: f32 = 60.0;+/// Half the asphalt width in metres. Karts wider than this are off track.+pub const HALF_WIDTH: f32 = 9.0;+/// Fraction of top speed kept on grass. Punishing but recoverable.+pub const OFF_TRACK_KEEP: f32 = 0.55;++/// A point on the centerline plus the direction of travel and the left normal.+#[derive(Debug, Clone, Copy)]+pub struct TrackPoint {+ /// Centre of the asphalt at this distance.+ pub x: f32,+ /// Centre of the asphalt at this distance.+ pub z: f32,+ /// Unit tangent of travel.+ pub tx: f32,+ /// Unit tangent of travel.+ pub tz: f32,+ /// Unit normal pointing left of travel (`(-tz, tx)`).+ pub nx: f32,+ /// Unit normal pointing left of travel (`(-tz, tx)`).+ pub nz: f32,+}++/// Centre x of the right-hand end cap (the +X semicircle bulge).+const CAP_CX: f32 = STRAIGHT / 2.0;++/// Centre x of the left-hand end cap. Both caps sit on the z = 0 axis.+const CAP_CX_LEFT: f32 = -STRAIGHT / 2.0;++fn wrap(s: f32) -> f32 {+ s.rem_euclid(TRACK_LENGTH)+}++/// Centerline sample at arc distance `s` metres. Wraps past the line.+///+/// Segments: top straight (travel -X at z = -R), left cap (around+/// `CAP_CX_LEFT`, from the top round the -X bulge to the bottom), bottom+/// straight (travel +X at z = +R), right cap (around `CAP_CX` back to the top).+/// Tangents and normals are continuous across every joint.+pub fn point_at(s: f32) -> TrackPoint {+ let s = wrap(s);+ let cap_len = std::f32::consts::PI * RADIUS;+ if s < STRAIGHT {+ // Top straight: from (+CAP_CX, -R) to (-CAP_CX, -R), travel -X.+ TrackPoint {+ x: CAP_CX - s,+ z: -RADIUS,+ tx: -1.0,+ tz: 0.0,+ nx: 0.0,+ nz: -1.0,+ }+ } else if s < STRAIGHT + cap_len {+ // Left cap: theta 0..PI. pos = (cx - R sin t, -R cos t):+ // t=0 is the top joint (-CAP_CX, -R), t=PI/2 the -X bulge, t=PI the+ // bottom joint. Tangent (-cos t, sin t) is -X at t=0 and +X at t=PI.+ let theta = (s - STRAIGHT) / RADIUS;+ let (sin, cos) = theta.sin_cos();+ TrackPoint {+ x: CAP_CX_LEFT - RADIUS * sin,+ z: -RADIUS * cos,+ tx: -cos,+ tz: sin,+ nx: -sin,+ nz: -cos,+ }+ } else if s < 2.0 * STRAIGHT + cap_len {+ // Bottom straight: from (-CAP_CX, +R) to (+CAP_CX, +R), travel +X.+ let t = s - STRAIGHT - cap_len;+ TrackPoint {+ x: CAP_CX_LEFT + t,+ z: RADIUS,+ tx: 1.0,+ tz: 0.0,+ nx: 0.0,+ nz: 1.0,+ }+ } else {+ // Right cap: theta 0..PI. pos = (cx + R sin t, +R cos t):+ // t=0 is the bottom joint (+CAP_CX, +R), t=PI/2 the +X bulge, t=PI+ // the top joint. Tangent (cos t, -sin t) is +X at t=0, -X at t=PI.+ let theta = (s - 2.0 * STRAIGHT - cap_len) / RADIUS;+ let (sin, cos) = theta.sin_cos();+ TrackPoint {+ x: CAP_CX + RADIUS * sin,+ z: RADIUS * cos,+ tx: cos,+ tz: -sin,+ nx: sin,+ nz: cos,+ }+ }+}++/// Signed lateral offset in metres: negative is left of centre, positive right.+pub fn lateral(x: f32, z: f32, p: &TrackPoint) -> f32 {+ (x - p.x) * p.nx + (z - p.z) * p.nz+}++/// True when the point is on asphalt (with a half-metre kerb of forgiveness).+pub fn on_track(x: f32, z: f32, p: &TrackPoint) -> bool {+ lateral(x, z, p).abs() <= HALF_WIDTH + 0.5+}++/// Advance `s` by `ds` metres, wrapping past the start/finish line.+pub fn advance(s: f32, ds: f32) -> f32 {+ wrap(s + ds)+}++/// Yaw whose forward (`(sin y, -cos y)`) equals the tangent.+pub fn tangent_yaw(p: &TrackPoint) -> f32 {+ p.tx.atan2(-p.tz)+}++/// Signed heading error in radians between kart yaw and track tangent.+pub fn heading_error(yaw: f32, p: &TrackPoint) -> f32 {+ wrap_angle(tangent_yaw(p) - yaw)+}++/// Wrap to [-PI, PI].+pub fn wrap_angle(a: f32) -> f32 {+ let two_pi = 2.0 * std::f32::consts::PI;+ let mut v = a.rem_euclid(two_pi);+ if v > std::f32::consts::PI {+ v -= two_pi;+ }+ v+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn length_matches_geometry() {+ let cap = 2.0 * std::f32::consts::PI * RADIUS;+ assert!((TRACK_LENGTH - (2.0 * STRAIGHT + cap)).abs() < 0.01);+ }++ #[test]+ fn straights_run_opposite_directions() {+ let top = point_at(10.0);+ assert!((top.tx + 1.0).abs() < 0.001 && top.tz.abs() < 0.001);+ let bottom = point_at(STRAIGHT + std::f32::consts::PI * RADIUS + 10.0);+ assert!((bottom.tx - 1.0).abs() < 0.001 && bottom.tz.abs() < 0.001);+ }++ #[test]+ fn joints_are_continuous() {+ // Sample densely across every joint; consecutive samples must stay+ // within one metre (at 2 m steps the cap moves ~2 m per step).+ let mut prev = point_at(0.0);+ let mut s = 2.0;+ while s < TRACK_LENGTH + 2.0 {+ let p = point_at(s);+ let dx = p.x - prev.x;+ let dz = p.z - prev.z;+ assert!(dx.hypot(dz) < 3.0, "jump at s={s}: {dx},{dz}");+ prev = p;+ s += 2.0;+ }+ }++ #[test]+ fn cap_midpoints_bulge_outward() {+ let cap_len = std::f32::consts::PI * RADIUS;+ let left = point_at(STRAIGHT + cap_len / 2.0);+ assert!(left.x < CAP_CX_LEFT - RADIUS + 1.0, "left bulge x={}", left.x);+ let right = point_at(2.0 * STRAIGHT + cap_len * 1.5);+ assert!(right.x > CAP_CX + RADIUS - 1.0, "right bulge x={}", right.x);+ }++ #[test]+ fn centre_is_on_track_edges_are_not() {+ let p = point_at(50.0);+ assert!(on_track(p.x, p.z, &p));+ assert!(!on_track(+ p.x + p.nx * (HALF_WIDTH + 2.0),+ p.z + p.nz * (HALF_WIDTH + 2.0),+ &p+ ));+ }++ #[test]+ fn wraps_past_the_line() {+ assert!(advance(TRACK_LENGTH - 1.0, 2.0) < 2.0);+ let a = point_at(TRACK_LENGTH + 5.0);+ let b = point_at(5.0);+ assert!((a.x - b.x).abs() < 0.001 && (a.z - b.z).abs() < 0.001);+ }+}
games/kart/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/kart/src/main/rust/src/vulkan/buffers.rs b/games/kart/src/main/rust/src/vulkan/buffers.rsnew file mode 100644index 0000000000..05a5c68488--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/buffers.rs@@ -0,0 +1,149 @@+//! Vertex + uniform buffers: the kart vertex format, the view-projection+//! UBO, and the host-visible upload helper.+//!+//! Same arrangement as games/voxels `vulkan/buffers.rs`: one+//! `AllocatedBuffer` (buffer + memory + size) with an `upload` that maps,+//! copies, and unmaps. The world is small (one oval + ≤8 karts), so per-frame+//! full re-uploads of the dynamic mesh stay comfortably in budget.+use ash::vk;+use std::mem;++/// One vertex: world position + flat RGB. Layout must match `kart.vert`+/// (`location 0 = pos`, `location 1 = color`).+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct KartVkVertex {+ /// World position.+ pub pos: [f32; 3],+ /// Flat RGB.+ pub color: [f32; 3],+}++impl KartVkVertex {+ /// Single binding, stride = struct size, per-vertex rate.+ pub fn binding_description() -> vk::VertexInputBindingDescription {+ vk::VertexInputBindingDescription::default()+ .binding(0)+ .stride(mem::size_of::<Self>() as u32)+ .input_rate(vk::VertexInputRate::VERTEX)+ }++ /// Two attributes: `vec3 pos` at 0, `vec3 color` at 1.+ pub fn attribute_descriptions() -> [vk::VertexInputAttributeDescription; 2] {+ [+ vk::VertexInputAttributeDescription::default()+ .binding(0)+ .location(0)+ .format(vk::Format::R32G32B32_SFLOAT)+ .offset(mem::offset_of!(KartVkVertex, pos) as u32),+ vk::VertexInputAttributeDescription::default()+ .binding(0)+ .location(1)+ .format(vk::Format::R32G32B32_SFLOAT)+ .offset(mem::offset_of!(KartVkVertex, color) as u32),+ ]+ }+}++/// Uniforms for `kart.vert`/`kart.frag`: view-projection, sun, camera.+/// `#[repr(C)]` + explicit padding so the host layout matches std140.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct KartUbo {+ /// `view * proj` (the Y flip lives in the shader, not here).+ pub view_proj: [[f32; 4]; 4],+ /// Fixed sun direction (normalized on upload).+ pub sun_dir: [f32; 3],+ /// std140 pad.+ pub _pad0: f32,+ /// Chase-cam world position (the fog origin).+ pub cam_pos: [f32; 3],+ /// std140 pad.+ pub _pad1: f32,+}++impl Default for KartUbo {+ fn default() -> Self {+ Self {+ view_proj: glam::Mat4::IDENTITY.to_cols_array_2d(),+ sun_dir: [0.35, -1.0, 0.45],+ _pad0: 0.0,+ cam_pos: [0.0, 4.0, 20.0],+ _pad1: 0.0,+ }+ }+}++/// A device buffer with its memory: the unit everything else allocates.+pub struct AllocatedBuffer {+ /// The Vulkan buffer.+ pub buffer: vk::Buffer,+ /// Its backing memory.+ pub memory: vk::DeviceMemory,+ /// Requested size (allocation may be larger).+ pub size: vk::DeviceSize,+}++impl AllocatedBuffer {+ /// Allocate host-visible coherent memory and bind it. Fails cleanly.+ pub unsafe fn new(+ instance: &ash::Instance,+ device: &ash::Device,+ phys: vk::PhysicalDevice,+ size: vk::DeviceSize,+ usage: vk::BufferUsageFlags,+ ) -> Result<Self, String> {+ let info = vk::BufferCreateInfo::default()+ .size(size.max(1))+ .usage(usage)+ .sharing_mode(vk::SharingMode::EXCLUSIVE);+ let buffer = device+ .create_buffer(&info, None)+ .map_err(|e| format!("create buffer {e:?}"))?;+ let mem_reqs = device.get_buffer_memory_requirements(buffer);+ let mem_props = instance.get_physical_device_memory_properties(phys);+ let properties =+ vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;+ let mem_type = (0..mem_props.memory_type_count)+ .find(|&i| {+ (mem_reqs.memory_type_bits & (1 << i)) != 0+ && mem_props.memory_types[i as usize]+ .property_flags+ .contains(properties)+ })+ .ok_or_else(|| format!("no mem type {size}"))?;+ let alloc = vk::MemoryAllocateInfo::default()+ .allocation_size(mem_reqs.size)+ .memory_type_index(mem_type);+ let memory = device+ .allocate_memory(&alloc, None)+ .map_err(|e| format!("alloc {e:?}"))?;+ device+ .bind_buffer_memory(buffer, memory, 0)+ .map_err(|e| format!("bind {e:?}"))?;+ Ok(Self { buffer, memory, size })+ }++ /// Map, copy, unmap. Empty uploads are a no-op.+ pub unsafe fn upload(&self, device: &ash::Device, data: &[u8]) {+ if data.is_empty() {+ return;+ }+ let ptr = device+ .map_memory(+ self.memory,+ 0,+ data.len() as u64,+ vk::MemoryMapFlags::empty(),+ )+ .unwrap() as *mut u8;+ ptr.copy_from_nonoverlapping(data.as_ptr(), data.len());+ device.unmap_memory(self.memory);+ }++ /// Free memory + buffer.+ pub unsafe fn destroy(&mut self, device: &ash::Device) {+ device.destroy_buffer(self.buffer, None);+ device.free_memory(self.memory, None);+ }+}
games/kart/src/main/rust/src/vulkan/context.rs
diff --git a/games/kart/src/main/rust/src/vulkan/context.rs b/games/kart/src/main/rust/src/vulkan/context.rsnew file mode 100644index 0000000000..4ae7a22530--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/context.rs@@ -0,0 +1,158 @@+//! Vulkan surface bootstrap: instance, Android surface, device, queue.+//!+//! Same arrangement as games/voxels `vulkan/context.rs`: `Entry::load` ++//! `khr::surface` + `khr::
Diff truncated.