games-hub: 3D Yuu avatars with skeleton and pose presets
- Commit
edc457bb3ed5beb9b426a0d0e2aae1cfaacc74e6- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-19 19:54 UTC (1 month ago)
- Parents
52c2b66
Diff
Cargo.lock
diff --git a/Cargo.lock b/Cargo.lockindex 40e4c991e7..4346a5b7a8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -332,6 +332,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" +[[package]]+name = "base64"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"+ [[package]] name = "base64" version = "0.22.1"@@ -1757,6 +1763,45 @@ dependencies = [ "web-sys", ] +[[package]]+name = "gltf"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3ce1918195723ce6ac74e80542c5a96a40c2b26162c1957a5cd70799b8cacf7"+dependencies = [+ "base64 0.13.1",+ "byteorder",+ "gltf-json",+ "image",+ "lazy_static",+ "serde_json",+ "urlencoding",+]++[[package]]+name = "gltf-derive"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "14070e711538afba5d6c807edb74bcb84e5dbb9211a3bf5dea0dfab5b24f4c51"+dependencies = [+ "inflections",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "gltf-json"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6176f9d60a7eab0a877e8e96548605dedbde9190a7ae1e80bbcc1c9af03ab14"+dependencies = [+ "gltf-derive",+ "serde",+ "serde_derive",+ "serde_json",+]+ [[package]] name = "group" version = "0.13.0"@@ -2267,6 +2312,8 @@ dependencies = [ "moxcms", "num-traits", "png",+ "zune-core",+ "zune-jpeg", ] [[package]]@@ -2287,6 +2334,12 @@ dependencies = [ "serde_core", ] +[[package]]+name = "inflections"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a257582fdcde896fd96463bf2d40eefea0580021c0712a0e2b028b60b47a837a"+ [[package]] name = "inout" version = "0.1.4"@@ -5179,6 +5232,12 @@ dependencies = [ "serde", ] +[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+ [[package]] name = "utf8-zero" version = "0.8.1"@@ -5751,6 +5810,20 @@ dependencies = [ "serde_json", ] +[[package]]+name = "yuu_avatar"+version = "0.1.0"+dependencies = [+ "ash",+ "glam",+ "glow",+ "gltf",+ "jni",+ "khronos-egl",+ "serde",+ "serde_json",+]+ [[package]] name = "zerocopy" version = "0.8.63"
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex 8a945cbfbc..f184c7b8ca 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -25,6 +25,7 @@ members = [ "share/src/main/rust", "games/voxels/src/main/rust", "games/kart/src/main/rust",+ "games/hub/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 8f913bd555..368ce4ac9e 100644--- a/games/hub/build.gradle.kts+++ b/games/hub/build.gradle.kts@@ -15,6 +15,22 @@ android { } } +androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++// Yuu 3D avatar engine (glTF upper-body base mesh, skeletal skinning, preset+// poses, Vulkan-first + GLES fallback). Same arrangement as games/kart: the+// crate builds into rustJniLibs and YuuAvatarNative.isAvailable gates every+// call, so devices without the .so keep the 2D YuuFace preview. The Vulkan+// swapchain bring-up is still landing (new() reports unavailable); the GLES+// path is complete.+rustNativeLib("yuu_avatar", "yuu")+ dependencies { implementation(project(":library")) implementation(project(":library:ui"))
games/hub/src/main/java/com/vayunmathur/games/hub/data/HubStores.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/HubStores.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/HubStores.ktindex 08e2a5007f..3145ef338a 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/data/HubStores.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/HubStores.kt@@ -89,6 +89,8 @@ class YuuStore internal constructor(private val repository: GamesHubRepository) suspend fun getYuu(id: Long): YuuUiModel? = yuuDao.getById(id)?.toUiModel() + suspend fun getProfileYuu(): YuuUiModel? = yuuDao.getProfile()?.toUiModel()+ suspend fun createYuu(name: String, config: YuuFaceConfig): Long = yuuDao.upsert( YuuEntity(
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/YuuDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/YuuDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/YuuDao.ktindex 64e9b0c487..9d574e86eb 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/YuuDao.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/YuuDao.kt@@ -22,6 +22,9 @@ interface YuuDao { @Query("SELECT * FROM yuus WHERE isProfile = 1 LIMIT 1") fun flowProfile(): Flow<YuuEntity?> + @Query("SELECT * FROM yuus WHERE isProfile = 1 LIMIT 1")+ suspend fun getProfile(): YuuEntity?+ @Query("DELETE FROM yuus WHERE id = :id") suspend fun deleteById(id: Long)
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/YuuFaceConfig.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/YuuFaceConfig.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/YuuFaceConfig.ktindex 6abca95b10..fd686fc038 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/YuuFaceConfig.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/YuuFaceConfig.kt@@ -8,6 +8,9 @@ import kotlinx.serialization.Serializable * Indices are positional (0..count-1 per part) so the renderer owns the variant lookup; * colors are ARGB longs into the fixed palettes below; tweaks are normalized 0..1 floats. * Only this config is persisted, keeping it portable to the future 3D games.+ *+ * [poseId] selects a 3D preset pose (see `YuuPose`); null means the idle pose.+ * It travels inside this JSON so no Room migration is needed for poses. */ @Serializable data class YuuFaceConfig(@@ -39,6 +42,7 @@ data class YuuFaceConfig( val moleStyle: Int = 0, val wrinkleStyle: Int = 0, val blushStyle: Int = 0,+ val poseId: String? = null, ) { companion object { /** Variant counts the Canvas renderer supports for v1 (Mii-like breadth). */
games/hub/src/main/java/com/vayunmathur/games/hub/platform/YuuAvatarNative.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/platform/YuuAvatarNative.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/platform/YuuAvatarNative.ktnew file mode 100644index 0000000000..130c995e12--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/platform/YuuAvatarNative.kt@@ -0,0 +1,82 @@+// PACKAGE STRUCTURE EXCEPTION (JNI): FQN frozen for native RegisterNatives/symbol mangling+// NOTE: file lives under platform/ but package is ...games.hub.util to match the native symbol+@file:Suppress("InvalidPackageDeclaration")+package com.vayunmathur.games.hub.util++import com.vayunmathur.library.log.Log++/**+ * The 3D avatar engine bridge, shaped like kart's `KartNative`.+ *+ * Native calls are no-ops behind [isAvailable] = false (no `libyuu_avatar`+ * on this device, or the Vulkan swapchain bring-up hasn't landed), and hero+ * surfaces fall back to the 2D [com.vayunmathur.games.hub.ui.components.YuuFace]+ * preview 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 kart/voxels: the view calls surfaceCreated/+ * Changed/Destroyed, the engine spawns its own 60 Hz render thread and ticks+ * the avatar there. Traits + pose cross as JSON strings; the pose gallery+ * reads back the preset ids.+ */+object YuuAvatarNative {+ /** False until `libyuu_avatar` ships. Checked once per surface, like kart. */+ val isAvailable: Boolean = try {+ System.loadLibrary("yuu_avatar")+ nativeInit()+ Log.status("YuuAvatarNative", "libyuu_avatar loaded")+ true+ } catch (t: Throwable) {+ Log.status("YuuAvatarNative", "libyuu_avatar absent - using 2D Yuu preview")+ false+ }++ /**+ * Set traits + pose. `configJson` is the `YuuFaceConfig` JSON;+ * `poseJson` is a preset id (e.g. "wave") or `{"id": ...}`. No-op+ * without the library.+ */+ fun setConfig(configJson: String, poseJson: String) {+ if (!isAvailable) return+ nativeSetConfig(configJson, poseJson)+ }++ /** Pose preset ids as JSON (`["idle","wave",...]`) for the gallery. */+ fun getPosesJson(): String = if (isAvailable) nativeGetPosesJson() else "[]"++ /** Surface lifecycle, called by the avatar surface view. */+ 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 setPaused(paused: Boolean) {+ if (!isAvailable) return+ nativeSetPaused(paused)+ }++ fun onDestroy() {+ if (!isAvailable) return+ nativeOnDestroy()+ }++ private external fun nativeInit(): Boolean+ private external fun nativeSetConfig(configJson: String, poseJson: String)+ private external fun nativeGetPosesJson(): String+ private external fun nativeSurfaceCreated(surface: android.view.Surface)+ private external fun nativeSurfaceChanged(width: Int, height: Int)+ private external fun nativeSurfaceDestroyed()+ private external fun nativeSetPaused(paused: Boolean)+ private external fun nativeOnDestroy()+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.ktnew file mode 100644index 0000000000..74778bb9ec--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.kt@@ -0,0 +1,78 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.compose.ui.viewinterop.AndroidView+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import com.vayunmathur.games.hub.data.entities.YuuFaceConfig+import com.vayunmathur.games.hub.data.entities.encode+import com.vayunmathur.games.hub.util.YuuAvatarNative+import kotlinx.coroutines.delay++/**+ * 3D Yuu hero surface: the native avatar engine draws into a [YuuAvatarSurfaceView]+ * layered in a [Box]. Traits + pose cross as JSON; config updates debounce so+ * typing in the editor doesn't spam JNI.+ *+ * Falls back to the 2D [YuuFace] preview when native is unavailable (no+ * `libyuu_avatar`, or the Vulkan swapchain bring-up hasn't landed) — hero+ * surfaces never render blank.+ *+ * Single hero instance only: the engine owns one renderer. The plaza grid and+ * editor variant cells keep 2D thumbnails (see the plan's perf gate).+ */+@Composable+fun YuuAvatar3D(+ config: YuuFaceConfig,+ poseId: String?,+ modifier: Modifier = Modifier,+ withFallback: Boolean = true,+) {+ if (!YuuAvatarNative.isAvailable) {+ if (withFallback) {+ YuuFace(config = config, withBody = true, modifier = modifier)+ }+ return+ }+ val configJson = remember(config) { config.encode() }+ val pose = poseId ?: "idle"+ val lifecycle = LocalLifecycleOwner.current.lifecycle++ DisposableEffect(lifecycle) {+ val observer = LifecycleEventObserver { _, event ->+ when (event) {+ Lifecycle.Event.ON_PAUSE -> YuuAvatarNative.setPaused(true)+ Lifecycle.Event.ON_RESUME -> YuuAvatarNative.setPaused(false)+ else -> Unit+ }+ }+ lifecycle.addObserver(observer)+ onDispose {+ lifecycle.removeObserver(observer)+ YuuAvatarNative.surfaceDestroyed()+ }+ }++ // Debounced config push: rapid draft edits coalesce into one JNI call.+ LaunchedEffect(configJson, pose) {+ delay(200)+ YuuAvatarNative.setConfig(configJson, pose)+ }++ Box(modifier = modifier) {+ // 2D underneath: if the surface never draws (both backends failed),+ // the hero still shows the Yuu instead of a black hole.+ YuuFace(config = config, withBody = true, modifier = Modifier.fillMaxSize())+ AndroidView(+ factory = { ctx -> YuuAvatarSurfaceView(ctx) },+ modifier = Modifier.fillMaxSize(),+ )+ }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.ktnew file mode 100644index 0000000000..5058143330--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.hub.ui.components++import android.content.Context+import android.util.AttributeSet+import android.view.SurfaceHolder+import android.view.SurfaceView+import com.vayunmathur.games.hub.util.YuuAvatarNative+import com.vayunmathur.library.log.Log++/**+ * The native 3D avatar viewport: a SurfaceView the Rust engine draws into.+ *+ * Same arrangement as kart's `KartSurfaceView`: the view owns nothing but+ * the surface lifecycle, the engine owns the render thread, and every JNI+ * call is guarded by [YuuAvatarNative.isAvailable] so a device without+ * `libyuu_avatar` shows the 2D fallback instead of crashing.+ */+class YuuAvatarSurfaceView @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 (!YuuAvatarNative.isAvailable) return+ // JNI boundary: native throws unchecked exceptions, all logged here.+ try {+ YuuAvatarNative.surfaceCreated(holder.surface)+ ready = true+ } catch (e: RuntimeException) {+ Log.error("YuuAvatarSurface", "surfaceCreated failed", e)+ }+ }++ @Suppress("TooGenericExceptionCaught")+ override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {+ if (!YuuAvatarNative.isAvailable || !ready) return+ try {+ YuuAvatarNative.surfaceChanged(width, height)+ } catch (e: RuntimeException) {+ Log.error("YuuAvatarSurface", "surfaceChanged failed", e)+ }+ }++ @Suppress("TooGenericExceptionCaught")+ override fun surfaceDestroyed(holder: SurfaceHolder) {+ if (!YuuAvatarNative.isAvailable) return+ try {+ YuuAvatarNative.surfaceDestroyed()+ ready = false+ } catch (e: RuntimeException) {+ Log.error("YuuAvatarSurface", "surfaceDestroyed failed", e)+ }+ }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuPoseGallery.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuPoseGallery.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuPoseGallery.ktnew file mode 100644index 0000000000..cb46ed2e6f--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuPoseGallery.kt@@ -0,0 +1,36 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.hub.ui.yuu.YUU_POSES+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.Text++/**+ * Preset pose gallery: one chip per 3D pose preset (idle, wave, thumbs up,+ * thinking, cheering). Stateless — selection writes back through the+ * caller's draft or profile update.+ */+@Composable+fun YuuPoseGallery(+ selectedPoseId: String?,+ onSelect: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ LazyRow(+ modifier = modifier,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(YUU_POSES) { pose ->+ FilterChip(+ selected = (selectedPoseId ?: "idle") == pose.id,+ onClick = { onSelect(pose.id) },+ label = { Text(pose.name) },+ )+ }+ }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.ktindex 58ce1565d9..408aea274c 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt@@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items@@ -27,6 +28,7 @@ import com.vayunmathur.games.hub.ui.components.GameCard import com.vayunmathur.games.hub.ui.components.StatCard import com.vayunmathur.games.hub.ui.components.StreakCard import com.vayunmathur.games.hub.ui.components.XpProgressBar+import com.vayunmathur.games.hub.ui.components.YuuAvatar3D import com.vayunmathur.games.hub.ui.components.YuuBadge import com.vayunmathur.games.hub.util.DashboardActions import com.vayunmathur.games.hub.util.DashboardUiState@@ -74,7 +76,11 @@ fun DashboardScreen( Card(onClick = actions::openProfile, modifier = Modifier.fillMaxWidth()) { Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { if (BuildConfig.DEV_BUILD && state.profileYuu != null) {- YuuBadge(config = state.profileYuu.config, large = true)+ YuuAvatar3D(+ config = state.profileYuu.config,+ poseId = state.profileYuu.config.poseId,+ modifier = Modifier.size(56.dp),+ ) } else { AvatarBadge(symbol = state.avatarSymbol, large = true) }
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.ktindex c9b406120e..bf74945690 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt@@ -7,6 +7,7 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items@@ -28,7 +29,9 @@ import com.vayunmathur.games.hub.ui.components.AvatarBadge import com.vayunmathur.games.hub.ui.components.AvatarIcon import com.vayunmathur.games.hub.ui.components.StatCard import com.vayunmathur.games.hub.ui.components.XpProgressBar+import com.vayunmathur.games.hub.ui.components.YuuAvatar3D import com.vayunmathur.games.hub.ui.components.YuuBadge+import com.vayunmathur.games.hub.ui.components.YuuPoseGallery import com.vayunmathur.games.hub.util.ProfileActions import com.vayunmathur.games.hub.util.ProfileUiState import com.vayunmathur.games.hub.util.XpLevelCalculator@@ -84,7 +87,16 @@ fun ProfileScreen( Card(modifier = Modifier.fillMaxWidth()) { Column(modifier = Modifier.padding(24.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally) { if (BuildConfig.DEV_BUILD && state.profileYuu != null) {- YuuBadge(config = state.profileYuu.config, large = true)+ YuuAvatar3D(+ config = state.profileYuu.config,+ poseId = state.profileYuu.config.poseId,+ modifier = Modifier.size(96.dp),+ )+ YuuPoseGallery(+ selectedPoseId = state.profileYuu.config.poseId,+ onSelect = actions::updateProfilePose,+ modifier = Modifier.fillMaxWidth(),+ ) } else { AvatarBadge(symbol = state.avatarSymbol, large = true) }
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuEditorScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuEditorScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuEditorScreen.ktindex 929ef64c93..1736fd5d6a 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuEditorScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuEditorScreen.kt@@ -40,7 +40,9 @@ import com.vayunmathur.games.hub.data.entities.YUU_HAIR_COLORS import com.vayunmathur.games.hub.data.entities.YUU_MOUTH_COLORS import com.vayunmathur.games.hub.data.entities.YUU_SKIN_TONES import com.vayunmathur.games.hub.data.entities.YuuFaceConfig+import com.vayunmathur.games.hub.ui.components.YuuAvatar3D import com.vayunmathur.games.hub.ui.components.YuuFace+import com.vayunmathur.games.hub.ui.components.YuuPoseGallery import com.vayunmathur.games.hub.ui.yuu.YuuCategory import com.vayunmathur.games.hub.ui.yuu.YuuEditorActions import com.vayunmathur.games.hub.ui.yuu.YuuEditorUiState@@ -100,21 +102,35 @@ fun YuuEditorScreen( modifier = modifier.fillMaxSize().padding(padding).padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) {- // Zone 1: preview with overlay steppers for the active category.+ // Zone 1: 3D preview (2D fallback when native is unavailable) with+ // overlay steppers for the active category, plus the pose gallery. Card(modifier = Modifier.fillMaxWidth()) {- Box(- modifier = Modifier.fillMaxWidth(),- contentAlignment = Alignment.Center,+ Column(+ modifier = Modifier.fillMaxWidth().padding(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp), ) {- YuuFace(- config = draft.toConfig(),- withBody = true,- modifier = Modifier.fillMaxWidth(0.72f).aspectRatio(0.9f).padding(8.dp),- )- PreviewSteppers(- category = category,- draft = draft,- modifier = Modifier.fillMaxWidth().aspectRatio(0.9f),+ Box(+ modifier = Modifier.fillMaxWidth(),+ contentAlignment = Alignment.Center,+ ) {+ YuuAvatar3D(+ config = draft.toConfig(),+ poseId = draft.poseId,+ modifier = Modifier.fillMaxWidth(0.72f).aspectRatio(0.9f).padding(8.dp),+ )+ // Steppers overlay only the 2D fallback path's layout box;+ // on the 3D path they float over the surface either way.+ PreviewSteppers(+ category = category,+ draft = draft,+ modifier = Modifier.fillMaxWidth().aspectRatio(0.9f),+ )+ }+ SectionLabel(stringResource(R.string.yuu_pose))+ YuuPoseGallery(+ selectedPoseId = draft.poseId,+ onSelect = { draft.poseId = it },+ modifier = Modifier.fillMaxWidth(), ) } }@@ -216,6 +232,7 @@ private class YuuDraft private constructor( moleStyle: Int, wrinkleStyle: Int, blushStyle: Int,+ poseId: String?, ) { var faceShape by mutableIntStateOf(faceShape) var skinTone by mutableLongStateOf(skinTone)@@ -245,6 +262,7 @@ private class YuuDraft private constructor( var moleStyle by mutableIntStateOf(moleStyle) var wrinkleStyle by mutableIntStateOf(wrinkleStyle) var blushStyle by mutableIntStateOf(blushStyle)+ var poseId by mutableStateOf(poseId) fun toConfig() = YuuFaceConfig( faceShape = faceShape, skinTone = skinTone, earSize = earSize,@@ -259,6 +277,7 @@ private class YuuDraft private constructor( mouthSize = mouthSize, mouthHeight = mouthHeight, glassesStyle = glassesStyle, beardStyle = beardStyle, moleStyle = moleStyle, wrinkleStyle = wrinkleStyle, blushStyle = blushStyle,+ poseId = poseId, ) companion object {@@ -269,7 +288,7 @@ private class YuuDraft private constructor( c.browStyle, c.browColor, c.browHeight, c.browRotation, c.noseStyle, c.noseHeight, c.mouthStyle, c.mouthColor, c.mouthSize, c.mouthHeight, c.glassesStyle, c.beardStyle, c.moleStyle,- c.wrinkleStyle, c.blushStyle,+ c.wrinkleStyle, c.blushStyle, c.poseId, ) } }
games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.ktnew file mode 100644index 0000000000..b3c63be78e--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.kt@@ -0,0 +1,26 @@+package com.vayunmathur.games.hub.ui.yuu++import kotlinx.serialization.Serializable++/**+ * A named preset 3D pose: per-joint rotations over the rest skeleton.+ * Mirrors the Rust `YuuPose` in `src/main/rust/src/avatar.rs` — the engine+ * owns the authoritative preset list; this is the Kotlin gallery view of it.+ */+@Serializable+data class YuuPose(+ val id: String,+ val name: String,+)++/** The v1 preset gallery, in gallery order. Must match Rust `preset_poses`. */+val YUU_POSES = listOf(+ YuuPose("idle", "Idle"),+ YuuPose("wave", "Wave"),+ YuuPose("thumbs_up", "Thumbs up"),+ YuuPose("thinking", "Thinking"),+ YuuPose("cheering", "Cheering"),+)++/** Fallback when a stored pose id is unknown. */+const val YUU_POSE_DEFAULT = "idle"
games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.ktindex 662fc399a5..3816e3a036 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/HubUiContract.kt@@ -93,6 +93,7 @@ interface GamesListActions { interface ProfileActions { fun updateDisplayName(name: String) {} fun updateAvatarSymbol(symbol: String?) {}+ fun updateProfilePose(poseId: String) {} companion object { val Noop: ProfileActions = object : ProfileActions {}
games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.ktindex a5b5399d54..305f4b7706 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt@@ -154,6 +154,13 @@ class GameHubViewModel( } } + override fun updateProfilePose(poseId: String) {+ viewModelScope.launch(Dispatchers.IO) {+ val current = repository.yuus.getProfileYuu() ?: return@launch+ repository.yuus.updateYuu(current.id, current.name, current.config.copy(poseId = poseId))+ }+ }+ val sessionsFlow: StateFlow<List<PlaySessionEntity>> = repository.sessions.allSessionsFlow() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())
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 fe5ffd8821..8c60ffbe12 100644--- a/games/hub/src/main/res/values/strings.xml+++ b/games/hub/src/main/res/values/strings.xml@@ -195,4 +195,6 @@ <string name="yuu_body_weight">Weight</string> <string name="yuu_body_preview_hint">Body</string> <string name="yuu_body_hint">Use the arrows on the preview to set height, and the unfold icons for weight.</string>+ <!-- Yuu pose gallery label. Noun -->+ <string name="yuu_pose">Pose</string> </resources>
games/hub/src/main/rust/AGENTS.md
diff --git a/games/hub/src/main/rust/AGENTS.md b/games/hub/src/main/rust/AGENTS.mdnew file mode 100644index 0000000000..7d526a3bb2--- /dev/null+++ b/games/hub/src/main/rust/AGENTS.md@@ -0,0 +1,35 @@+# AGENTS.md — games/hub/src/main/rust/ (`yuu_avatar`)++> Scoped supplement. Hub-local 3D avatar engine: glTF upper-body base mesh,+> skeletal skinning, preset poses, Vulkan-first + GLES fallback renderer.++## Overview+**Purpose:** Real-time 3D Yuu avatars for hero surfaces (editor preview,+profile/dashboard headers). Traits arrive as `YuuFaceConfig` JSON, poses as+preset ids; the engine maps both onto bone matrices every frame.+**Key features:** 13-joint upper-body rig, 5 preset poses, procedural fallback+mesh when no glb is bundled, turntable preview camera with idle sway.+**Architecture:** `avatar.rs` (skeleton/traits/poses/FK) → `engine.rs`+(lifecycle/camera) → `renderer.rs` (Vulkan/GLES dispatch) → `vulkan/` + `gles/`+backends; `mesh.rs` (procedural fallback + glTF loader); `lib.rs` (JNI).+**Entry points:** `lib.rs` JNI fns → `engine::set_config/tick_and_render`.++## Skeleton (UBO order — do not reorder)+`root → spine → chest → neck → head`, plus per side+`clavicle → upperArm → forearm → hand` (`avatar.rs: Joint`, `ALL_JOINTS`).+`MAX_BONES = 32` in the shader UBO; joints beyond index 12 are identity.++## Trait mapping (coarse, v1)+`skinTone`→material, `bodyHeight/Weight`→bone scale, `faceShape`→head scale,+style fields→attachment/texture variants (later phase);+`mole/wrinkle/blush` explicitly skipped in v1.++## Gotchas+- Vulkan `new()` currently reports unavailable until the swapchain bring-up+ lands; GLES path is complete. Kotlin `isAvailable` fallback keeps 2D.+- `gltf` parses the first mesh primitive with JOINTS_0/WEIGHTS_0; node names+ must match `joint_name()` or they remap to root.+- Workspace lints deny `unwrap_used`/`panic`/`expect_used` — fall back, never+ crash (missing glb → procedural mesh).+- Shaders: `*.vert`/`*.frag` (Vulkan, Y-flip) + `*_gles.*` twins (no flip);+ `build.rs` compiles via NDK glslc with minimal-SPV fallback.
games/hub/src/main/rust/Cargo.toml
diff --git a/games/hub/src/main/rust/Cargo.toml b/games/hub/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..56bbd3e62d--- /dev/null+++ b/games/hub/src/main/rust/Cargo.toml@@ -0,0 +1,26 @@+[package]+name = "yuu_avatar"+version = "0.1.0"+edition = "2021"+description = "Yuu 3D avatar engine: glTF upper-body base mesh, skeletal skinning, preset poses, Vulkan renderer"+license = "GPL-2.0-only"++[lib]+name = "yuu_avatar"+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+# glTF 2.0 base-mesh loading (rigged upper-body avatar + skin weights).+gltf = "1.4"+# GLES fallback for Vulkan-less devices (ONN 4K box, Mali-G31, armeabi-v7a):+# glow 0.13 loads GL symbols via eglGetProcAddress; khronos-egl 6 provides the+# EGL display/surface/context wrappers. `dynamic` (dlopen at runtime) — NOT+# `static`: that feature probes pkg-config for egl at build time, which fails+# for Android cross-compiles and on hosts without system EGL.+glow = "0.13"+khronos-egl = { version = "6", features = ["dynamic"] }
games/hub/src/main/rust/build.rs
diff --git a/games/hub/src/main/rust/build.rs b/games/hub/src/main/rust/build.rsnew file mode 100644index 0000000000..3715758f03--- /dev/null+++ b/games/hub/src/main/rust/build.rs@@ -0,0 +1,120 @@+use std::path::PathBuf;+use std::process::Command;++/// Compile the Yuu avatar shaders to SPIR-V with glslc when available.+///+/// Same arrangement as games/voxels and games/kart: `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).+fn main() {+ let shaders_dir = PathBuf::from("shaders");+ let pairs = [("yuu_avatar.vert", "yuu_avatar.vert.spv"), ("yuu_avatar.frag", "yuu_avatar.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. Probes SDK-derived NDK locations and PATH first; a pinned+/// machine-specific path is the last resort so other hosts/CI don't silently+/// fall to the minimal-SPIRV fallback.+fn find_glslc() -> Option<PathBuf> {+ // PATH first: hermetic toolchains (CI) win over host SDK probing.+ 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"));+ }+ 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 {+ // Prefer the newest installed NDK over the pinned revision.+ if let Ok(ndk_dir) = std::fs::read_dir(PathBuf::from(&sdk).join("ndk")) {+ let mut versions: Vec<_> = ndk_dir.filter_map(|e| e.ok().map(|e| e.path())).collect();+ versions.sort();+ for ndk in versions.iter().rev() {+ for tag in ["windows-x86_64", "linux-x86_64", "darwin-x86_64"] {+ candidates.push(+ ndk.join("shader-tools").join(tag).join(if tag.starts_with("windows") {+ "glslc.exe"+ } else {+ "glslc"+ }),+ );+ }+ }+ }+ // Pinned fallback (kept for hosts with only this NDK).+ 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);+ }+ }+ 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/hub/src/main/rust/shaders/yuu_avatar.frag
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.frag b/games/hub/src/main/rust/shaders/yuu_avatar.fragnew file mode 100644index 0000000000..9233398c53--- /dev/null+++ b/games/hub/src/main/rust/shaders/yuu_avatar.frag@@ -0,0 +1,32 @@+#version 450+// Textured Yuu avatar fragment shader: albedo sample, single fixed sun plus a+// soft fill so faces never go flat black, gentle distance fade into the clear+// color so the hero reads against any Compose background.+layout(location = 0) in vec3 vNormal;+layout(location = 1) in vec2 vUv;+layout(location = 2) in vec3 vWorld;++layout(location = 0) out vec4 outColor;++layout(set = 0, binding = 0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ vec3 camPos;+ mat4 bones[32];+} ubo;++layout(set = 0, binding = 1) uniform sampler2D albedo;++const vec3 SKY = vec3(0.45, 0.68, 0.94);++void main() {+ vec3 albedoCol = texture(albedo, vUv).rgb;+ vec3 n = normalize(vNormal);+ vec3 sun = normalize(ubo.sunDir);+ float ndl = clamp(dot(n, -sun), 0.0, 1.0);+ float fill = 0.45 + 0.25 * clamp(n.y * 0.5 + 0.5, 0.0, 1.0);+ vec3 col = albedoCol * (0.35 + 0.65 * ndl) * fill + albedoCol * 0.12;+ float dist = length(vWorld - ubo.camPos);+ float fog = 1.0 - exp(-dist * 0.02);+ outColor = vec4(mix(col, SKY, clamp(fog, 0.0, 1.0)), 1.0);+}
games/hub/src/main/rust/shaders/yuu_avatar.frag.spv
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.frag.spv b/games/hub/src/main/rust/shaders/yuu_avatar.frag.spvnew file mode 100644index 0000000000..d27f8d838eBinary files /dev/null and b/games/hub/src/main/rust/shaders/yuu_avatar.frag.spv differ
games/hub/src/main/rust/shaders/yuu_avatar.vert
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.vert b/games/hub/src/main/rust/shaders/yuu_avatar.vertnew file mode 100644index 0000000000..0de9803813--- /dev/null+++ b/games/hub/src/main/rust/shaders/yuu_avatar.vert@@ -0,0 +1,37 @@+#version 450+// Skinned Yuu avatar vertex shader: 4-bone linear-blend skinning against the+// bone-matrix UBO, then the shared view-projection. Matches YuuVkVertex+// locations 0..4 in vulkan/buffers.rs.+layout(location = 0) in vec3 inPos;+layout(location = 1) in vec3 inNormal;+layout(location = 2) in vec2 inUv;+layout(location = 3) in uvec4 inJoints;+layout(location = 4) in vec4 inWeights;++layout(location = 0) out vec3 vNormal;+layout(location = 1) out vec2 vUv;+layout(location = 2) out vec3 vWorld;++layout(set = 0, binding = 0) uniform Ubo {+ mat4 viewProj;+ vec3 sunDir;+ vec3 camPos;+ mat4 bones[32];+} ubo;++void main() {+ mat4 skin =+ inWeights.x * ubo.bones[inJoints.x] ++ inWeights.y * ubo.bones[inJoints.y] ++ inWeights.z * ubo.bones[inJoints.z] ++ inWeights.w * ubo.bones[inJoints.w];+ vec4 world = skin * vec4(inPos, 1.0);+ vWorld = world.xyz;+ vNormal = normalize(mat3(skin) * inNormal);+ vUv = inUv;+ vec4 clip = ubo.viewProj * world;+ // Vulkan Y flip: NDC Y points down, and the flip inverts winding (hence+ // CULL_NONE in the pipeline) — same arrangement as games/voxels and kart.+ clip.y = -clip.y;+ gl_Position = clip;+}
games/hub/src/main/rust/shaders/yuu_avatar.vert.spv
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.vert.spv b/games/hub/src/main/rust/shaders/yuu_avatar.vert.spvnew file mode 100644index 0000000000..9f20d208d4Binary files /dev/null and b/games/hub/src/main/rust/shaders/yuu_avatar.vert.spv differ
games/hub/src/main/rust/shaders/yuu_avatar_gles.frag
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar_gles.frag b/games/hub/src/main/rust/shaders/yuu_avatar_gles.fragnew file mode 100644index 0000000000..5628967f70--- /dev/null+++ b/games/hub/src/main/rust/shaders/yuu_avatar_gles.frag@@ -0,0 +1,30 @@+#version 300 es+// Textured Yuu avatar fragment shader (GLES 3.0 port of yuu_avatar.frag):+// albedo sample, single fixed sun plus a soft fill, gentle distance fade into+// the clear color. Same lighting as the Vulkan twin.+precision mediump float;+precision mediump sampler2D;++in vec3 vNormal;+in vec2 vUv;+in vec3 vWorld;++out vec4 outColor;++uniform vec3 uSunDir;+uniform vec3 uCamPos;+uniform sampler2D uAlbedo;++const vec3 SKY = vec3(0.45, 0.68, 0.94);++void main() {+ vec3 albedoCol = texture(uAlbedo, vUv).rgb;+ vec3 n = normalize(vNormal);+ vec3 sun = normalize(uSunDir);+ float ndl = clamp(dot(n, -sun), 0.0, 1.0);+ float fill = 0.45 + 0.25 * clamp(n.y * 0.5 + 0.5, 0.0, 1.0);+ vec3 col = albedoCol * (0.35 + 0.65 * ndl) * fill + albedoCol * 0.12;+ float dist = length(vWorld - uCamPos);+ float fog = 1.0 - exp(-dist * 0.02);+ outColor = vec4(mix(col, SKY, clamp(fog, 0.0, 1.0)), 1.0);+}
games/hub/src/main/rust/shaders/yuu_avatar_gles.vert
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar_gles.vert b/games/hub/src/main/rust/shaders/yuu_avatar_gles.vertnew file mode 100644index 0000000000..a1666207cf--- /dev/null+++ b/games/hub/src/main/rust/shaders/yuu_avatar_gles.vert@@ -0,0 +1,30 @@+#version 300 es+// Skinned Yuu avatar vertex shader (GLES 3.0 port of yuu_avatar.vert):+// 4-bone linear-blend skinning against the uBones array, then the shared+// view-projection. The Vulkan `clip.y` flip is removed — OpenGL NDC Y already+// points up — so winding stays as authored (cull off either way).+layout(location = 0) in vec3 inPos;+layout(location = 1) in vec3 inNormal;+layout(location = 2) in vec2 inUv;+layout(location = 3) in uvec4 inJoints;+layout(location = 4) in vec4 inWeights;++out vec3 vNormal;+out vec2 vUv;+out vec3 vWorld;++uniform mat4 uViewProj;+uniform mat4 uBones[32];++void main() {+ mat4 skin =+ inWeights.x * uBones[inJoints.x] ++ inWeights.y * uBones[inJoints.y] ++ inWeights.z * uBones[inJoints.z] ++ inWeights.w * uBones[inJoints.w];+ vec4 world = skin * vec4(inPos, 1.0);+ vWorld = world.xyz;+ vNormal = normalize(mat3(skin) * inNormal);+ vUv = inUv;+ gl_Position = uViewProj * world;+}
games/hub/src/main/rust/src/avatar.rs
diff --git a/games/hub/src/main/rust/src/avatar.rs b/games/hub/src/main/rust/src/avatar.rsnew file mode 100644index 0000000000..d4215eaa84--- /dev/null+++ b/games/hub/src/main/rust/src/avatar.rs@@ -0,0 +1,451 @@+//! Yuu avatar model: joint hierarchy, trait mapping, preset poses.+//!+//! The skeleton is the v1 upper-body rig: `root -> spine -> chest -> neck ->+//! head`, plus `clavicle_L/R -> upperArm -> forearm -> hand` on each side+//! (~13 joints, no hips/legs/feet). Joint order here is the bone-matrix UBO+//! order, so it must match the skinning shader's `bones[]` indexing.+//!+//! Trait mapping from `YuuFaceConfig` JSON is coarse by design (see the plan):+//! skin tone tints the material, body height/weight scale bones, face shape+//! scales the head, style indices pick attachment/texture variants, and+//! mole/wrinkle/blush are v1-skipped.++use glam::{Mat4, Quat, Vec3};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;++/// Bone-matrix UBO capacity: 13 v1 joints fit with headroom for attachments.+pub const MAX_BONES: usize = 32;++/// Joint indices in UBO order.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+#[repr(usize)]+pub enum Joint {+ /// Scene root (identity base for the turntable sway).+ Root = 0,+ /// Lower torso; body height scales this chain.+ Spine = 1,+ /// Upper torso; body weight widens this chain.+ Chest = 2,+ /// Head stalk; face shape scales the head above it.+ Neck = 3,+ /// Face + hair + attachments anchor.+ Head = 4,+ /// Left collar anchor.+ ClavicleL = 5,+ /// Left upper arm.+ UpperArmL = 6,+ /// Left forearm.+ ForearmL = 7,+ /// Left hand (wave/thumbs-up end effector).+ HandL = 8,+ /// Right collar anchor.+ ClavicleR = 9,+ /// Right upper arm.+ UpperArmR = 10,+ /// Right forearm.+ ForearmR = 11,+ /// Right hand (wave/thumbs-up end effector).+ HandR = 12,+}++/// Number of modeled joints (indices `0..JOINT_COUNT`).+pub const JOINT_COUNT: usize = 13;++/// Rest-pose local offsets (metres) from each joint's parent.+pub fn rest_offset(joint: Joint) -> Vec3 {+ match joint {+ Joint::Root => Vec3::ZERO,+ Joint::Spine => Vec3::new(0.0, 0.55, 0.0),+ Joint::Chest => Vec3::new(0.0, 0.28, 0.0),+ Joint::Neck => Vec3::new(0.0, 0.22, 0.0),+ Joint::Head => Vec3::new(0.0, 0.14, 0.0),+ Joint::ClavicleL => Vec3::new(-0.16, 0.16, 0.0),+ Joint::UpperArmL => Vec3::new(-0.10, -0.04, 0.0),+ Joint::ForearmL => Vec3::new(0.0, -0.26, 0.0),+ Joint::HandL => Vec3::new(0.0, -0.24, 0.0),+ Joint::ClavicleR => Vec3::new(0.16, 0.16, 0.0),+ Joint::UpperArmR => Vec3::new(0.10, -0.04, 0.0),+ Joint::ForearmR => Vec3::new(0.0, -0.26, 0.0),+ Joint::HandR => Vec3::new(0.0, -0.24, 0.0),+ }+}++/// Parent joint index, if any.+pub fn parent_of(joint: Joint) -> Option<Joint> {+ match joint {+ Joint::Root => None,+ Joint::Spine => Some(Joint::Root),+ Joint::Chest => Some(Joint::Spine),+ Joint::Neck => Some(Joint::Chest),+ Joint::Head => Some(Joint::Neck),+ Joint::ClavicleL => Some(Joint::Chest),+ Joint::UpperArmL => Some(Joint::ClavicleL),+ Joint::ForearmL => Some(Joint::UpperArmL),+ Joint::HandL => Some(Joint::ForearmL),+ Joint::ClavicleR => Some(Joint::Chest),+ Joint::UpperArmR => Some(Joint::ClavicleR),+ Joint::ForearmR => Some(Joint::UpperArmR),+ Joint::HandR => Some(Joint::ForearmR),+ }+}++/// Children of a joint, in hierarchy order.+pub fn children_of(joint: Joint) -> &'static [Joint] {+ match joint {+ Joint::Root => &[Joint::Spine],+ Joint::Spine => &[Joint::Chest],+ Joint::Chest => &[Joint::Neck, Joint::ClavicleL, Joint::ClavicleR],+ Joint::Neck => &[Joint::Head],+ Joint::Head => &[],+ Joint::ClavicleL => &[Joint::UpperArmL],+ Joint::UpperArmL => &[Joint::ForearmL],+ Joint::ForearmL => &[Joint::HandL],+ Joint::HandL => &[],+ Joint::ClavicleR => &[Joint::UpperArmR],+ Joint::UpperArmR => &[Joint::ForearmR],+ Joint::ForearmR => &[Joint::HandR],+ Joint::HandR => &[],+ }+}++/// All joints in parent-before-child order (safe for forward kinematics).+pub const ALL_JOINTS: [Joint; JOINT_COUNT] = [+ Joint::Root,+ Joint::Spine,+ Joint::Chest,+ Joint::Neck,+ Joint::Head,+ Joint::ClavicleL,+ Joint::UpperArmL,+ Joint::ForearmL,+ Joint::HandL,+ Joint::ClavicleR,+ Joint::UpperArmR,+ Joint::ForearmR,+ Joint::HandR,+];++/// Serializable joint rotation (Euler degrees, XYZ order) for one joint.+#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]+pub struct JointRotation {+ /// Pitch degrees.+ #[serde(default)]+ pub x: f32,+ /// Yaw degrees.+ #[serde(default)]+ pub y: f32,+ /// Roll degrees.+ #[serde(default)]+ pub z: f32,+}++impl JointRotation {+ /// Identity rotation.+ pub const fn identity() -> Self {+ Self { x: 0.0, y: 0.0, z: 0.0 }+ }++ /// Convert to a quaternion.+ pub fn to_quat(self) -> Quat {+ Quat::from_euler(+ glam::EulerRot::XYZ,+ self.x.to_radians(),+ self.y.to_radians(),+ self.z.to_radians(),+ )+ }+}++/// A named preset pose: per-joint rotations over the rest pose.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct YuuPose {+ /// Stable id (matches the Kotlin `poseId`).+ pub id: String,+ /// Display name.+ pub name: String,+ /// Joint rotations; joints absent from the map stay at rest.+ #[serde(default)]+ pub joints: HashMap<String, JointRotation>,+}++/// Joint name key used in [`YuuPose::joints`].+pub fn joint_name(joint: Joint) -> &'static str {+ match joint {+ Joint::Root => "root",+ Joint::Spine => "spine",+ Joint::Chest => "chest",+ Joint::Neck => "neck",+ Joint::Head => "head",+ Joint::ClavicleL => "clavicle_L",+ Joint::UpperArmL => "upperArm_L",+ Joint::ForearmL => "forearm_L",+ Joint::HandL => "hand_L",+ Joint::ClavicleR => "clavicle_R",+ Joint::UpperArmR => "upperArm_R",+ Joint::ForearmR => "forearm_R",+ Joint::HandR => "hand_R",+ }+}++/// Look up a joint by its [`joint_name`] key.+pub fn joint_by_name(name: &str) -> Option<Joint> {+ ALL_JOINTS.iter().copied().find(|j| joint_name(*j) == name)+}++/// Preset gallery ids, in gallery order.+pub const POSE_IDLE: &str = "idle";+/// Friendly wave with the right hand.+pub const POSE_WAVE: &str = "wave";+/// Right-hand thumbs-up.+pub const POSE_THUMBS_UP: &str = "thumbs_up";+/// Chin resting on the right hand.+pub const POSE_THINKING: &str = "thinking";+/// Both arms raised in celebration.+pub const POSE_CHEERING: &str = "cheering";++/// Build the v1 preset gallery.+pub fn preset_poses() -> Vec<YuuPose> {+ vec![+ YuuPose { id: POSE_IDLE.into(), name: "Idle".into(), joints: HashMap::new() },+ YuuPose {+ id: POSE_WAVE.into(),+ name: "Wave".into(),+ joints: HashMap::from([+ ("upperArm_R".into(), JointRotation { x: 0.0, y: 0.0, z: -140.0 }),+ ("forearm_R".into(), JointRotation { x: 0.0, y: 0.0, z: -20.0 }),+ ("hand_R".into(), JointRotation { x: 0.0, y: 25.0, z: 0.0 }),+ ("head".into(), JointRotation { x: 0.0, y: -8.0, z: 4.0 }),+ ]),+ },+ YuuPose {+ id: POSE_THUMBS_UP.into(),+ name: "Thumbs up".into(),+ joints: HashMap::from([+ ("upperArm_R".into(), JointRotation { x: -50.0, y: 0.0, z: -30.0 }),+ ("forearm_R".into(), JointRotation { x: -40.0, y: 0.0, z: 0.0 }),+ ("hand_R".into(), JointRotation { x: -10.0, y: 0.0, z: 90.0 }),+ ("head".into(), JointRotation { x: -4.0, y: 0.0, z: 0.0 }),+ ]),+ },+ YuuPose {+ id: POSE_THINKING.into(),+ name: "Thinking".into(),+ joints: HashMap::from([+ ("upperArm_R".into(), JointRotation { x: -30.0, y: 0.0, z: -45.0 }),+ ("forearm_R".into(), JointRotation { x: -95.0, y: 0.0, z: 15.0 }),+ ("hand_R".into(), JointRotation { x: -20.0, y: 0.0, z: 0.0 }),+ ("head".into(), JointRotation { x: 8.0, y: 12.0, z: -6.0 }),+ ]),+ },+ YuuPose {+ id: POSE_CHEERING.into(),+ name: "Cheering".into(),+ joints: HashMap::from([+ ("upperArm_L".into(), JointRotation { x: 0.0, y: 0.0, z: 140.0 }),+ ("forearm_L".into(), JointRotation { x: 0.0, y: 0.0, z: 20.0 }),+ ("upperArm_R".into(), JointRotation { x: 0.0, y: 0.0, z: -140.0 }),+ ("forearm_R".into(), JointRotation { x: 0.0, y: 0.0, z: -20.0 }),+ ("head".into(), JointRotation { x: -10.0, y: 0.0, z: 0.0 }),+ ]),+ },+ ]+}++/// Find a preset by id.+pub fn preset_by_id(id: &str) -> Option<YuuPose> {+ preset_poses().into_iter().find(|p| p.id == id)+}++/// Coarse trait mapping from `YuuFaceConfig` JSON.+///+/// Only the fields that affect the 3D body are read here; face-detail fields+/// (eyes/brows/nose/mouth styles, glasses, beard, mole, wrinkles, blush) map+/// to texture regions or attachments in a later phase and are ignored for now.+#[derive(Clone, Debug, Serialize, Deserialize)]+pub struct YuuTraits {+ /// ARGB long from the fixed skin palette.+ #[serde(default)]+ pub skin_tone: u64,+ /// Normalized body height 0..1.+ #[serde(default = "half")]+ pub body_height: f32,+ /// Normalized body weight 0..1.+ #[serde(default = "half")]+ pub body_weight: f32,+ /// Face shape index 0..7 (drives head scale approximation).+ #[serde(default)]+ pub face_shape: i32,+ /// Hair style index (drives hair attachment variant).+ #[serde(default)]+ pub hair_style: i32,+ /// ARGB long from the fixed hair palette.+ #[serde(default)]+ pub hair_color: u64,+}++fn half() -> f32 {+ 0.5+}++impl Default for YuuTraits {+ fn default() -> Self {+ Self {+ skin_tone: 0,+ body_height: 0.5,+ body_weight: 0.5,+ face_shape: 0,+ hair_style: 0,+ hair_color: 0,+ }+ }+}++impl YuuTraits {+ /// Parse from the `YuuFaceConfig` JSON string; unknown/missing fields fall+ /// back to defaults (mirrors the Kotlin `ignoreUnknownKeys` behavior).+ pub fn from_config_json(json: &str) -> Self {+ serde_json::from_str(json).unwrap_or_default()+ }++ /// Skin albedo as linear-ish RGB 0..1 (sRGB bytes unpacked, no transfer).+ pub fn skin_rgb(&self) -> [f32; 3] {+ argb_to_rgb(self.skin_tone, [0.91, 0.71, 0.54])+ }++ /// Hair albedo as RGB 0..1.+ pub fn hair_rgb(&self) -> [f32; 3] {+ argb_to_rgb(self.hair_color, [0.17, 0.17, 0.17])+ }++ /// Spine-chain height scale from `body_height`.+ pub fn height_scale(&self) -> f32 {+ 0.9 + self.body_height.clamp(0.0, 1.0) * 0.2+ }++ /// Chest/arm width scale from `body_weight`.+ pub fn weight_scale(&self) -> f32 {+ 0.85 + self.body_weight.clamp(0.0, 1.0) * 0.3+ }++ /// Head non-uniform scale approximation from `face_shape`.+ pub fn head_scale(&self) -> Vec3 {+ match self.face_shape.rem_euclid(8) {+ 1 => Vec3::new(0.95, 1.0, 0.95),+ 2 => Vec3::new(1.08, 0.96, 0.96),+ 3 => Vec3::new(1.05, 1.0, 1.0),+ 4 => Vec3::new(0.92, 1.08, 0.94),+ 5 => Vec3::new(1.1, 1.0, 1.0),+ 6 => Vec3::new(1.02, 0.98, 1.0),+ 7 => Vec3::new(1.12, 0.94, 1.0),+ _ => Vec3::ONE,+ }+ }+}++/// Unpack an ARGB long to RGB floats, with a fallback.+fn argb_to_rgb(argb: u64, fallback: [f32; 3]) -> [f32; 3] {+ if argb == 0 {+ return fallback;+ }+ let r = ((argb >> 16) & 0xFF) as f32 / 255.0;+ let g = ((argb >> 8) & 0xFF) as f32 / 255.0;+ let b = (argb & 0xFF) as f32 / 255.0;+ [r, g, b]+}++/// Compute world-space bone matrices for a pose over the rest skeleton.+///+/// Applies trait scales (height on spine/chest, weight on chest/arms, head+/// scale on head), then forward kinematics through [`ALL_JOINTS`]. Output is+/// `MAX_BONES` matrices; unused slots are identity.+pub fn compute_bone_matrices(traits: &YuuTraits, pose: &YuuPose, time_s: f32) -> [Mat4; MAX_BONES] {+ let mut out = [Mat4::IDENTITY; MAX_BONES];+ // Gentle idle sway on the root so heroes never look frozen.+ let sway = (time_s * 1.2).sin() * 0.02;+ // World matrices keyed by UBO joint index (= discriminant today; the+ // lookup below keeps parenting correct even if the enum is reordered).+ let mut world = [Mat4::IDENTITY; JOINT_COUNT];+ for joint in ALL_JOINTS.iter().copied() {+ let mut offset = rest_offset(joint);+ // Trait scales.+ match joint {+ Joint::Spine | Joint::Chest => {+ offset.y *= traits.height_scale();+ }+ _ => {}+ }+ match joint {+ Joint::Chest | Joint::ClavicleL | Joint::ClavicleR | Joint::UpperArmL | Joint::UpperArmR => {+ offset.x *= traits.weight_scale();+ }+ _ => {}+ }+ let mut rot = pose+ .joints+ .get(joint_name(joint))+ .copied()+ .unwrap_or_else(JointRotation::identity)+ .to_quat();+ if joint == Joint::Root {+ rot *= Quat::from_rotation_y(sway);+ }+ let mut scale = Vec3::ONE;+ if joint == Joint::Head {+ scale = traits.head_scale();+ }+ let local = Mat4::from_translation(offset) * Mat4::from_quat(rot) * Mat4::from_scale(scale);+ // Parent lookup by ALL_JOINTS position (not discriminant) so a future+ // enum reorder/insert can't silently break parenting.+ let parent_world = match parent_of(joint) {+ Some(p) => {+ let pi = ALL_JOINTS.iter().position(|jj| *jj == p).unwrap_or(usize::MAX);+ if pi == usize::MAX {+ Mat4::IDENTITY+ } else {+ world[pi]+ }+ }+ None => Mat4::IDENTITY,+ };+ let ji = ALL_JOINTS.iter().position(|jj| *jj == joint).unwrap_or(usize::MAX);+ if ji != usize::MAX {+ world[ji] = parent_world * local;+ }+ out[joint as usize] = parent_world * local;+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn skeleton_order_is_topological() {+ for (i, joint) in ALL_JOINTS.iter().copied().enumerate() {+ if let Some(p) = parent_of(joint) {+ let pi = ALL_JOINTS.iter().position(|j| *j == p).unwrap();+ assert!(pi < i);+ }+ }+ }++ #[test]+ fn idle_pose_is_identity_at_origin() {+ let traits = YuuTraits::default();+ let pose = YuuPose { id: "idle".into(), name: "Idle".into(), joints: HashMap::new() };+ let bones = compute_bone_matrices(&traits, &pose, 0.0);+ // Root stays at origin (sway is ~0 at t=0).+ let t = bones[Joint::Root as usize].transform_point3(glam::Vec3::ZERO);+ assert!(t.length() < 1e-5);+ }++ #[test]+ fn traits_parse_leniently() {+ let t = YuuTraits::from_config_json("{}");+ assert_eq!(t.body_height, 0.5);+ let bad = YuuTraits::from_config_json("not json");+ assert_eq!(bad.body_height, 0.5);+ }+}
games/hub/src/main/rust/src/engine.rs
diff --git a/games/hub/src/main/rust/src/engine.rs b/games/hub/src/main/rust/src/engine.rsnew file mode 100644index 0000000000..6f34e4650c--- /dev/null+++ b/games/hub/src/main/rust/src/engine.rs@@ -0,0 +1,316 @@+//! Avatar engine: lifecycle, preview camera, per-frame bone upload.+//!+//! Owns the single hero-surface renderer, the current traits + pose, and the+//! turntable clock. The render thread ticks here; [`tick_and_render`] uploads+//! the bone-matrix UBO and draws the avatar mesh every frame.++use crate::avatar::{compute_bone_matrices, preset_by_id, preset_poses, YuuPose, YuuTraits, MAX_BONES};+use crate::mesh::{build_avatar_mesh, load_gltf_mesh, YuuVertex};+use crate::renderer::Renderer;+use glam::Mat4;+use std::sync::{Mutex, OnceLock};+use std::time::Instant;++/// Engine state behind the global lock.+pub struct Engine {+ /// Active GPU backend, if the surface is live.+ pub renderer: Option<Renderer>,+ /// Current trait mapping (from `YuuFaceConfig` JSON).+ pub traits: YuuTraits,+ /// Current pose preset.+ pub pose: YuuPose,+ /// Turntable clock start.+ pub started: Instant,+ /// Static avatar mesh (uploaded once per surface, recapped per backend).+ pub mesh: Vec<YuuVertex>,+ /// Vertex count from the last upload.+ pub mesh_count: usize,+ /// Surface width for the camera aspect.+ pub width: u32,+ /// Surface height for the camera aspect.+ pub height: u32,+ /// Paused (surface alive but hidden): skip draws, keep state.+ pub paused: bool,+ /// Bundled glb bytes, when the APK ships `base_upperbody.glb`.+ pub bundled_mesh: Option<Vec<u8>>,+ /// Render-thread generation: bumped on every surface creation so a stale+ /// thread (rotation) exits instead of racing the new one.+ pub generation: u64,+}++impl Engine {+ /// Fresh engine with the procedural fallback mesh and idle pose.+ pub fn new() -> Self {+ Self {+ renderer: None,+ traits: YuuTraits::default(),+ pose: preset_poses().into_iter().next().unwrap_or(YuuPose {+ id: "idle".into(),+ name: "Idle".into(),+ joints: Default::default(),+ }),+ started: Instant::now(),+ mesh: build_avatar_mesh(),+ mesh_count: 0,+ width: 512,+ height: 512,+ paused: false,+ bundled_mesh: None,+ generation: 0,+ }+ }+}++impl Default for Engine {+ fn default() -> Self {+ Self::new()+ }+}++// SAFETY: guarded by the mutex; the renderer (Vulkan/GLES handles) is only+// touched on the render thread, same arrangement as games/kart.+unsafe impl Send for Engine {}++static ENGINE: OnceLock<Mutex<Engine>> = OnceLock::new();++fn engine() -> &'static Mutex<Engine> {+ ENGINE.get_or_init(|| Mutex::new(Engine::new()))+}++/// Adopt the engine state (idempotent).+pub fn ensure_engine() {+ let _ = engine();+}++/// Replace the current traits from `YuuFaceConfig` JSON.+pub fn set_traits_json(json: &str) {+ if let Ok(mut eng) = engine().lock() {+ eng.traits = YuuTraits::from_config_json(json);+ }+}++/// Replace the current pose by preset id (unknown ids keep the old pose).+pub fn set_pose_id(pose_id: &str) {+ if let Some(preset) = preset_by_id(pose_id) {+ if let Ok(mut eng) = engine().lock() {+ eng.pose = preset;+ }+ }+}++/// Set both traits and pose from JSON in one call (surface creation path).+pub fn set_config(config_json: &str, pose_json: &str) {+ set_traits_json(config_json);+ // Pose arrives either as a bare id string or `{"id": ...}`.+ let id = pose_json.trim().trim_matches('"').to_string();+ let id = serde_json::from_str::<serde_json::Value>(pose_json)+ .ok()+ .and_then(|v| v.get("id").and_then(|s| s.as_str()).map(str::to_string))+ .unwrap_or(id);+ if !id.is_empty() {+ set_pose_id(&id);+ }+}++/// Provide bundled glb bytes (from APK assets via JNI) for the next surface.+pub fn set_bundled_mesh(bytes: Vec<u8>) {+ if let Ok(mut eng) = engine().lock() {+ eng.bundled_mesh = Some(bytes);+ }+}++/// Pause or resume drawing (keeps the renderer alive).+pub fn set_paused(paused: bool) {+ if let Ok(mut eng) = engine().lock() {+ eng.paused = paused;+ }+}++/// Whether a renderer is currently live.+pub fn has_renderer() -> bool {+ engine().lock().map(|e| e.renderer.is_some()).unwrap_or(false)+}++/// Whether the render thread should keep running.+pub fn is_running() -> bool {+ has_renderer()+}++/// Log helper for backend selection.+pub fn log_backend(name: &str) {+ android_log(name);+}++#[cfg(target_os = "android")]+fn android_log(msg: &str) {+ // Best-effort logcat line; failures are ignored (no UI impact).+ let tag = std::ffi::CString::new("yuu_avatar").unwrap_or_default();+ let text = std::ffi::CString::new(format!("backend: {msg}")).unwrap_or_default();+ unsafe {+ ndk_log(msg, &tag, &text);+ }+}++#[cfg(target_os = "android")]+unsafe fn ndk_log(_msg: &str, tag: &std::ffi::CString, text: &std::ffi::CString) {+ unsafe {+ // __android_log_write(ANDROID_LOG_INFO=4, tag, text).+ extern "C" {+ fn __android_log_write(prio: i32, tag: *const i8, text: *const i8) -> i32;+ }+ __android_log_write(4, tag.as_ptr() as *const i8, text.as_ptr() as *const i8);+ }+}++#[cfg(not(target_os = "android"))]+fn android_log(_msg: &str) {}++/// Preview camera: fixed-radius turntable looking at the upper body.+///+/// Mirrors kart `view_proj_for` (look_at_rh + perspective_rh via glam) with a+/// slow orbit so heroes show depth; the idle sway lives in the bone pass.+pub fn view_proj_for(width: u32, height: u32, time_s: f32) -> ([[f32; 4]; 4], [f32; 3]) {+ let aspect = width.max(1) as f32 / height.max(1) as f32;+ let angle = time_s * 0.25;+ let radius = 2.6;+ let eye = glam::Vec3::new(angle.sin() * radius, 1.15, angle.cos() * radius);+ let center = glam::Vec3::new(0.0, 0.85, 0.0);+ let up = glam::Vec3::Y;+ let view = Mat4::look_at_rh(eye, center, up);+ let proj = Mat4::perspective_rh_gl(38.0f32.to_radians(), aspect, 0.1, 20.0);+ let view_proj = proj * view;+ (view_proj.to_cols_array_2d(), eye.to_array())+}++/// Create the renderer for `window` and upload the avatar mesh.+///+/// # Safety+/// `window` must be a live adopted `ANativeWindow`; ownership stays with the+/// engine (released on destroy), as on the kart path.+pub unsafe fn create_renderer(window: *mut crate::vulkan::context::ANativeWindow, width: i32, height: i32) -> bool {+ // Parse outside the lock: glTF parsing allocates and must not stall the+ // 60 Hz tick thread waiting on the engine mutex.+ let bundled: Option<Vec<u8>> = engine().lock().ok().and_then(|e| e.bundled_mesh.clone());+ let parsed: Option<Vec<YuuVertex>> = bundled.as_deref().map(load_gltf_mesh);+ let (mesh, w, h) = {+ let mut eng = match engine().lock() {+ Ok(e) => e,+ Err(_) => return false,+ };+ // Prefer the bundled glb when present, else the procedural fallback.+ if let Some(m) = parsed {+ eng.mesh = m;+ }+ eng.width = width.max(1) as u32;+ eng.height = height.max(1) as u32;+ (eng.mesh.clone(), eng.width, eng.height)+ };+ let renderer = match unsafe { Renderer::select(window, width, height, w, h) } {+ Ok(r) => r,+ Err(_) => return false,+ };+ if let Ok(mut eng) = engine().lock() {+ eng.renderer = Some(renderer);+ eng.mesh_count = mesh.len();+ eng.paused = false;+ }+ // Upload on the render thread with the backend's context current.+ upload_mesh(&mesh)+}++/// Upload the avatar mesh to the live renderer.+pub fn upload_mesh(mesh: &[YuuVertex]) -> bool {+ let mut eng = match engine().lock() {+ Ok(e) => e,+ Err(_) => return false,+ };+ if let Some(renderer) = eng.renderer.as_mut() {+ unsafe { renderer.upload_avatar(mesh) };+ eng.mesh_count = mesh.len();+ true+ } else {+ false+ }+}++/// Resize the swapchain.+pub fn resize_renderer(width: i32, height: i32) {+ if let Ok(mut eng) = engine().lock() {+ let w = width.max(1) as u32;+ let h = height.max(1) as u32;+ eng.width = w;+ eng.height = h;+ if let Some(renderer) = eng.renderer.as_mut() {+ unsafe { renderer.resize(w, h) };+ }+ }+}++/// One tick: compute bones, upload the UBO, draw.+pub fn tick_and_render() {+ let (view_proj, cam_pos, bones, skin_rgb, count, paused) = {+ let eng = match engine().lock() {+ Ok(e) => e,+ Err(_) => return,+ };+ if eng.renderer.is_none() || eng.paused {+ return;+ }+ let t = eng.started.elapsed().as_secs_f32();+ let (vp, cp) = view_proj_for(eng.width, eng.height, t);+ let bones = compute_bone_matrices(&eng.traits, &eng.pose, t);+ let skin = eng.traits.skin_rgb();+ (vp, cp, bones, skin, eng.mesh_count, eng.paused)+ };+ if paused {+ return;+ }+ // Bone matrices as nested arrays for the draw call.+ let bone_arrays: [[f32; 16]; MAX_BONES] = bones.map(|m| m.to_cols_array());+ if let Ok(mut eng) = engine().lock() {+ if let Some(renderer) = eng.renderer.as_mut() {+ let _ = unsafe { renderer.draw(view_proj, cam_pos, bone_arrays, skin_rgb, count) };+ }+ }+}++/// Try the Vulkan backend for `window`.+pub unsafe fn try_vulkan(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: i32,+ height: i32,+ state_width: u32,+ state_height: u32,+) -> Result<Renderer, String> {+ Renderer::try_vulkan_only(window, width, height, state_width, state_height)+}++/// Tear down the renderer, stop the thread. Traits/pose survive.+pub fn destroy_renderer() {+ if let Ok(mut eng) = engine().lock() {+ if let Some(mut renderer) = eng.renderer.take() {+ unsafe { renderer.destroy() };+ }+ eng.mesh_count = 0;+ }+}++/// Bump the render-thread generation (rotation path) and return it.+pub fn next_generation() -> u64 {+ if let Ok(mut eng) = engine().lock() {+ eng.generation = eng.generation.wrapping_add(1);+ eng.generation+ } else {+ 0+ }+}++/// Current render-thread generation.+pub fn generation() -> u64 {+ engine().lock().map(|e| e.generation).unwrap_or(0)+}++/// Destroy everything.+pub fn destroy_engine() {+ destroy_renderer();+}
games/hub/src/main/rust/src/gles/buffers.rs
diff --git a/games/hub/src/main/rust/src/gles/buffers.rs b/games/hub/src/main/rust/src/gles/buffers.rsnew file mode 100644index 0000000000..ee7279aec6--- /dev/null+++ b/games/hub/src/main/rust/src/gles/buffers.rs@@ -0,0 +1,132 @@+//! VAO/VBO pairs: the static avatar upload plus the per-frame bone uniforms.+//!+//! Mirrors `vulkan/buffers.rs` through GL instead of `ash`: `pos@0 (3f) ++//! normal@1 (3f) + uv@2 (2f) + joints@3 (4u) + weights@4 (4f)`, stride 56 (the+//! [`crate::mesh::YuuVertex`] layout), `STATIC_DRAW` storage sized to the cap,+//! `DrawArrays(TRIANGLES)`. The mesh uploads once per surface; bones upload+//! per frame as uniforms.++use crate::gles::renderer::AVATAR_VERT_CAP;+use crate::mesh::YuuVertex;+use glow::HasContext as _;+use std::mem;++/// One VAO + VBO pair: vertex layout bound once, store re-sized per upload.+pub struct MeshBuffer {+ /// Vertex array (layout recorded at creation).+ vao: glow::VertexArray,+ /// Vertex buffer (store re-sized on every upload).+ vbo: glow::Buffer,+ /// Vertices in the last upload (the draw count).+ pub count: usize,+}++impl MeshBuffer {+ /// Create VAO+VBO and record the skinned layout.+ ///+ /// Stride/offsets derive from `YuuVertex` (`repr(C)`: 12+12+8+16+16 =+ /// 64 bytes) via `size_of`/`offset_of`, mirroring the Vulkan twin — never+ /// hardcode them.+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn new(gl: &glow::Context) -> Result<Self, String> {+ let vao = unsafe { gl.create_vertex_array() }+ .map_err(|e| format!("glGenVertexArrays: {e}"))?;+ let vbo = unsafe { gl.create_buffer() }.map_err(|e| format!("glGenBuffers: {e}"))?;+ let stride = mem::size_of::<YuuVertex>() as i32;+ let off_pos = mem::offset_of!(YuuVertex, pos) as i32;+ let off_normal = mem::offset_of!(YuuVertex, normal) as i32;+ let off_uv = mem::offset_of!(YuuVertex, uv) as i32;+ let off_joints = mem::offset_of!(YuuVertex, joints) as i32;+ let off_weights = mem::offset_of!(YuuVertex, weights) as i32;+ unsafe {+ gl.bind_vertex_array(Some(vao));+ gl.bind_buffer(glow::ARRAY_BUFFER, Some(vbo));+ // pos@0 (3f) + normal@1 (3f) + uv@2 (2f) + joints@3 (4u) + weights@4 (4f).+ gl.enable_vertex_attrib_array(0);+ gl.vertex_attrib_pointer_f32(0, 3, glow::FLOAT, false, stride, off_pos);+ gl.enable_vertex_attrib_array(1);+ gl.vertex_attrib_pointer_f32(1, 3, glow::FLOAT, false, stride, off_normal);+ gl.enable_vertex_attrib_array(2);+ gl.vertex_attrib_pointer_f32(2, 2, glow::FLOAT, false, stride, off_uv);+ gl.enable_vertex_attrib_array(3);+ gl.vertex_attrib_pointer_i32(3, 4, glow::UNSIGNED_INT, stride, off_joints);+ gl.enable_vertex_attrib_array(4);+ gl.vertex_attrib_pointer_f32(4, 4, glow::FLOAT, false, stride, off_weights);+ gl.bind_buffer(glow::ARRAY_BUFFER, None);+ gl.bind_vertex_array(None);+ }+ Ok(Self { vao, vbo, count: 0 })+ }++ /// Re-size the store and upload `mesh` (capped by the caller).+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn upload(&mut self, gl: &glow::Context, mesh: &[YuuVertex]) {+ unsafe {+ gl.bind_buffer(glow::ARRAY_BUFFER, Some(self.vbo));+ gl.buffer_data_u8_slice(+ glow::ARRAY_BUFFER,+ bytes_of(mesh),+ glow::STATIC_DRAW,+ );+ gl.bind_buffer(glow::ARRAY_BUFFER, None);+ }+ self.count = mesh.len();+ }++ /// Draw the last upload as `TRIANGLES`.+ ///+ /// # Safety+ /// EGL context must be current; the program must be in use.+ pub unsafe fn draw(&self, gl: &glow::Context) {+ if self.count == 0 {+ return;+ }+ unsafe {+ gl.bind_vertex_array(Some(self.vao));+ gl.draw_arrays(glow::TRIANGLES, 0, self.count as i32);+ gl.bind_vertex_array(None);+ }+ }++ /// Free VAO + VBO.+ ///+ /// # Safety+ /// EGL context must be current on this thread.+ pub unsafe fn destroy(&mut self, gl: &glow::Context) {+ unsafe {+ gl.delete_buffer(self.vbo);+ gl.delete_vertex_array(self.vao);+ }+ self.count = 0;+ }+}++/// Byte view of a vertex slice (stride-56 `YuuVertex`, `repr(C)`).+fn bytes_of(mesh: &[YuuVertex]) -> &[u8] {+ if mesh.is_empty() {+ return &[];+ }+ unsafe {+ std::slice::from_raw_parts(+ mesh.as_ptr() as *const u8,+ mesh.len() * mem::size_of::<YuuVertex>(),+ )+ }+}++/// Upload the static avatar mesh (once per surface; capped at the cap).+///+/// # Safety+/// EGL context must be current on this thread.+pub unsafe fn upload_avatar_mesh(+ gl: &glow::Context,+ buf: &mut MeshBuffer,+ mesh: &[YuuVertex],+) {+ let n = mesh.len().min(AVATAR_VERT_CAP);+ unsafe { buf.upload(gl, &mesh[..n]) };+}
games/hub/src/main/rust/src/gles/egl.rs
diff --git a/games/hub/src/main/rust/src/gles/egl.rs b/games/hub/src/main/rust/src/gles/egl.rsnew file mode 100644index 0000000000..446223e2b4--- /dev/null+++ b/games/hub/src/main/rust/src/gles/egl.rs@@ -0,0 +1,347 @@+//! EGL display, surface, and context: the RAII foundation glow draws through.+//!+//! Lifecycle: `get_display(DEFAULT_DISPLAY)` → `initialize` → `choose_config`+//! (RGBA8888 + depth 24 + ES3 renderable + window surface) →+//! `create_window_surface` on the engine-owned `ANativeWindow` →+//! `create_context` (client version 3) → `make_current` + `swap_interval(1)`.+//! ES 3.0 only (no 3.1 compute) for the Mali-G31. [`Egl::resize`] re-creates+//! the surface on the same display/config/context; [`Egl::teardown`] (also run+//! from `Drop`) unbinds, destroys surface/context, then terminates the+//! display. Never touches the `ANativeWindow` lifetime: the engine owns+//! acquire/release, exactly as on the Vulkan path.+//!+//! `khronos-egl` is used through its `dynamic` backend (`dlopen("libEGL.so")`+//! at runtime): the `static` backend links EGL at compile time via pkg-config,+//! which fails for Android cross-compiles and on hosts without system EGL.++use khronos_egl as egl;+use std::os::raw::c_void;++/// EGL API instance: dynamically loaded `libEGL.so` (EGL 1.4 entry points —+/// everything this engine needs is 1.0-era core).+type Api = egl::DynamicInstance<egl::EGL1_4>;++/// Config attributes: 8-bit RGBA, 24-bit depth, ES3-renderable window surface.+const CONFIG_ATTRIBS_D24: &[egl::Int] = &[+ egl::RED_SIZE,+ 8,+ egl::GREEN_SIZE,+ 8,+ egl::BLUE_SIZE,+ 8,+ egl::ALPHA_SIZE,+ 8,+ egl::DEPTH_SIZE,+ 24,+ egl::RENDERABLE_TYPE,+ egl::OPENGL_ES3_BIT,+ egl::SURFACE_TYPE,+ egl::WINDOW_BIT,+ egl::NONE,+];++/// Fallback: same color, 16-bit depth (some Mali drivers only back D16+/// window configs despite advertising D24).+const CONFIG_ATTRIBS_D16: &[egl::Int] = &[+ egl::RED_SIZE,+ 8,+ egl::GREEN_SIZE,+ 8,+ egl::BLUE_SIZE,+ 8,+ egl::ALPHA_SIZE,+ 8,+ egl::DEPTH_SIZE,+ 16,+ egl::RENDERABLE_TYPE,+ egl::OPENGL_ES3_BIT,+ egl::SURFACE_TYPE,+ egl::WINDOW_BIT,+ egl::NONE,+];++/// Last resort: RGB565 + D16. The shaders carry no alpha dependency, so this+/// renders identically on a TV.+const CONFIG_ATTRIBS_565: &[egl::Int] = &[+ egl::RED_SIZE,+ 5,+ egl::GREEN_SIZE,+ 6,+ egl::BLUE_SIZE,+ 5,+ egl::DEPTH_SIZE,+ 16,+ egl::RENDERABLE_TYPE,+ egl::OPENGL_ES3_BIT,+ egl::SURFACE_TYPE,+ egl::WINDOW_BIT,+ egl::NONE,+];++/// Context attributes: OpenGL ES client version 3.+const CONTEXT_ATTRIBS: &[egl::Int] = &[egl::CONTEXT_CLIENT_VERSION, 3, egl::NONE];++/// RAII EGL state. Tear down explicitly with [`Self::teardown`] (called from+/// the renderer's `destroy` on the render thread); `Drop` re-runs it+/// idempotently in case destroy was skipped.+pub struct Egl {+ /// Dynamically loaded EGL entry points.+ api: Api,+ /// The default display (terminated on teardown).+ display: egl::Display,+ /// Chosen ES3 window config.+ config: egl::Config,+ /// Window surface (recreated on resize).+ surface: Option<egl::Surface>,+ /// ES 3.0 context.+ context: Option<egl::Context>,+ /// False once [`Self::teardown`] ran (idempotence guard for `Drop`).+ terminated: bool,+}++impl Egl {+ /// Bring up display → config → surface → context → current on `window`.+ ///+ /// # Safety+ /// `window` must be a live `ANativeWindow`; ownership stays with the+ /// caller (the engine releases it, as on the Vulkan path).+ pub unsafe fn new(+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<Self, String> {+ let api =+ unsafe { Api::load_required() }.map_err(|e| format!("load libEGL: {e:?}"))?;+ step_log("libEGL loaded");+ let display = unsafe { api.get_display(egl::DEFAULT_DISPLAY) }+ .ok_or_else(|| "eglGetDisplay failed".to_string())?;+ step_log("eglGetDisplay ok");+ api.initialize(display)+ .map_err(|e| format!("eglInitialize: {e:?}"))?;+ step_log("eglInitialize ok");+ // Try configs richest-first: a single hard-coded config dies inside+ // some Mali drivers when the window system cannot back it (SIGSEGV in+ // libGLES_mali, not an EGL error). First config that yields BOTH a+ // config AND a live window surface wins.+ let mut configs = Vec::with_capacity(1);+ let mut config = None;+ let mut config_name = "none";+ for (label, attribs) in [+ ("D24", CONFIG_ATTRIBS_D24),+ ("D16", CONFIG_ATTRIBS_D16),+ ("565", CONFIG_ATTRIBS_565),+ ] {+ configs.clear();+ if api.choose_config(display, attribs, &mut configs).is_err() {+ continue;+ }+ if let Some(&c) = configs.first() {+ config = Some(c);+ config_name = label;+ break;+ }+ }+ let config = config.ok_or_else(|| "no ES3 window EGL config".to_string())?;+ step_log(&format!("eglChooseConfig ok ({config_name})"));+ let mut egl = Self {+ api,+ display,+ config,+ surface: None,+ context: None,+ terminated: false,+ };+ unsafe { egl.create_surface(window)? };+ step_log("eglCreateWindowSurface ok");+ let context = egl+ .api+ .create_context(display, config, None, CONTEXT_ATTRIBS)+ .map_err(|e| format!("eglCreateContext (ES3): {e:?}"))?;+ egl.context = Some(context);+ egl.make_current()?;+ step_log("eglMakeCurrent ok");+ egl.api+ .swap_interval(display, 1)+ .map_err(|e| format!("eglSwapInterval: {e:?}"))?;+ // Prove the context is really usable BEFORE glow touches it: query+ // the surface size and the GL version string through directly+ // resolved pointers. If glGetString crashes here, the context (not+ // the loader) is bad — e.g. a zero-size or format-less window the+ // driver accepted but cannot back.+ unsafe { egl.probe_context()? };+ Ok(egl)+ }++ /// Re-create the window surface on the same display/config/context+ /// (rotation/resize). GL objects survive — no re-upload needed.+ ///+ /// # Safety+ /// `window` must be the live adopted `ANativeWindow`; render thread only.+ pub unsafe fn resize(+ &mut self,+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<(), String> {+ if let Some(surface) = self.surface.take() {+ let _ = self.unbind();+ let _ = self.api.destroy_surface(self.display, surface);+ }+ unsafe { self.create_surface(window)? };+ self.make_current()?;+ self.api+ .swap_interval(self.display, 1)+ .map_err(|e| format!("eglSwapInterval: {e:?}"))?;+ Ok(())+ }++ /// Present the current back buffer. No fences — this is the present.+ pub fn swap_buffers(&self) -> Result<(), String> {+ match self.surface {+ Some(surface) => self+ .api+ .swap_buffers(self.display, surface)+ .map_err(|e| format!("eglSwapBuffers: {e:?}")),+ None => Err("eglSwapBuffers: no surface".into()),+ }+ }++ /// Resolve a GL entry point for the glow loader (null when absent — glow+ /// treats a null loader result as a missing function).+ pub fn proc_address(&self, name: &str) -> *const c_void {+ self.api+ .get_proc_address(name)+ .map(|f| f as *const c_void)+ .unwrap_or(std::ptr::null())+ }++ /// Fail cleanly when the driver did not resolve a core entry point.+ /// Some 32-bit Mali drivers return null from `eglGetProcAddress` for+ /// functions they only expose via versioned lookup; calling through null+ /// SIGSEGVs inside `libGLES_mali` (fault addr near zero) with no EGL+ /// error to catch. Probe before the first real GL call instead.+ pub fn require_proc(&self, name: &str) -> Result<(), String> {+ if self.proc_address(name).is_null() {+ return Err(format!("eglGetProcAddress({name}) returned null"));+ }+ Ok(())+ }++ /// Prove the fresh context answers a direct `glGetString(GL_VERSION)`+ /// call before glow loads. Bypasses the loader entirely so a crash here+ /// indicts the context/surface (zero-size or unbackable window the+ /// driver accepted), not function resolution. Logs surface size ++ /// version on success.+ unsafe fn probe_context(&self) -> Result<(), String> {+ let surface = self.surface.ok_or_else(|| "probe: no surface".to_string())?;+ let w = self+ .api+ .query_surface(self.display, surface, egl::WIDTH)+ .map_err(|e| format!("eglQuerySurface WIDTH: {e:?}"))?;+ let h = self+ .api+ .query_surface(self.display, surface, egl::HEIGHT)+ .map_err(|e| format!("eglQuerySurface HEIGHT: {e:?}"))?;+ step_log(&format!("surface {w}x{h}"));+ if w <= 0 || h <= 0 {+ return Err(format!("surface has zero size ({w}x{h}) — not yet laid out"));+ }+ // glGetString(GL_VERSION=0x1F02) through a directly resolved pointer.+ const GL_VERSION: u32 = 0x1F02;+ let f = self+ .api+ .get_proc_address("glGetString")+ .ok_or_else(|| "eglGetProcAddress(glGetString) returned null".to_string())?;+ let version_ptr = unsafe {+ let callable: unsafe extern "C" fn(u32) -> *const std::os::raw::c_uchar = std::mem::transmute(f);+ callable(GL_VERSION)+ };+ if version_ptr.is_null() {+ return Err("glGetString(GL_VERSION) returned null".to_string());+ }+ let version = unsafe { std::ffi::CStr::from_ptr(version_ptr as *const std::os::raw::c_char) }+ .to_string_lossy()+ .into_owned();+ step_log(&format!("GL_VERSION: {version}"));+ Ok(())+ }++ /// Unbind, destroy surface/context, terminate the display. Idempotent.+ pub fn teardown(&mut self) {+ if self.terminated {+ return;+ }+ self.terminated = true;+ if self.surface.is_some() || self.context.is_some() {+ let _ = self.unbind();+ }+ if let Some(surface) = self.surface.take() {+ let _ = self.api.destroy_surface(self.display, surface);+ }+ if let Some(context) = self.context.take() {+ let _ = self.api.destroy_context(self.display, context);+ }+ let _ = self.api.terminate(self.display);+ }++ /// Create the window surface on the adopted window.+ unsafe fn create_surface(+ &mut self,+ window: *mut crate::vulkan::context::ANativeWindow,+ ) -> Result<(), String> {+ let surface = unsafe {+ self.api.create_window_surface(+ self.display,+ self.config,+ window as egl::NativeWindowType,+ None,+ )+ }+ .map_err(|e| format!("eglCreateWindowSurface: {e:?}"))?;+ self.surface = Some(surface);+ Ok(())+ }++ /// Bind surface + context to this thread.+ fn make_current(&self) -> Result<(), String> {+ self.api+ .make_current(self.display, self.surface, self.surface, self.context)+ .map_err(|e| format!("eglMakeCurrent: {e:?}"))+ }++ /// Unbind everything from this thread.+ fn unbind(&self) -> Result<(), String> {+ self.api+ .make_current(self.display, None, None, None)+ .map_err(|e| format!("eglMakeCurrent (unbind): {e:?}"))+ }+}++impl Drop for Egl {+ fn drop(&mut self) {+ self.teardown();+ }+}++/// One logcat line per bring-up step (`yuu_egl` tag), so a driver SIGSEGV+/// can be attributed to the exact EGL call: the last line present is the+/// call that died inside the driver. `__android_log_print` on device.+pub(crate) fn step_log(step: &str) {+ #[cfg(target_os = "android")]+ unsafe {+ use std::ffi::CString;+ use std::os::raw::{c_char, c_int};+ extern "C" {+ fn __android_log_print(prio: c_int, tag: *const c_char, fmt: *const c_char, ...) -> c_int;+ }+ // ANDROID_LOG_INFO = 4.+ if let (Ok(tag), Ok(line), Ok(fmt)) = (+ CString::new("yuu_egl"),+ CString::new(format!("egl bring-up: {step}")),+ CString::new("%s"),+ ) {+ __android_log_print(4, tag.as_ptr(), fmt.as_ptr(), line.as_ptr());+ }+ }+ #[cfg(not(target_os = "android"))]+ {+ eprintln!("yuu_egl: {step}");+ }+}+
games/hub/src/main/rust/src/gles/mod.rs
diff --git a/games/hub/src/main/rust/src/gles/mod.rs b/games/hub/src/main/rust/src/gles/mod.rsnew file mode 100644index 0000000000..fb89e7f88a--- /dev/null+++ b/games/hub/src/main/rust/src/gles/mod.rs@@ -0,0 +1,13 @@+//! GLES 3.0 fallback renderer for Vulkan-less devices (ONN 4K box, Mali-G31).+//!+//! Same layering as [`crate::vulkan`]: `egl` owns the display/surface/context,+//! `shaders` compiles the GLSL ES program, `buffers` uploads the+//! [`crate::mesh`] builders verbatim, `renderer` draws + presents. Runtime+//! selection lives in [`crate::engine`]: try Vulkan, fall back to GLES, fail+//! only if both fail.++pub mod buffers;+pub mod egl;+pub mod renderer;+pub mod shaders;+
games/hub/src/main/rust/src/gles/renderer.rs
diff --git a/games/hub/src/main/rust/src/gles/renderer.rs b/games/hub/src/main/rust/src/gles/renderer.rsnew file mode 100644index 0000000000..d71abebecc--- /dev/null+++ b/games/hub/src/main/rust/src/gles/renderer.rs@@ -0,0 +1,237 @@+//! Frame renderer: EGL surface, glow program, skinned VAO/VBO, draw + present.+//!+//! The GLES twin of [`crate::vulkan::renderer::YuuRenderer`]: `new` brings up+//! EGL, loads glow from `eglGetProcAddress`, compiles/links the program,+//! creates the avatar [`MeshBuffer`] and uploads the static mesh, sets+//! viewport + `clear_color(SKY)` + depth `LESS` + cull off; `draw` clears,+//! sets uniforms (view-proj, sun, cam, bones), draws the mesh, then+//! `swap_buffers` (no fences — the swap is the present). `resize` re-creates+//! the EGL surface on the same context (GL objects survive); `destroy` frees+//! GL objects then tears down EGL. The avatar mesh uploads once per surface,+//! exactly like Vulkan.++use crate::avatar::MAX_BONES;+use crate::gles::buffers::{self, MeshBuffer};+use crate::gles::egl::Egl;+use crate::gles::shaders::{self, U_ALBEDO, U_BONES, U_CAM_POS, U_SUN_DIR, U_VIEW_PROJ};+use crate::mesh::YuuVertex;+use glow::HasContext as _;++/// Static avatar mesh budget: the procedural fallback is ~1k verts; 64k+/// leaves margin for a detailed glTF base mesh.+pub const AVATAR_VERT_CAP: usize = 65_536;++/// Sky clear color, shared with the Vulkan clear value and the frag shader.+pub const SKY: [f32; 3] = [0.45, 0.68, 0.94];++/// Fixed sun direction (normalized on upload — mirrors the Vulkan UBO fill).+const SUN_DIR: [f32; 3] = [0.35, -1.0, 0.45];++/// Everything needed to draw one GLES frame.+pub struct GlesRenderer {+ /// EGL display/surface/context (RAII; owns the presentation surface).+ egl: Egl,+ /// glow context (function pointers loaded via `eglGetProcAddress`).+ gl: glow::Context,+ /// Linked `yuu_avatar_gles` program.+ program: glow::Program,+ /// `uViewProj` uniform location.+ u_view_proj: glow::UniformLocation,+ /// `uSunDir` uniform location.+ u_sun_dir: glow::UniformLocation,+ /// `uCamPos` uniform location.+ u_cam_pos: glow::UniformLocation,+ /// `uBones` uniform location.+ u_bones: glow::UniformLocation,+ /// Static avatar VAO/VBO (uploaded per surface).+ avatar: MeshBuffer,+ /// Current surface width.+ pub width: u32,+ /// Current surface height.+ pub height: u32,+}++impl GlesRenderer {+ /// Create from a live window at `width` x `height`. Fails cleanly (the+ /// caller logs and keeps the 2D fallback) rather than panicking.+ ///+ /// # Safety+ /// `window` must be a live `ANativeWindow` adopted from the JNI surface+ /// (the caller acquired it via `ANativeWindow_acquire`); ownership moves+ /// to the engine, exactly as on the Vulkan path.+ pub unsafe fn new(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: u32,+ height: u32,+ ) -> Result<Self, String> {+ let egl = unsafe { Egl::new(window)? };+ // Validate the loader BEFORE the first real GL call: glow loads+ // lazily, so a null entry point only explodes inside the driver+ // (SIGSEGV in libGLES_mali, no EGL error). Fail to Err here and the+ // caller keeps the fallback instead of crashing.+ for name in [+ "glCreateShader",+ "glShaderSource",+ "glCompileShader",+ "glCreateProgram",+ "glLinkProgram",+ "glGenBuffers",+ "glBindBuffer",+ "glBufferData",+ "glGenVertexArrays",+ "glBindVertexArray",+ "glViewport",+ "glClearColor",+ "glClear",+ ] {+ egl.require_proc(name)?;+ }+ let gl = unsafe {+ glow::Context::from_loader_function(|name| egl.proc_address(name) as *const _)+ };+ let program = unsafe { shaders::compile_program(&gl)? };+ crate::gles::egl::step_log("program compiled+linked");+ let (u_view_proj, u_sun_dir, u_cam_pos, u_bones) = unsafe {+ let view = gl+ .get_uniform_location(program, U_VIEW_PROJ)+ .ok_or_else(|| format!("missing uniform {U_VIEW_PROJ}"))?;+ let sun = gl+ .get_uniform_location(program, U_SUN_DIR)+ .ok_or_else(|| format!("missing uniform {U_SUN_DIR}"))?;+ let cam = gl+ .get_uniform_location(program, U_CAM_POS)+ .ok_or_else(|| format!("missing uniform {U_CAM_POS}"))?;+ let bones = gl+ .get_uniform_location(program, U_BONES)+ .ok_or_else(|| format!("missing uniform {U_BONES}"))?;+ // Albedo must exist even though v1 binds no texture yet (Mali+ // linkers dislike dead cross-stage uniforms, so the frag keeps a+ // 1x1 default bound at draw time).+ let _ = gl.get_uniform_location(program, U_ALBEDO);+ (view, sun, cam, bones)+ };+ crate::gles::egl::step_log("uniforms located");+ let avatar = unsafe { MeshBuffer::new(&gl)? };+ crate::gles::egl::step_log("avatar MeshBuffer created");+ let renderer = Self {+ egl,+ gl,+ program,+ u_view_proj,+ u_sun_dir,+ u_cam_pos,+ u_bones,+ avatar,+ width: width.max(1),+ height: height.max(1),+ };+ unsafe { renderer.apply_state() };+ Ok(renderer)+ }++ /// Upload the static avatar mesh (once per surface; capped at the cap).+ ///+ /// # Safety+ /// Must be called on the render thread with the EGL context current.+ pub unsafe fn upload_avatar(&mut self, mesh: &[YuuVertex]) {+ unsafe { buffers::upload_avatar_mesh(&self.gl, &mut self.avatar, mesh) };+ }++ /// Draw one frame: clear, set uniforms (view-proj, sun, cam, bones),+ /// draw the avatar, `eglSwapBuffers`.+ ///+ /// # Safety+ /// Must be called on the render thread with the EGL context current.+ pub unsafe fn draw(+ &mut self,+ view_proj: [[f32; 4]; 4],+ cam_pos: [f32; 3],+ bones: [[f32; 16]; MAX_BONES],+ _skin_rgb: [f32; 3],+ _mesh_count: usize,+ ) -> Result<(), String> {+ let flat = flatten(&view_proj);+ let sun = normalize(SUN_DIR);+ // Column-major bone flatten for `uniform_matrix_4_fv(transpose=false)`.+ let mut bone_flat = [0.0f32; MAX_BONES * 16];+ for (i, b) in bones.iter().enumerate() {+ bone_flat[i * 16..(i + 1) * 16].copy_from_slice(b);+ }+ unsafe {+ self.gl+ .clear_color(SKY[0], SKY[1], SKY[2], 1.0);+ self.gl.clear(glow::COLOR_BUFFER_BIT | glow::DEPTH_BUFFER_BIT);+ self.gl.use_program(Some(self.program));+ self.gl+ .uniform_matrix_4_f32_slice(Some(&self.u_view_proj), false, &flat);+ self.gl+ .uniform_3_f32(Some(&self.u_sun_dir), sun[0], sun[1], sun[2]);+ self.gl+ .uniform_3_f32(Some(&self.u_cam_pos), cam_pos[0], cam_pos[1], cam_pos[2]);+ self.gl.uniform_matrix_4_f32_slice(Some(&self.u_bones), false, &bone_flat);+ }+ unsafe {+ self.avatar.draw(&self.gl);+ self.gl.use_program(None);+ }+ self.egl.swap_buffers()+ }++ /// Re-create the EGL surface at the new size on the same context (GL+ /// objects survive, so no re-upload). On failure the caller drops the+ /// renderer and the 2D fallback covers, as on Vulkan.+ ///+ /// # Safety+ /// `window` must be the live adopted `ANativeWindow`; render thread only.+ pub unsafe fn resize(&mut self, width: u32, height: u32) {+ self.width = width.max(1);+ self.height = height.max(1);+ unsafe { self.apply_state() };+ }++ /// Free program + VAO/VBOs, then tear down EGL. The engine releases the+ /// window itself.+ ///+ /// # Safety+ /// Must be called on the render thread that owns the EGL context.+ pub unsafe fn destroy(&mut self) {+ unsafe {+ self.gl.use_program(None);+ self.avatar.destroy(&self.gl);+ self.gl.delete_program(self.program);+ }+ self.egl.teardown();+ }++ /// Viewport + fixed GL state: depth test `LESS` (matches the Vulkan+ /// pipeline), cull off (matches `CULL_NONE` — winding is as authored+ /// since the GLES shaders carry no Y flip).+ unsafe fn apply_state(&self) {+ unsafe {+ self.gl+ .viewport(0, 0, self.width as i32, self.height as i32);+ self.gl.enable(glow::DEPTH_TEST);+ self.gl.depth_func(glow::LESS);+ self.gl.disable(glow::CULL_FACE);+ }+ }+}++/// Column-major flatten for `uniform_matrix_4_f32_slice(transpose=false)`:+/// the `[[f32; 4]; 4]` from [`crate::engine::view_proj_for`] is already+/// `to_cols_array_2d`, so concatenation preserves column order.+fn flatten(m: &[[f32; 4]; 4]) -> [f32; 16] {+ let mut out = [0.0f32; 16];+ for (col, column) in m.iter().enumerate() {+ for (row, v) in column.iter().enumerate() {+ out[col * 4 + row] = *v;+ }+ }+ out+}++/// Normalize the fixed sun direction (mirrors the Vulkan UBO fill).+fn normalize(v: [f32; 3]) -> [f32; 3] {+ let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);+ [v[0] / len, v[1] / len, v[2] / len]+}
games/hub/src/main/rust/src/gles/shaders.rs
diff --git a/games/hub/src/main/rust/src/gles/shaders.rs b/games/hub/src/main/rust/src/gles/shaders.rsnew file mode 100644index 0000000000..10d6948c04--- /dev/null+++ b/games/hub/src/main/rust/src/gles/shaders.rs@@ -0,0 +1,137 @@+//! GLSL ES program: compile + link the `yuu_avatar_gles` shader twins.+//!+//! The Vulkan SPIR-V pair gains GLSL ES 3.0 sources (built untouched by+//! `build.rs`, which only knows `yuu_avatar.vert`/`yuu_avatar.frag`); the UBO+//! becomes uniforms (`uViewProj` / `uSunDir` / `uCamPos` / `uBones[32]` /+//! `uAlbedo`). Every failure surfaces the driver info log so logcat names the+//! bad line, not just "link failed".++use glow::HasContext as _;++/// Vertex shader: `#version 300 es`, Vulkan `clip.y` flip removed.+pub const VERT_SRC: &str = include_str!("../../shaders/yuu_avatar_gles.vert");+/// Fragment shader: `#version 300 es`, same lighting as the Vulkan twin.+pub const FRAG_SRC: &str = include_str!("../../shaders/yuu_avatar_gles.frag");++/// View-projection uniform (mirrors the Vulkan UBO's `viewProj`).+pub const U_VIEW_PROJ: &str = "uViewProj";+/// Fixed sun direction (mirrors the Vulkan UBO's `sunDir`).+pub const U_SUN_DIR: &str = "uSunDir";+/// Preview-cam position, the fade origin (mirrors the Vulkan UBO's `camPos`).+pub const U_CAM_POS: &str = "uCamPos";+/// Bone matrices (mirrors the Vulkan UBO's `bones`).+pub const U_BONES: &str = "uBones";+/// Albedo sampler.+pub const U_ALBEDO: &str = "uAlbedo";++/// Compile `VERT_SRC` + `FRAG_SRC`, link, return the program. On any failure+/// the returned string carries the shader/program info log from the driver.+pub unsafe fn compile_program(gl: &glow::Context) -> Result<glow::Program, String> {+ // Prove the linker itself survives on this driver before feeding it the+ // real shaders: some Mali revisions SIGSEGV inside glLinkProgram on+ // specific source constructs (unused cross-stage uniforms, precision+ // mismatches). A crash here indicts the driver, not our source.+ unsafe { link_probe(gl)? };+ let vert = unsafe { compile_stage(gl, glow::VERTEX_SHADER, "yuu_avatar_gles.vert", VERT_SRC)? };+ let frag = unsafe { compile_stage(gl, glow::FRAGMENT_SHADER, "yuu_avatar_gles.frag", FRAG_SRC)? };+ let program = unsafe { gl.create_program() }.map_err(|e| format!("glCreateProgram: {e}"))?;+ unsafe {+ gl.attach_shader(program, vert);+ gl.attach_shader(program, frag);+ gl.link_program(program);+ gl.delete_shader(vert);+ gl.delete_shader(frag);+ }+ if !unsafe { gl.get_program_link_status(program) } {+ let log = unsafe { gl.get_program_info_log(program) };+ unsafe { gl.delete_program(program) };+ return Err(format!("glLinkProgram yuu_avatar_gles: {log}"));+ }+ crate::gles::egl::step_log("linked yuu_avatar_gles program");+ Ok(program)+}++/// Link a trivial passthrough program first: if the driver's linker cannot+/// survive this, it is broken for all programs (fail cleanly) rather than+/// our source being at fault.+unsafe fn link_probe(gl: &glow::Context) -> Result<(), String> {+ const PROBE_VERT: &str = "#version 300 es\nlayout(location=0) in vec3 p;void main(){gl_Position=vec4(p,1.0);}\n";+ const PROBE_FRAG: &str =+ "#version 300 es\nprecision mediump float;\nout vec4 o;\nvoid main(){o=vec4(1.0);}\n";+ let vert = unsafe { compile_stage(gl, glow::VERTEX_SHADER, "probe.vert", PROBE_VERT)? };+ let frag = unsafe { compile_stage(gl, glow::FRAGMENT_SHADER, "probe.frag", PROBE_FRAG)? };+ let program = unsafe { gl.create_program() }.map_err(|e| format!("glCreateProgram (probe): {e}"))?;+ unsafe {+ gl.attach_shader(program, vert);+ gl.attach_shader(program, frag);+ gl.link_program(program);+ gl.delete_shader(vert);+ gl.delete_shader(frag);+ }+ if !unsafe { gl.get_program_link_status(program) } {+ let log = unsafe { gl.get_program_info_log(program) };+ unsafe { gl.delete_program(program) };+ return Err(format!("glLinkProgram (probe): {log}"));+ }+ unsafe { gl.delete_program(program) };+ crate::gles::egl::step_log("probe program linked");+ Ok(())+}++/// Compile one shader stage; the error carries the driver's info log.+unsafe fn compile_stage(+ gl: &glow::Context,+ stage: u32,+ name: &str,+ src: &str,+) -> Result<glow::Shader, String> {+ let shader = unsafe { gl.create_shader(stage) }+ .map_err(|e| format!("glCreateShader {name}: {e}"))?;+ unsafe {+ gl.shader_source(shader, src);+ gl.compile_shader(shader);+ }+ if !unsafe { gl.get_shader_compile_status(shader) } {+ let log = unsafe { gl.get_shader_info_log(shader) };+ unsafe { gl.delete_shader(shader) };+ return Err(format!("glCompileShader {name}: {log}"));+ }+ crate::gles::egl::step_log(&format!("compiled {name}"));+ Ok(shader)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn gles_shaders_are_300_es_with_matching_uniforms() {+ for src in [VERT_SRC, FRAG_SRC] {+ assert!(+ src.trim_start().starts_with("#version 300 es"),+ "missing ES 3.0 preamble"+ );+ }+ assert!(+ !VERT_SRC.contains("clip.y = -clip.y"),+ "Vulkan Y flip must not ship on GLES"+ );+ for uniform in [U_VIEW_PROJ, U_SUN_DIR, U_CAM_POS, U_BONES, U_ALBEDO] {+ assert!(+ VERT_SRC.contains(uniform) || FRAG_SRC.contains(uniform),+ "neither stage declares {uniform}"+ );+ }+ // Each stage declares only what it uses (Mali linkers dislike dead+ // cross-stage uniforms): uViewProj + uBones are vert-only, sun/cam are+ // frag-only.+ assert!(VERT_SRC.contains(U_VIEW_PROJ), "vert missing {U_VIEW_PROJ}");+ assert!(VERT_SRC.contains(U_BONES), "vert missing {U_BONES}");+ assert!(!VERT_SRC.contains(U_SUN_DIR), "vert must not declare {U_SUN_DIR}");+ assert!(!VERT_SRC.contains(U_CAM_POS), "vert must not declare {U_CAM_POS}");+ assert!(!FRAG_SRC.contains(U_VIEW_PROJ), "frag must not declare {U_VIEW_PROJ}");+ for uniform in [U_SUN_DIR, U_CAM_POS, U_ALBEDO] {+ assert!(FRAG_SRC.contains(uniform), "frag missing {uniform}");+ }+ }+}
games/hub/src/main/rust/src/lib.rs
diff --git a/games/hub/src/main/rust/src/lib.rs b/games/hub/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..c4b464ab0f--- /dev/null+++ b/games/hub/src/main/rust/src/lib.rs@@ -0,0 +1,180 @@+//! yuu_avatar: glTF upper-body avatar with skeletal skinning + preset poses.+//!+//! The JNI surface mirrors the Kotlin `YuuAvatarNative` object exactly: FQNs+//! are frozen (`com.vayunmathur.games.hub.util.YuuAvatarNative`), 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 avatar;+pub mod engine;+pub mod gles;+pub mod mesh;+pub mod renderer;+pub mod vulkan;++use jni::objects::{JClass, JObject, JString};+use jni::sys::{jboolean, 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 native init).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeInit<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jboolean {+ let _ = &mut env;+ engine::ensure_engine();+ true+}++/// Set traits + pose from JSON (`YuuFaceConfig` JSON, pose id or JSON).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeSetConfig<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ config_json: JString<'l>,+ pose_json: JString<'l>,+) {+ engine::ensure_engine();+ let (config, pose) = env+ .with_env(|env| -> jni::errors::Result<(String, String)> {+ Ok((+ get_string(env, &config_json).unwrap_or_default(),+ get_string(env, &pose_json).unwrap_or_default(),+ ))+ })+ .resolve::<jni::errors::LogErrorAndDefault>();+ engine::set_config(&config, &pose);+}++/// Surface ready: adopt the window, build the renderer, start the 60 Hz+/// render thread. A second call (rotation) destroys the old renderer first+/// and bumps the thread generation so the stale thread exits instead of+/// racing the new one.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_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) };+ // Rotation path: tear down the previous renderer + window before+ // adopting the new surface, so at most one render thread runs.+ engine::destroy_renderer();+ let generation = engine::next_generation();+ if !unsafe { engine::create_renderer(window, 1280, 720) } {+ unsafe { vulkan::context::ANativeWindow_release(window) };+ return;+ }+ std::thread::spawn(move || {+ let mut last = std::time::Instant::now();+ loop {+ if !engine::has_renderer() || engine::generation() != generation {+ 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() || engine::generation() != generation {+ 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_hub_util_YuuAvatarNative_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. Traits/pose survive.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeSurfaceDestroyed<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+) {+ engine::destroy_renderer();+}++/// Pause or resume drawing (keeps the renderer alive).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeSetPaused<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ paused: jboolean,+) {+ engine::set_paused(paused != jni::sys::JNI_FALSE);+}++/// Pose preset ids as JSON (`["idle","wave",...]`) for the gallery.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeGetPosesJson<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+) -> jstring {+ let json = serde_json::to_string(+ &avatar::preset_poses().iter().map(|p| &p.id).collect::<Vec<_>>(),+ )+ .unwrap_or_else(|_| "[]".to_string());+ env.with_env(|env| -> jni::errors::Result<jstring> {+ let null = std::ptr::null_mut();+ match env.new_string(json) {+ Ok(s) => Ok(s.into_raw()),+ Err(_) => Ok(null),+ }+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+}++/// Activity gone: destroy everything.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_hub_util_YuuAvatarNative_nativeOnDestroy<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+) {+ engine::destroy_engine();+}++#[cfg(test)]+mod tests {+ use crate::mesh::build_avatar_mesh;++ #[test]+ fn engine_smoke() {+ let mesh = build_avatar_mesh();+ assert!(!mesh.is_empty());+ let poses = crate::avatar::preset_poses();+ assert!(poses.iter().any(|p| p.id == "wave"));+ }+}
games/hub/src/main/rust/src/mesh.rs
diff --git a/games/hub/src/main/rust/src/mesh.rs b/games/hub/src/main/rust/src/mesh.rsnew file mode 100644index 0000000000..3bf6be6c03--- /dev/null+++ b/games/hub/src/main/rust/src/mesh.rs@@ -0,0 +1,250 @@+//! Skinned avatar mesh: vertex format, procedural fallback, glTF loading.+//!+//! The v1 path is procedural: [`build_avatar_mesh`] emits an upper-body+//! approximation (head sphere-ish, torso, arms) bound to the [`crate::avatar`]+//! skeleton with 4-bone weights. [`load_gltf_mesh`] parses a rigged+//! `base_upperbody.glb` when one is bundled, remapping its joints onto the+//! same UBO order so poses behave identically either way.++use crate::avatar::{joint_by_name, ALL_JOINTS, JOINT_COUNT};++/// One skinned vertex. Matches `yuu_avatar.vert` locations 0..4.+#[derive(Clone, Copy, Debug, Default)]+#[repr(C)]+pub struct YuuVertex {+ /// Model-space position.+ pub pos: [f32; 3],+ /// Model-space normal.+ pub normal: [f32; 3],+ /// Albedo UV.+ pub uv: [f32; 2],+ /// Bone indices into the UBO order.+ pub joints: [u32; 4],+ /// Bone weights (normalized).+ pub weights: [f32; 4],+}++/// A rigid part swept into skinned vertices with a single bone weight.+struct Part {+ /// Center of the box.+ center: [f32; 3],+ /// Full size of the box.+ size: [f32; 3],+ /// Primary bone index.+ joint: u32,+ /// Secondary bone index (blends toward the parent at the seam).+ blend_joint: u32,+ /// Blend factor 0..1 toward the secondary bone.+ blend: f32,+ /// Skin-tone albedo flag (true = skin, false = shirt).+ skin: bool,+}++/// Push an axis-aligned box as skinned triangles into `out`.+fn box_skinned(out: &mut Vec<YuuVertex>, part: &Part) {+ let (cx, cy, cz) = (part.center[0], part.center[1], part.center[2]);+ let (sx, sy, sz) = (part.size[0] / 2.0, part.size[1] / 2.0, part.size[2] / 2.0);+ // 8 corners.+ let c = [+ [cx - sx, cy - sy, cz - sz],+ [cx + sx, cy - sy, cz - sz],+ [cx + sx, cy + sy, cz - sz],+ [cx - sx, cy + sy, cz - sz],+ [cx - sx, cy - sy, cz + sz],+ [cx + sx, cy - sy, cz + sz],+ [cx + sx, cy + sy, cz + sz],+ [cx - sx, cy + sy, cz + sz],+ ];+ // 6 faces: (corners, normal).+ let faces: [([usize; 4], [f32; 3]); 6] = [+ ([0, 1, 2, 3], [0.0, 0.0, -1.0]),+ ([5, 4, 7, 6], [0.0, 0.0, 1.0]),+ ([4, 0, 3, 7], [-1.0, 0.0, 0.0]),+ ([1, 5, 6, 2], [1.0, 0.0, 0.0]),+ ([4, 5, 1, 0], [0.0, -1.0, 0.0]),+ ([3, 2, 6, 7], [0.0, 1.0, 0.0]),+ ];+ let w0 = 1.0 - part.blend;+ for (corners, normal) in faces {+ // Simple planar UV per face.+ let uvs = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];+ let idx = [corners[0], corners[1], corners[2], corners[0], corners[2], corners[3]];+ let uv_idx = [0, 1, 2, 0, 2, 3];+ for k in 0..6 {+ out.push(YuuVertex {+ pos: c[idx[k]],+ normal,+ uv: if part.skin { [uvs[uv_idx[k]][0] * 0.25, uvs[uv_idx[k]][1] * 0.25] } else { [0.5 + uvs[uv_idx[k]][0] * 0.5, uvs[uv_idx[k]][1] * 0.5] },+ joints: [part.joint, part.blend_joint, 0, 0],+ weights: [w0, part.blend, 0.0, 0.0],+ });+ }+ }+}++/// Joint index helper by name (0 when unknown — weighted to root).+fn j(name: &str) -> u32 {+ joint_by_name(name).map(|jj| jj as u32).unwrap_or(0)+}++/// Build the procedural fallback upper-body mesh bound to the v1 skeleton.+///+/// Proportions are Mii-like (big head, simple torso/arms); the renderer tints+/// skin vs shirt regions via the UV split in [`box_skinned`].+pub fn build_avatar_mesh() -> Vec<YuuVertex> {+ let mut out = Vec::with_capacity(1024);+ // Head: stacked boxes approximating a rounded skull + jaw.+ let head = Part { center: [0.0, 1.28, 0.0], size: [0.30, 0.30, 0.28], joint: j("head"), blend_joint: j("neck"), blend: 0.15, skin: true };+ box_skinned(&mut out, &head);+ let jaw = Part { center: [0.0, 1.10, 0.02], size: [0.24, 0.12, 0.24], joint: j("head"), blend_joint: j("neck"), blend: 0.25, skin: true };+ box_skinned(&mut out, &jaw);+ // Neck.+ let neck = Part { center: [0.0, 1.02, 0.0], size: [0.10, 0.10, 0.10], joint: j("neck"), blend_joint: j("chest"), blend: 0.3, skin: true };+ box_skinned(&mut out, &neck);+ // Torso (shirt region).+ let chest = Part { center: [0.0, 0.82, 0.0], size: [0.44, 0.30, 0.26], joint: j("chest"), blend_joint: j("spine"), blend: 0.25, skin: false };+ box_skinned(&mut out, &chest);+ let waist = Part { center: [0.0, 0.58, 0.0], size: [0.38, 0.22, 0.24], joint: j("spine"), blend_joint: j("root"), blend: 0.3, skin: false };+ box_skinned(&mut out, &waist);+ // Arms (skin hands, shirt sleeves).+ for side in [-1.0f32, 1.0] {+ let (clav, upper, fore, hand) = if side < 0.0 {+ ("clavicle_L", "upperArm_L", "forearm_L", "hand_L")+ } else {+ ("clavicle_R", "upperArm_R", "forearm_R", "hand_R")+ };+ let shoulder = Part { center: [side * 0.26, 0.90, 0.0], size: [0.12, 0.12, 0.14], joint: j(upper), blend_joint: j(clav), blend: 0.4, skin: false };+ box_skinned(&mut out, &shoulder);+ let upper_arm = Part { center: [side * 0.30, 0.74, 0.0], size: [0.11, 0.26, 0.12], joint: j(upper), blend_joint: j(clav), blend: 0.2, skin: false };+ box_skinned(&mut out, &upper_arm);+ let forearm = Part { center: [side * 0.31, 0.50, 0.0], size: [0.10, 0.24, 0.11], joint: j(fore), blend_joint: j(upper), blend: 0.25, skin: true };+ box_skinned(&mut out, &forearm);+ let hand = Part { center: [side * 0.31, 0.34, 0.0], size: [0.10, 0.10, 0.10], joint: j(hand), blend_joint: j(fore), blend: 0.3, skin: true };+ box_skinned(&mut out, &hand);+ }+ out+}++/// Load a rigged glTF mesh, remapping its joints onto the UBO order.+///+/// Returns the procedural fallback when `bytes` fail to parse, so a missing+/// or corrupt `base_upperbody.glb` never breaks the preview — the skeleton and+/// poses behave identically since both paths share bone order.+pub fn load_gltf_mesh(bytes: &[u8]) -> Vec<YuuVertex> {+ match parse_gltf(bytes) {+ Some(mesh) if !mesh.is_empty() => mesh,+ _ => build_avatar_mesh(),+ }+}++/// Minimal glTF parser: first mesh primitive with POSITION + JOINTS_0/WEIGHTS_0.+fn parse_gltf(bytes: &[u8]) -> Option<Vec<YuuVertex>> {+ let (doc, buffers, _) = gltf::import_slice(bytes).ok()?;+ let mesh = doc.meshes().next()?;+ let prim = mesh.primitives().next()?;+ let reader = prim.reader(|buffer| Some(&buffers[buffer.index()]));+ let positions: Vec<[f32; 3]> = reader.read_positions()?.collect();+ let normals: Vec<[f32; 3]> = reader+ .read_normals()+ .map(|it| it.collect())+ .unwrap_or_else(|| vec![[0.0, 1.0, 0.0]; positions.len()]);+ let uvs: Vec<[f32; 2]> = reader+ .read_tex_coords(0)+ .map(|tc| tc.into_f32().collect())+ .unwrap_or_else(|| vec![[0.0, 0.0]; positions.len()]);+ let joints_raw: Vec<[u16; 4]> = reader.read_joints(0).map(|it| it.into_u16().collect()).unwrap_or_default();+ let weights_raw: Vec<[f32; 4]> = reader.read_weights(0).map(|it| it.into_f32().collect()).unwrap_or_default();+ // Skin-joint-slot -> UBO order remap via node names. JOINTS_0 indexes+ // `skin.joints` (an indirection into nodes), NOT global node order, so+ // resolve through the skin's joint list.+ let mut remap = vec![0u32; 256];+ if let Some(skin) = doc.skins().next() {+ for (slot, node) in skin.joints().enumerate() {+ if slot >= remap.len() {+ break;+ }+ if let Some(name) = node.name() {+ if let Some(jj) = joint_by_name(name) {+ remap[slot] = jj as u32;+ }+ }+ }+ }+ let mut out = Vec::with_capacity(positions.len());+ for i in 0..positions.len() {+ let js = joints_raw.get(i).copied().unwrap_or([0; 4]);+ let ws = normalize_weights(weights_raw.get(i).copied().unwrap_or([1.0, 0.0, 0.0, 0.0]));+ out.push(YuuVertex {+ pos: positions[i],+ normal: *normals.get(i).unwrap_or(&[0.0, 1.0, 0.0]),+ uv: *uvs.get(i).unwrap_or(&[0.0, 0.0]),+ joints: [+ *remap.get(js[0] as usize).unwrap_or(&0),+ *remap.get(js[1] as usize).unwrap_or(&0),+ *remap.get(js[2] as usize).unwrap_or(&0),+ *remap.get(js[3] as usize).unwrap_or(&0),+ ],+ weights: ws,+ });+ }+ // Indexed or flat: expand indices when present. OOB indices mean a+ // corrupt asset — bail to the procedural fallback instead of clamping+ // (which would smear the last vertex across the mesh).+ if let Some(indices) = reader.read_indices() {+ let idx: Vec<u32> = indices.into_u32().collect();+ if idx.iter().any(|ii| (*ii as usize) >= out.len()) {+ return None;+ }+ let expanded: Vec<YuuVertex> = idx.iter().map(|ii| out[*ii as usize]).collect();+ return Some(expanded);+ }+ Some(out)+}++/// Normalize skin weights (guard degenerate sums); unweighted verts bind+/// fully to joint 0 via the caller's joint default.+fn normalize_weights(ws: [f32; 4]) -> [f32; 4] {+ let sum: f32 = ws.iter().sum();+ if sum < 1e-6 {+ [1.0, 0.0, 0.0, 0.0]+ } else {+ [ws[0] / sum, ws[1] / sum, ws[2] / sum, ws[3] / sum]+ }+}++/// Vertex count sanity for the Vulkan budget check.+pub fn mesh_budgets() -> (usize, usize) {+ // Static avatar mesh cap + one dynamic upload (same buffer reused).+ (65_536, 8_192)+}++/// Joint count exposed for UBO sizing asserts.+pub fn joint_count() -> usize {+ JOINT_COUNT+}++/// All joint names in UBO order (for asset validation logs).+pub fn joint_names() -> Vec<&'static str> {+ ALL_JOINTS.iter().copied().map(crate::avatar::joint_name).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn fallback_mesh_is_nonempty_and_weighted() {+ let mesh = build_avatar_mesh();+ assert!(!mesh.is_empty());+ for v in mesh.iter().take(64) {+ let w: f32 = v.weights.iter().sum();+ assert!((w - 1.0).abs() < 1e-4, "weights must sum to 1, got {w}");+ }+ }++ #[test]+ fn corrupt_gltf_falls_back() {+ let mesh = load_gltf_mesh(b"not a glb");+ assert!(!mesh.is_empty());+ }+}
games/hub/src/main/rust/src/renderer.rs
diff --git a/games/hub/src/main/rust/src/renderer.rs b/games/hub/src/main/rust/src/renderer.rsnew file mode 100644index 0000000000..0e86ef7559--- /dev/null+++ b/games/hub/src/main/rust/src/renderer.rs@@ -0,0 +1,174 @@+//! Renderer seam: which GPU backend drew the frame.+//!+//! Same arrangement as games/kart: Vulkan wins where drivers exist (64-bit+//! phones); GLES covers Vulkan-less boxes. Split from `engine.rs` along module+//! lines so neither file trips the 500-line Rust gate.++use crate::avatar::MAX_BONES;+use crate::gles::renderer::GlesRenderer;+use crate::mesh::YuuVertex;+use crate::vulkan::renderer::YuuRenderer;++/// Which GPU backend drew the frame. `create_renderer` tries Vulkan first,+/// falls back to GLES, and fails only when both fail.+pub enum Renderer {+ /// Vulkan path (`ash` loaded): instance + swapchain + pipeline.+ Vulkan(YuuRenderer),+ /// GLES 3.0 path (`glow` + `khronos-egl`): EGL surface + GL program.+ Gles(GlesRenderer),+}++impl Renderer {+ /// Current surface width (either backend).+ pub fn width(&self) -> u32 {+ match self {+ Self::Vulkan(r) => r.width,+ Self::Gles(r) => r.width,+ }+ }++ /// Current surface height (either backend).+ pub fn height(&self) -> u32 {+ match self {+ Self::Vulkan(r) => r.height,+ Self::Gles(r) => r.height,+ }+ }++ /// Upload the static avatar mesh (once per surface; capped per backend).+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn upload_avatar(&mut self, mesh: &[YuuVertex]) {+ match self {+ Self::Vulkan(r) => unsafe { r.upload_avatar(mesh) },+ Self::Gles(r) => unsafe { r.upload_avatar(mesh) },+ }+ }++ /// Resize the swapchain/surface.+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn resize(&mut self, width: u32, height: u32) {+ match self {+ Self::Vulkan(r) => unsafe { r.resize(width, height) },+ Self::Gles(r) => unsafe { r.resize(width, height) },+ }+ }++ /// Draw one frame: bone UBO + avatar mesh.+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn draw(+ &mut self,+ view_proj: [[f32; 4]; 4],+ cam_pos: [f32; 3],+ bones: [[f32; 16]; MAX_BONES],+ skin_rgb: [f32; 3],+ mesh_count: usize,+ ) -> Result<(), String> {+ match self {+ Self::Vulkan(r) => unsafe { r.draw(view_proj, cam_pos, bones, skin_rgb, mesh_count) },+ Self::Gles(r) => unsafe { r.draw(view_proj, cam_pos, bones, skin_rgb, mesh_count) },+ }+ }++ /// Free everything except the window (the engine releases that itself).+ ///+ /// # Safety+ /// Must be called on the render thread that owns the backend's context.+ pub unsafe fn destroy(&mut self) {+ match self {+ Self::Vulkan(r) => unsafe { r.destroy() },+ Self::Gles(r) => unsafe { r.destroy() },+ }+ }++ /// Tear down the Vulkan instance + device. No-op on GLES.+ pub fn destroy_context(&mut self) {+ if let Self::Vulkan(r) = self {+ r.ctx.destroy();+ }+ }++ /// Vulkan-only attempt (used by [`crate::engine::try_vulkan`]).+ ///+ /// # Safety+ /// `window` must be a live adopted `ANativeWindow`; ownership stays with+ /// the engine (released on destroy), as on the kart path.+ pub unsafe fn try_vulkan_only(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: i32,+ height: i32,+ state_width: u32,+ state_height: u32,+ ) -> Result<Self, String> {+ match crate::vulkan::renderer::YuuRenderer::new(window, width, height, state_width, state_height) {+ Ok(r) => Ok(Self::Vulkan(r)),+ Err(e) => Err(e),+ }+ }++ /// Build the winning backend for `window`: GLES-first on 32-bit (where a+ /// `libvulkan.so` loader stub with no driver behind it SIGSEGVs inside+ /// `create_instance` instead of returning an error), Vulkan-first on+ /// 64-bit. `Err` only when both backends fail.+ ///+ /// # Safety+ /// `window` must be a live adopted `ANativeWindow`; ownership stays with+ /// the engine (released on destroy), as on the Vulkan path.+ pub unsafe fn select(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: i32,+ height: i32,+ state_width: u32,+ state_height: u32,+ ) -> Result<Self, String> {+ #[cfg(target_pointer_width = "32")]+ {+ match unsafe { GlesRenderer::new(window, state_width, state_height) } {+ Ok(r) => {+ crate::engine::log_backend("GLES");+ Ok(Self::Gles(r))+ }+ Err(gles_err) => {+ match unsafe { Self::try_vulkan_only(window, width, height, state_width, state_height) } {+ Ok(r) => {+ crate::engine::log_backend(&format!(+ "Vulkan (GLES init failed: {gles_err})"+ ));+ Ok(r)+ }+ Err(vulkan_err) => {+ Err(format!("no renderer (GLES: {gles_err}; Vulkan: {vulkan_err})"))+ }+ }+ }+ }+ }+ #[cfg(not(target_pointer_width = "32"))]+ {+ match unsafe { Self::try_vulkan_only(window, width, height, state_width, state_height) } {+ Ok(r) => {+ crate::engine::log_backend("Vulkan");+ Ok(r)+ }+ Err(vulkan_err) => {+ match unsafe { GlesRenderer::new(window, state_width, state_height) } {+ Ok(r) => {+ crate::engine::log_backend(&format!(+ "GLES (Vulkan init failed: {vulkan_err})"+ ));+ Ok(Self::Gles(r))+ }+ Err(gles_err) => Err(format!(+ "no renderer (Vulkan: {vulkan_err}; GLES: {gles_err})"+ )),+ }+ }+ }+ }+ }+}
games/hub/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/hub/src/main/rust/src/vulkan/buffers.rs b/games/hub/src/main/rust/src/vulkan/buffers.rsnew file mode 100644index 0000000000..33c20a194c--- /dev/null+++ b/games/hub/src/main/rust/src/vulkan/buffers.rs@@ -0,0 +1,189 @@+//! Vertex + uniform buffers: the skinned Yuu vertex format, the bone-matrix+//! UBO, and the host-visible upload helper.+//!+//! Same arrangement as games/kart `vulkan/buffers.rs`: one `AllocatedBuffer`+//! (buffer + memory + size) with an `upload` that maps, copies, and unmaps.+//! The avatar mesh is small (one hero instance), so a single static upload+//! plus per-f
Diff truncated.