avatar: extract yuu engine to library, multi-surface, vulkan, assets, 3D grid
- Commit
89d01cf578f7f39260adb887e2d0a066e0cd0fd3- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-19 21:14 UTC (1 month ago)
- Parents
edc457b
Diff
Cargo.toml
diff --git a/Cargo.toml b/Cargo.tomlindex f184c7b8ca..ab72806429 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -25,7 +25,7 @@ members = [ "share/src/main/rust", "games/voxels/src/main/rust", "games/kart/src/main/rust",- "games/hub/src/main/rust",+ "library/avatar/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 368ce4ac9e..fba71b2ba7 100644--- a/games/hub/build.gradle.kts+++ b/games/hub/build.gradle.kts@@ -15,26 +15,11 @@ 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")) implementation(project(":library:room"))+ implementation(project(":library:avatar")) implementation(project(":sdk:games")) // "Play on TV": the generic phone-as-controller SDK (pad UI + discovery + // client) plus PQC sealing for the handshake's session secret.
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.ktdeleted file mode 100644index 130c995e12..0000000000--- a/games/hub/src/main/java/com/vayunmathur/games/hub/platform/YuuAvatarNative.kt+++ /dev/null@@ -1,82 +0,0 @@-// 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/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.ktindex cb46ed2e6f..3dfd858182 100644--- 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.kt@@ -6,7 +6,7 @@ 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.avatar.yuu.YUU_POSES import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.Text
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 408aea274c..4f7c1548f3 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@@ -28,8 +28,10 @@ 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.data.entities.encode import com.vayunmathur.games.hub.ui.components.YuuBadge+import com.vayunmathur.games.hub.ui.yuu.DASHBOARD_SURFACE_ID+import com.vayunmathur.library.avatar.components.YuuAvatar3D import com.vayunmathur.games.hub.util.DashboardActions import com.vayunmathur.games.hub.util.DashboardUiState import com.vayunmathur.games.hub.util.formatPlaytime@@ -77,9 +79,13 @@ fun DashboardScreen( Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { if (BuildConfig.DEV_BUILD && state.profileYuu != null) { YuuAvatar3D(- config = state.profileYuu.config,+ configJson = state.profileYuu.config.encode(), poseId = state.profileYuu.config.poseId,+ surfaceId = DASHBOARD_SURFACE_ID, modifier = Modifier.size(56.dp),+ fallback = {+ AvatarBadge(symbol = state.avatarSymbol, large = true)+ }, ) } 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 bf74945690..6609788eea 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@@ -25,13 +25,15 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.vayunmathur.games.hub.R import com.vayunmathur.games.hub.BuildConfig+import com.vayunmathur.games.hub.data.entities.encode 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.ui.yuu.PROFILE_SURFACE_ID+import com.vayunmathur.library.avatar.components.YuuAvatar3D import com.vayunmathur.games.hub.util.ProfileActions import com.vayunmathur.games.hub.util.ProfileUiState import com.vayunmathur.games.hub.util.XpLevelCalculator@@ -88,9 +90,13 @@ fun ProfileScreen( Column(modifier = Modifier.padding(24.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally) { if (BuildConfig.DEV_BUILD && state.profileYuu != null) { YuuAvatar3D(- config = state.profileYuu.config,+ configJson = state.profileYuu.config.encode(), poseId = state.profileYuu.config.poseId,+ surfaceId = PROFILE_SURFACE_ID, modifier = Modifier.size(96.dp),+ fallback = {+ AvatarBadge(symbol = state.avatarSymbol, large = true)+ }, ) YuuPoseGallery( selectedPoseId = state.profileYuu.config.poseId,
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 1736fd5d6a..6c4d2b6276 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,9 +40,13 @@ 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.data.entities.encode import com.vayunmathur.games.hub.ui.components.YuuFace import com.vayunmathur.games.hub.ui.components.YuuPoseGallery+import com.vayunmathur.games.hub.ui.yuu.EDITOR_SURFACE_ID+import com.vayunmathur.games.hub.ui.yuu.YuuSurfaceIds+import com.vayunmathur.library.avatar.components.YuuAvatar3D+import com.vayunmathur.games.hub.ui.yuu.EDITOR_SURFACE_ID import com.vayunmathur.games.hub.ui.yuu.YuuCategory import com.vayunmathur.games.hub.ui.yuu.YuuEditorActions import com.vayunmathur.games.hub.ui.yuu.YuuEditorUiState@@ -114,9 +118,17 @@ fun YuuEditorScreen( contentAlignment = Alignment.Center, ) { YuuAvatar3D(- config = draft.toConfig(),+ configJson = draft.toConfig().encode(), poseId = draft.poseId,+ surfaceId = EDITOR_SURFACE_ID, modifier = Modifier.fillMaxWidth(0.72f).aspectRatio(0.9f).padding(8.dp),+ fallback = {+ YuuFace(+ config = draft.toConfig(),+ withBody = true,+ 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.@@ -418,6 +430,43 @@ private fun VariantCell( } } +/**+ * Live-3D variant cell: renders the full draft config with one field+ * overridden, keyed by a stable cell id. Over the live-surface cap it falls+ * back to the 2D thumbnail (see [YuuSurfaceIds]).+ */+@Composable+private fun VariantCell3D(+ cellId: Int,+ config: YuuFaceConfig,+ selected: Boolean,+ onClick: () -> Unit,+) {+ Card(+ onClick = onClick,+ border = if (selected) {+ BorderStroke(2.dp, MaterialTheme.colorScheme.primary)+ } else null,+ modifier = Modifier.aspectRatio(1f),+ ) {+ Box(modifier = Modifier.fillMaxSize().padding(6.dp), contentAlignment = Alignment.Center) {+ if (YuuSurfaceIds.isLive(cellId)) {+ YuuAvatar3D(+ configJson = config.encode(),+ poseId = config.poseId,+ surfaceId = cellId,+ modifier = Modifier.fillMaxSize(),+ fallback = {+ YuuFace(config = config, modifier = Modifier.fillMaxSize())+ },+ )+ } else {+ YuuFace(config = config, modifier = Modifier.fillMaxSize())+ }+ }+ }+}+ @Composable private fun ColorSwatches( colors: List<Long>,@@ -451,9 +500,12 @@ private fun FacePanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_face_shape)) VariantGrid(count = YuuFaceConfig.FACE_SHAPES, selected = d.faceShape) { i, sel ->- VariantCell(sel, onClick = { d.faceShape = i }) {- YuuFace(YuuFaceConfig(faceShape = i, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(0, i),+ config = d.toConfig().copy(faceShape = i),+ selected = sel,+ onClick = { d.faceShape = i },+ ) } SectionLabel(stringResource(R.string.yuu_skin_tone)) ColorSwatches(YUU_SKIN_TONES, d.skinTone) { d.skinTone = it }@@ -479,9 +531,12 @@ private fun HairPanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_hair_style)) VariantGrid(count = YuuFaceConfig.HAIR_STYLES, selected = d.hairStyle) { i, sel ->- VariantCell(sel, onClick = { d.hairStyle = i }) {- YuuFace(YuuFaceConfig(hairStyle = i, hairColor = d.hairColor, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(1, i),+ config = d.toConfig().copy(hairStyle = i),+ selected = sel,+ onClick = { d.hairStyle = i },+ ) } SectionLabel(stringResource(R.string.yuu_hair_color)) ColorSwatches(YUU_HAIR_COLORS, d.hairColor) { d.hairColor = it }@@ -493,9 +548,12 @@ private fun EyesPanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_eye_style)) VariantGrid(count = YuuFaceConfig.EYE_STYLES, selected = d.eyeStyle) { i, sel ->- VariantCell(sel, onClick = { d.eyeStyle = i }) {- YuuFace(YuuFaceConfig(eyeStyle = i, eyeColor = d.eyeColor, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(2, i),+ config = d.toConfig().copy(eyeStyle = i),+ selected = sel,+ onClick = { d.eyeStyle = i },+ ) } SectionLabel(stringResource(R.string.yuu_eye_color)) ColorSwatches(YUU_EYE_COLORS, d.eyeColor) { d.eyeColor = it }@@ -507,9 +565,12 @@ private fun BrowsPanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_brow_style)) VariantGrid(count = YuuFaceConfig.BROW_STYLES, selected = d.browStyle) { i, sel ->- VariantCell(sel, onClick = { d.browStyle = i }) {- YuuFace(YuuFaceConfig(browStyle = i, browColor = d.browColor, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(3, i),+ config = d.toConfig().copy(browStyle = i),+ selected = sel,+ onClick = { d.browStyle = i },+ ) } SectionLabel(stringResource(R.string.yuu_brow_color)) ColorSwatches(YUU_HAIR_COLORS, d.browColor) { d.browColor = it }@@ -521,9 +582,12 @@ private fun NosePanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_nose_style)) VariantGrid(count = YuuFaceConfig.NOSE_STYLES, selected = d.noseStyle) { i, sel ->- VariantCell(sel, onClick = { d.noseStyle = i }) {- YuuFace(YuuFaceConfig(noseStyle = i, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(4, i),+ config = d.toConfig().copy(noseStyle = i),+ selected = sel,+ onClick = { d.noseStyle = i },+ ) } } }@@ -533,9 +597,12 @@ private fun MouthPanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_mouth_style)) VariantGrid(count = YuuFaceConfig.MOUTH_STYLES, selected = d.mouthStyle) { i, sel ->- VariantCell(sel, onClick = { d.mouthStyle = i }) {- YuuFace(YuuFaceConfig(mouthStyle = i, mouthColor = d.mouthColor, skinTone = d.skinTone), Modifier.fillMaxSize())- }+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(5, i),+ config = d.toConfig().copy(mouthStyle = i),+ selected = sel,+ onClick = { d.mouthStyle = i },+ ) } SectionLabel(stringResource(R.string.yuu_mouth_color)) ColorSwatches(YUU_MOUTH_COLORS, d.mouthColor) { d.mouthColor = it }@@ -547,32 +614,77 @@ private fun ExtrasPanel(d: YuuDraft) { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { SectionLabel(stringResource(R.string.yuu_glasses)) VariantGrid(count = YuuFaceConfig.GLASSES_STYLES + 1, selected = d.glassesStyle) { i, sel ->- VariantCell(sel, onClick = { d.glassesStyle = i }) {- if (i == 0) Text(stringResource(UiR.string.none)) else YuuFace(YuuFaceConfig(glassesStyle = i, skinTone = d.skinTone), Modifier.fillMaxSize())+ if (i == 0) {+ VariantCell(sel, onClick = { d.glassesStyle = i }) {+ Text(stringResource(UiR.string.none))+ }+ } else {+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(6, i),+ config = d.toConfig().copy(glassesStyle = i),+ selected = sel,+ onClick = { d.glassesStyle = i },+ ) } } SectionLabel(stringResource(R.string.yuu_beard)) VariantGrid(count = YuuFaceConfig.BEARD_STYLES + 1, selected = d.beardStyle) { i, sel ->- VariantCell(sel, onClick = { d.beardStyle = i }) {- if (i == 0) Text(stringResource(UiR.string.none)) else YuuFace(YuuFaceConfig(beardStyle = i, skinTone = d.skinTone, hairColor = d.hairColor), Modifier.fillMaxSize())+ if (i == 0) {+ VariantCell(sel, onClick = { d.beardStyle = i }) {+ Text(stringResource(UiR.string.none))+ }+ } else {+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(7, i),+ config = d.toConfig().copy(beardStyle = i),+ selected = sel,+ onClick = { d.beardStyle = i },+ ) } } SectionLabel(stringResource(R.string.yuu_mole)) VariantGrid(count = YuuFaceConfig.MOLE_STYLES + 1, selected = d.moleStyle) { i, sel ->- VariantCell(sel, onClick = { d.moleStyle = i }) {- if (i == 0) Text(stringResource(UiR.string.none)) else YuuFace(YuuFaceConfig(moleStyle = i, skinTone = d.skinTone), Modifier.fillMaxSize())+ if (i == 0) {+ VariantCell(sel, onClick = { d.moleStyle = i }) {+ Text(stringResource(UiR.string.none))+ }+ } else {+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(8, i),+ config = d.toConfig().copy(moleStyle = i),+ selected = sel,+ onClick = { d.moleStyle = i },+ ) } } SectionLabel(stringResource(R.string.yuu_wrinkles)) VariantGrid(count = YuuFaceConfig.WRINKLE_STYLES + 1, selected = d.wrinkleStyle) { i, sel ->- VariantCell(sel, onClick = { d.wrinkleStyle = i }) {- if (i == 0) Text(stringResource(UiR.string.none)) else YuuFace(YuuFaceConfig(wrinkleStyle = i, skinTone = d.skinTone), Modifier.fillMaxSize())+ if (i == 0) {+ VariantCell(sel, onClick = { d.wrinkleStyle = i }) {+ Text(stringResource(UiR.string.none))+ }+ } else {+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(9, i),+ config = d.toConfig().copy(wrinkleStyle = i),+ selected = sel,+ onClick = { d.wrinkleStyle = i },+ ) } } SectionLabel(stringResource(R.string.yuu_blush)) VariantGrid(count = YuuFaceConfig.BLUSH_STYLES + 1, selected = d.blushStyle) { i, sel ->- VariantCell(sel, onClick = { d.blushStyle = i }) {- if (i == 0) Text(stringResource(UiR.string.none)) else YuuFace(YuuFaceConfig(blushStyle = i, skinTone = d.skinTone), Modifier.fillMaxSize())+ if (i == 0) {+ VariantCell(sel, onClick = { d.blushStyle = i }) {+ Text(stringResource(UiR.string.none))+ }+ } else {+ VariantCell3D(+ cellId = YuuSurfaceIds.forVariant(10, i),+ config = d.toConfig().copy(blushStyle = i),+ selected = sel,+ onClick = { d.blushStyle = i },+ ) } } }
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuScreen.ktindex 857323f281..3bf0f0aaf7 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuScreen.kt+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/YuuScreen.kt@@ -25,9 +25,12 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.vayunmathur.games.hub.R import com.vayunmathur.games.hub.data.YuuUiModel+import com.vayunmathur.games.hub.data.entities.encode import com.vayunmathur.games.hub.ui.components.YuuFace import com.vayunmathur.games.hub.ui.yuu.YuuListActions import com.vayunmathur.games.hub.ui.yuu.YuuListUiState+import com.vayunmathur.games.hub.ui.yuu.YuuSurfaceIds+import com.vayunmathur.library.avatar.components.YuuAvatar3D import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DropdownMenu@@ -116,10 +119,29 @@ private fun YuuCard( verticalArrangement = Arrangement.spacedBy(8.dp), ) { Box(contentAlignment = Alignment.TopEnd) {- YuuFace(- config = yuu.config,- modifier = Modifier.fillMaxWidth().aspectRatio(1f),- )+ // Live 3D cell with a stable id (keyed by Yuu id, not position)+ // so config/pose never bleeds across recycled cells. Over the+ // live-surface cap the cell falls back to the 2D thumbnail.+ val surfaceId = YuuSurfaceIds.forYuu(yuu.id)+ if (YuuSurfaceIds.isLive(surfaceId)) {+ YuuAvatar3D(+ configJson = yuu.config.encode(),+ poseId = yuu.config.poseId,+ surfaceId = surfaceId,+ modifier = Modifier.fillMaxWidth().aspectRatio(1f),+ fallback = {+ YuuFace(+ config = yuu.config,+ modifier = Modifier.fillMaxWidth().aspectRatio(1f),+ )+ },+ )+ } else {+ YuuFace(+ config = yuu.config,+ modifier = Modifier.fillMaxWidth().aspectRatio(1f),+ )+ } IconButton(onClick = { menuOpen = true }) { IconMoreVert() } DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { DropdownMenuItem(
games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuSurfaceIds.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuSurfaceIds.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuSurfaceIds.ktnew file mode 100644index 0000000000..2915f58372--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuSurfaceIds.kt@@ -0,0 +1,45 @@+package com.vayunmathur.games.hub.ui.yuu++/**+ * Stable surface ids for the multi-renderer avatar engine. Kotlin owns+ * identity: each hero surface gets a fixed id so the engine can route+ * config/pose/lifecycle per surface. Grid cells (Phase E) derive ids from+ * their Yuu/variant keys instead.+ */+const val EDITOR_SURFACE_ID = 1+const val DASHBOARD_SURFACE_ID = 2+const val PROFILE_SURFACE_ID = 3++/**+ * Live-surface budget for the 3D grid expansion. Each live surface holds a+ * swapchain + render thread + up to ~4MB of GPU buffers; beyond+ * [MAX_LIVE_SURFACES] cells fall back to 2D thumbnails. Heroes (ids 1–3)+ * always win eviction priority and are never counted here.+ */+object YuuSurfaceIds {+ /** Max concurrent live 3D grid cells (tune on-device; start conservative). */+ const val MAX_LIVE_SURFACES = 8++ /** Base for Yuu-derived cell ids (heroes occupy 1–3). */+ private const val CELL_BASE = 1000++ /** Base for editor variant-cell ids (per-panel base + variant index). */+ private const val VARIANT_BASE = 100000++ /** Stable cell id for a Yuu row id. */+ fun forYuu(yuuId: Long): Int = CELL_BASE + (yuuId % 100000).toInt()++ /** Stable cell id for an editor variant (panel base + variant index). */+ fun forVariant(panelBase: Int, variant: Int): Int = VARIANT_BASE + panelBase * 100 + variant++ /**+ * Whether a cell id currently holds a live surface. Budget gate: the+ * lowest ids win so the first cells render 3D and the rest stay 2D.+ * Called during composition — pure arithmetic, no allocation.+ */+ fun isLive(surfaceId: Int): Boolean = when {+ surfaceId >= VARIANT_BASE -> surfaceId - VARIANT_BASE < MAX_LIVE_SURFACES+ surfaceId >= CELL_BASE -> surfaceId - CELL_BASE < MAX_LIVE_SURFACES+ else -> true+ }+}
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.rsdeleted file mode 100644index 6f34e4650c..0000000000--- a/games/hub/src/main/rust/src/engine.rs+++ /dev/null@@ -1,316 +0,0 @@-//! 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/lib.rs
diff --git a/games/hub/src/main/rust/src/lib.rs b/games/hub/src/main/rust/src/lib.rsdeleted file mode 100644index c4b464ab0f..0000000000--- a/games/hub/src/main/rust/src/lib.rs+++ /dev/null@@ -1,180 +0,0 @@-//! 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/vulkan/renderer.rs
diff --git a/games/hub/src/main/rust/src/vulkan/renderer.rs b/games/hub/src/main/rust/src/vulkan/renderer.rsdeleted file mode 100644index bc485ee4ff..0000000000--- a/games/hub/src/main/rust/src/vulkan/renderer.rs+++ /dev/null@@ -1,113 +0,0 @@-//! Frame renderer: command pool, per-frame fence, bone UBO + avatar mesh-//! upload, albedo texture, draw.-//!-//! One in-flight frame at a time (the render thread ticks at 60 Hz and waits-//! on the fence before re-recording, so no frame ever overtakes another).-//! The avatar mesh uploads once per surface; the bone UBO re-uploads every-//! frame from the engine's pose. View-projection comes from the preview-//! camera with the surface pre-rotation prepended.-use crate::avatar::MAX_BONES;-use crate::mesh::YuuVertex;-use crate::vulkan::buffers::{AllocatedBuffer, YuuUbo, YuuVkVertex};-use crate::vulkan::context::VulkanContext;-use crate::vulkan::pipeline::Pipelines;-use crate::vulkan::swapchain::Swapchain;-use ash::vk;-use std::mem;--/// Static avatar mesh budget: the procedural fallback is ~1k verts; 64k-/// leaves margin for a detailed glTF base mesh.-const AVATAR_VERT_CAP: usize = 65_536;--/// Everything needed to draw one frame.-pub struct YuuRenderer {- /// Vulkan context (owns instance/device/surface).- pub ctx: VulkanContext,- /// Swapchain + depth + render pass + framebuffers.- pub swap: Swapchain,- /// Graphics pipeline + UBO/sampler descriptor set.- pub pipes: Pipelines,- /// Static avatar vertex buffer (uploaded per surface).- pub avatar_buf: AllocatedBuffer,- /// Uniform buffer (view-projection + sun + camera + bones).- pub ubo_buf: AllocatedBuffer,- /// Albedo texture image + memory + view + sampler (1x1 skin default).- pub albedo_image: vk::Image,- /// Albedo memory.- pub albedo_memory: vk::DeviceMemory,- /// Albedo view.- pub albedo_view: vk::ImageView,- /// Albedo sampler.- pub albedo_sampler: vk::Sampler,- /// Command pool (graphics family).- pub pool: vk::CommandPool,- /// One reusable command buffer.- pub cmd: vk::CommandBuffer,- /// Frame fence (signalled when the GPU finishes the frame).- pub fence: vk::Fence,- /// Image-acquired + render-finished semaphores.- pub sem_acquire: vk::Semaphore,- /// Image-acquired + render-finished semaphores.- pub sem_render: vk::Semaphore,- /// Current surface width.- pub width: u32,- /// Current surface height.- pub height: u32,-}--impl YuuRenderer {- /// Create from a live window at `width` x `height`. Fails cleanly.- ///- /// # Safety- /// `window` must be a live adopted `ANativeWindow`; ownership stays with- /// the engine (released on destroy), as on the kart path.- pub unsafe fn new(- window: *mut crate::vulkan::context::ANativeWindow,- width: i32,- height: i32,- state_width: u32,- state_height: u32,- ) -> Result<Self, String> {- let _ = (window, width, height, state_width, state_height);- // NOTE(size): full swapchain bring-up (Swapchain::new against the- // adopted window, depth, render pass) follows the kart- // `vulkan/renderer.rs::KartRenderer::new` sequence verbatim; this- // scaffold lands the avatar-side types (buffers/pipeline/UBO) first so- // `cargo check` validates the skinning pipeline before the backend- // copy-paste lands. Until then, creation reports unavailable and the- // Kotlin `isAvailable` fallback keeps the 2D preview.- Err("yuu_avatar Vulkan backend: swapchain bring-up lands next".to_string())- }-- /// Upload the static avatar mesh (once per surface; capped at the budget).- pub unsafe fn upload_avatar(&self, _mesh: &[YuuVertex]) {- // Filled in with the swapchain bring-up (see `new` note).- }-- /// Resize the swapchain.- pub unsafe fn resize(&mut self, width: u32, height: u32) {- self.width = width.max(1);- self.height = height.max(1);- }-- /// Draw one frame: upload the bone UBO, record, submit, present.- 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> {- // Filled in with the swapchain bring-up (see `new` note).- Ok(())- }-- /// Free everything except the context (the engine releases the window).- pub unsafe fn destroy(&mut self) {- // Filled in with the swapchain bring-up (see `new` note).- let _ = mem::size_of::<YuuUbo>();- let _ = mem::size_of::<YuuVkVertex>();- let _ = AVATAR_VERT_CAP;- }-}
library/avatar/AGENTS.md
diff --git a/library/avatar/AGENTS.md b/library/avatar/AGENTS.mdnew file mode 100644index 0000000000..6d1929c638--- /dev/null+++ b/library/avatar/AGENTS.md@@ -0,0 +1,53 @@+# AGENTS.md — library/avatar/ (':library:avatar')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `library/avatar/` + allowed shared modules. Do not root-scan.++_Install: dev by default (library, no launcher)._+<!-- last-reviewed: 2026-10-19 -->+- Gradle: :library:avatar / dir: library/avatar/+- Package roots present: `com.vayunmathur.library.avatar` (bridge), `...avatar.components` (surface/composable), `...avatar.yuu` (pose contract)+- Entry files: YuuAvatarNative.kt (JNI bridge), components/YuuAvatar3D.kt (hero composable)+- Deps: :library:ui, :library:log, androidx.lifecycle.runtime.compose+- Rust: yes (`src/main/rust/`, crate `yuu_avatar`, glTF + skinning)+- Metadata: none (library, no listing)++## Overview+**Purpose:** Shared 3D Yuu avatar engine: glTF upper-body base mesh, skeletal skinning, preset poses, Vulkan-first + GLES fallback. First consumer: `:games:hub` hero surfaces; future 3D games reuse the same bridge.+**Key features:** 13-joint upper-body rig, 5 preset poses, per-surface multi-renderer engine, procedural fallback mesh, turntable preview camera.+**Architecture:** Rust crate (`src/main/rust/`: `avatar.rs` skeleton/traits/poses → `engine.rs` per-surface lifecycle → `renderer.rs` dispatch → `vulkan/` + `gles/`) ↔ JNI (`YuuAvatarNative`, `internal object`, package matches directory) ↔ Compose (`YuuAvatar3D` + `YuuAvatarSurfaceView`).+**Entry points:** `YuuAvatar3D(configJson, poseId, surfaceId, modifier, fallback)` → `YuuAvatarNative` → Rust `lib.rs`.+## Gotchas+- Rust `preset_poses` is authoritative; `yuu/YuuPose.kt` `YUU_POSES` is the hand-kept mirror — update both.+- Vulkan `new()` brings up the swapchain; GLES is the fallback via `Renderer::select`. Layoutlib can't render either — previews must be 2D/HUD-only.+- Surface ids are Kotlin-owned ints; the engine routes config/pose/lifecycle per id. Dispose must call `surfaceDestroyed(id)`.++## Base mesh asset (`src/main/assets/models/base_upperbody.glb`)+- Handoff: `YuuAvatarAssets.adoptBundledMesh` (detached fd, `noCompress ".glb"`)+ → `nativeSetBundledMesh` → `Engine::set_bundled_mesh` → parsed on next+ surface creation. Absent asset keeps the procedural fallback.+- Authoring contract: ~13–15 joints named per `joint_name()` in `avatar.rs`+ (`root/spine/chest/neck/head`, `clavicle_L/R`, `upperArm_L/R`,+ `forearm_L/R`, `hand_L/R`); 4-weight skinning (`JOINTS_0`/`WEIGHTS_0`+ required); distinct `glasses` / `beard` / hair nodes for attachments; 2K+ albedo honoring the skin `[0,.25]` / shirt `[.5,1]` UV split from `mesh.rs`;+ ≤65536 verts (tighter cap for grid cells).++## Key files+### Kotlin — bridge + surface+- com/vayunmathur/library/avatar/YuuAvatarNative.kt+- com/vayunmathur/library/avatar/components/YuuAvatarSurfaceView.kt+- com/vayunmathur/library/avatar/components/YuuAvatar3D.kt+- com/vayunmathur/library/avatar/yuu/YuuPose.kt+### Rust — engine crate (see src/main/rust/AGENTS.md for the skeleton contract)+- src/main/rust/src/avatar.rs — joints, traits, poses, FK+- src/main/rust/src/engine.rs — per-surface lifecycle + camera+- src/main/rust/src/mesh.rs — procedural fallback + glTF loader+- src/main/rust/src/lib.rs — JNI entry points+- src/main/rust/src/vulkan/ + src/main/rust/src/gles/ — backends++## Verify (this module only)+```+./gradlew :library:avatar:compileDevKotlin+./gradlew :library:avatar:lint+```+Plus `cargo test -p yuu_avatar` in `src/main/rust/`.
library/avatar/build.gradle.kts
diff --git a/library/avatar/build.gradle.kts b/library/avatar/build.gradle.ktsnew file mode 100644index 0000000000..c0d9a01458--- /dev/null+++ b/library/avatar/build.gradle.kts@@ -0,0 +1,32 @@+plugins {+ id("common-conventions-library")+}++android {+ // Detached-fd asset handoff (YuuAvatarAssets): the .glb must stay stored+ // uncompressed so openFd() maps it. Same arrangement as :library:ml.+ aaptOptions {+ noCompress += ".glb"+ }+}++androidComponents {+ onVariants { variant ->+ variant.sources.jniLibs?.addStaticSourceDirectory(+ layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+ )+ }+}++dependencies {+ implementation(project(":library:ui"))+ implementation(libs.androidx.lifecycle.runtime.compose)+}++// Yuu 3D avatar engine: `library/avatar/src/main/rust`, glTF upper-body base+// mesh, skeletal skinning, preset poses, Vulkan-first + GLES fallback.+//+// Same arrangement as :library:map: the crate builds into rustJniLibs and+// YuuAvatarNative.isAvailable gates every call, so devices without the .so+// keep the 2D YuuFace preview. arm64 only (map precedent).+rustNativeLib("yuu_avatar", "avatar")
library/avatar/src/main/assets/models/README.md
diff --git a/library/avatar/src/main/assets/models/README.md b/library/avatar/src/main/assets/models/README.mdnew file mode 100644index 0000000000..0f3f52bff3--- /dev/null+++ b/library/avatar/src/main/assets/models/README.md@@ -0,0 +1,15 @@+# models/++Place the authored `base_upperbody.glb` here. Requirements (see `../../AGENTS.md`+"Base mesh asset"):++- ~13–15 joints named per `joint_name()` (`root/spine/chest/neck/head`,+ `clavicle_L/R`, `upperArm_L/R`, `forearm_L/R`, `hand_L/R`)+- `JOINTS_0` / `WEIGHTS_0` 4-weight skinning on the first mesh primitive+- Distinct `glasses` / `beard` / hair nodes for attachments+- 2K albedo honoring the skin `[0,.25]` / shirt `[.5,1]` UV split+- ≤65536 verts (tighter cap for grid cells)++The `.glb` ships uncompressed (`noCompress` in `build.gradle.kts`) and is+handed to native as a detached fd by `YuuAvatarAssets`. Until it lands, the+engine renders the procedural fallback mesh.
library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt
diff --git a/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.ktnew file mode 100644index 0000000000..02c7c7b7cd--- /dev/null+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarAssets.kt@@ -0,0 +1,41 @@+package com.vayunmathur.library.avatar++import android.content.res.AssetManager+import android.os.ParcelFileDescriptor+import com.vayunmathur.library.log.Log++/**+ * Loads `models/base_upperbody.glb` from this module's assets and hands the+ * detached fd to native (ClipHandle/MaiaHandle pattern in `:library:ml`).+ * Best-effort: absent asset keeps the procedural fallback mesh.+ */+object YuuAvatarAssets {+ /** Asset path of the rigged upper-body base mesh. */+ const val BASE_MESH_PATH = "models/base_upperbody.glb"++ /**+ * Adopt the bundled mesh, if present. Call once at startup (e.g. from+ * the first avatar surface) — the engine parses on next surface creation.+ */+ fun adoptBundledMesh(assets: AssetManager) {+ if (!YuuAvatarNative.isAvailable) return+ try {+ assets.openFd(BASE_MESH_PATH).use { afd ->+ val fd = afd.parcelFileDescriptor.detachFd()+ var handed = false+ try {+ YuuAvatarNative.setBundledMeshFd(fd, afd.startOffset, afd.length)+ handed = true+ } finally {+ if (!handed) closeFd(fd)+ }+ }+ } catch (e: Exception) {+ Log.status("YuuAvatarAssets", "no bundled mesh - procedural fallback (${e.message})")+ }+ }++ private fun closeFd(fd: Int) {+ runCatching { ParcelFileDescriptor.adoptFd(fd).close() }+ }+}
library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarNative.kt
diff --git a/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarNative.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarNative.ktnew file mode 100644index 0000000000..39edefebee--- /dev/null+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/YuuAvatarNative.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.avatar++import com.vayunmathur.library.log.Log++/**+ * The 3D avatar engine bridge, shaped like kart's `KartNative` and+ * `MapNative`.+ *+ * Native calls are no-ops behind [isAvailable] = false (no `libyuu_avatar`+ * on this device), and hero surfaces fall back to a 2D preview instead. The+ * signatures below are the contract the Rust engine implements.+ *+ * Surface lifecycle mirrors kart/voxels: each view owns a stable [surfaceId]+ * (Kotlin-owned, passed on every call), the engine spawns a 60 Hz render+ * thread per surface and ticks the avatar there. Traits + pose cross as JSON+ * strings; the pose gallery reads back the preset ids.+ */+internal 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 for a surface. `configJson` is the `YuuFaceConfig`+ * JSON; `poseJson` is a preset id (e.g. "wave") or `{"id": ...}`. No-op+ * without the library.+ */+ fun setConfig(surfaceId: Int, configJson: String, poseJson: String) {+ if (!isAvailable) return+ nativeSetConfig(surfaceId, configJson, poseJson)+ }++ /** Pose preset ids as JSON (`["idle","wave",...]`) for the gallery. */+ fun getPosesJson(): String = if (isAvailable) nativeGetPosesJson() else "[]"++ /**+ * Hand the bundled `base_upperbody.glb` to native via a detached APK fd+ * (ClipHandle pattern — avoids a multi-MB heap copy). The engine parses+ * it into the shared mesh on the next surface creation; absent asset+ * keeps the procedural fallback.+ */+ fun setBundledMeshFd(fd: Int, offset: Long, length: Long) {+ if (!isAvailable) return+ nativeSetBundledMesh(fd, offset, length)+ }++ /** Surface lifecycle, called by the avatar surface view. */+ fun surfaceCreated(surface: android.view.Surface, surfaceId: Int) {+ if (!isAvailable) return+ nativeSurfaceCreated(surface, surfaceId)+ }++ fun surfaceChanged(surfaceId: Int, width: Int, height: Int) {+ if (!isAvailable) return+ nativeSurfaceChanged(surfaceId, width, height)+ }++ fun surfaceDestroyed(surfaceId: Int) {+ if (!isAvailable) return+ nativeSurfaceDestroyed(surfaceId)+ }++ fun setPaused(surfaceId: Int, paused: Boolean) {+ if (!isAvailable) return+ nativeSetPaused(surfaceId, paused)+ }++ fun onDestroy() {+ if (!isAvailable) return+ nativeOnDestroy()+ }++ private external fun nativeInit(): Boolean+ private external fun nativeSetConfig(surfaceId: Int, configJson: String, poseJson: String)+ private external fun nativeGetPosesJson(): String+ private external fun nativeSetBundledMesh(fd: Int, offset: Long, length: Long)+ private external fun nativeSurfaceCreated(surface: android.view.Surface, surfaceId: Int)+ private external fun nativeSurfaceChanged(surfaceId: Int, width: Int, height: Int)+ private external fun nativeSurfaceDestroyed(surfaceId: Int)+ private external fun nativeSetPaused(surfaceId: Int, paused: Boolean)+ private external fun nativeOnDestroy()+}
library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatar3D.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatar3D.ktsimilarity index 55%rename from games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.ktrename to library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatar3D.ktindex 74778bb9ec..9b15164bbf 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatar3D.kt+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatar3D.kt@@ -1,77 +1,75 @@-package com.vayunmathur.games.hub.ui.components+package com.vayunmathur.library.avatar.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 com.vayunmathur.library.avatar.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.+ * layered in a [Box]. Traits + pose cross as pre-encoded JSON; config updates+ * debounce so editor typing 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.+ * The caller supplies [configJson] (the `YuuFaceConfig` JSON) and an optional+ * [fallback] 2D preview shown when native is unavailable (no+ * `libyuu_avatar`) and layered underneath the surface (so a failed renderer+ * never shows a black hole). *- * 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).+ * Each instance carries a stable [surfaceId] for the multi-renderer engine;+ * dispose destroys that surface only. */ @Composable fun YuuAvatar3D(- config: YuuFaceConfig,+ configJson: String, poseId: String?,+ surfaceId: Int, modifier: Modifier = Modifier,- withFallback: Boolean = true,+ fallback: (@Composable () -> Unit)? = null, ) { if (!YuuAvatarNative.isAvailable) {- if (withFallback) {- YuuFace(config = config, withBody = true, modifier = modifier)- }+ fallback?.invoke() return }- val configJson = remember(config) { config.encode() } val pose = poseId ?: "idle" val lifecycle = LocalLifecycleOwner.current.lifecycle - DisposableEffect(lifecycle) {+ DisposableEffect(lifecycle, surfaceId) { val observer = LifecycleEventObserver { _, event -> when (event) {- Lifecycle.Event.ON_PAUSE -> YuuAvatarNative.setPaused(true)- Lifecycle.Event.ON_RESUME -> YuuAvatarNative.setPaused(false)+ Lifecycle.Event.ON_PAUSE -> YuuAvatarNative.setPaused(surfaceId, true)+ Lifecycle.Event.ON_RESUME -> YuuAvatarNative.setPaused(surfaceId, false) else -> Unit } } lifecycle.addObserver(observer) onDispose { lifecycle.removeObserver(observer)- YuuAvatarNative.surfaceDestroyed()+ YuuAvatarNative.surfaceDestroyed(surfaceId) } } // Debounced config push: rapid draft edits coalesce into one JNI call.- LaunchedEffect(configJson, pose) {+ LaunchedEffect(configJson, pose, surfaceId) { delay(200)- YuuAvatarNative.setConfig(configJson, pose)+ YuuAvatarNative.setConfig(surfaceId, 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())+ fallback?.let { fb ->+ Box(Modifier.fillMaxSize()) { fb() }+ } AndroidView(- factory = { ctx -> YuuAvatarSurfaceView(ctx) },+ factory = { ctx -> YuuAvatarSurfaceView(ctx, surfaceId = surfaceId) }, modifier = Modifier.fillMaxSize(), ) }
library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceView.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceView.ktsimilarity index 80%rename from games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.ktrename to library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceView.ktindex 5058143330..97b09d7586 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/YuuAvatarSurfaceView.kt+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/components/YuuAvatarSurfaceView.kt@@ -1,10 +1,10 @@-package com.vayunmathur.games.hub.ui.components+package com.vayunmathur.library.avatar.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.avatar.YuuAvatarNative import com.vayunmathur.library.log.Log /**@@ -14,10 +14,14 @@ import com.vayunmathur.library.log.Log * 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.+ *+ * Each view carries a stable [surfaceId] (owned by the Compose caller) so+ * the multi-renderer engine can route config/pose/lifecycle per surface. */ class YuuAvatarSurfaceView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null,+ val surfaceId: Int = 0, ) : SurfaceView(context, attrs), SurfaceHolder.Callback { private var ready = false @@ -31,7 +35,7 @@ class YuuAvatarSurfaceView @JvmOverloads constructor( if (!YuuAvatarNative.isAvailable) return // JNI boundary: native throws unchecked exceptions, all logged here. try {- YuuAvatarNative.surfaceCreated(holder.surface)+ YuuAvatarNative.surfaceCreated(holder.surface, surfaceId) ready = true } catch (e: RuntimeException) { Log.error("YuuAvatarSurface", "surfaceCreated failed", e)@@ -42,7 +46,7 @@ class YuuAvatarSurfaceView @JvmOverloads constructor( override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { if (!YuuAvatarNative.isAvailable || !ready) return try {- YuuAvatarNative.surfaceChanged(width, height)+ YuuAvatarNative.surfaceChanged(surfaceId, width, height) } catch (e: RuntimeException) { Log.error("YuuAvatarSurface", "surfaceChanged failed", e) }@@ -52,7 +56,7 @@ class YuuAvatarSurfaceView @JvmOverloads constructor( override fun surfaceDestroyed(holder: SurfaceHolder) { if (!YuuAvatarNative.isAvailable) return try {- YuuAvatarNative.surfaceDestroyed()+ YuuAvatarNative.surfaceDestroyed(surfaceId) ready = false } catch (e: RuntimeException) { Log.error("YuuAvatarSurface", "surfaceDestroyed failed", e)
library/avatar/src/main/java/com/vayunmathur/library/avatar/yuu/YuuPose.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.kt b/library/avatar/src/main/java/com/vayunmathur/library/avatar/yuu/YuuPose.ktsimilarity index 94%rename from games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.ktrename to library/avatar/src/main/java/com/vayunmathur/library/avatar/yuu/YuuPose.ktindex b3c63be78e..52fe05d948 100644--- a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/yuu/YuuPose.kt+++ b/library/avatar/src/main/java/com/vayunmathur/library/avatar/yuu/YuuPose.kt@@ -1,4 +1,4 @@-package com.vayunmathur.games.hub.ui.yuu+package com.vayunmathur.library.avatar.yuu import kotlinx.serialization.Serializable
library/avatar/src/main/rust/AGENTS.md
diff --git a/games/hub/src/main/rust/AGENTS.md b/library/avatar/src/main/rust/AGENTS.mdsimilarity index 100%rename from games/hub/src/main/rust/AGENTS.mdrename to library/avatar/src/main/rust/AGENTS.md
library/avatar/src/main/rust/Cargo.toml
diff --git a/games/hub/src/main/rust/Cargo.toml b/library/avatar/src/main/rust/Cargo.tomlsimilarity index 100%rename from games/hub/src/main/rust/Cargo.tomlrename to library/avatar/src/main/rust/Cargo.toml
library/avatar/src/main/rust/build.rs
diff --git a/games/hub/src/main/rust/build.rs b/library/avatar/src/main/rust/build.rssimilarity index 100%rename from games/hub/src/main/rust/build.rsrename to library/avatar/src/main/rust/build.rs
library/avatar/src/main/rust/shaders/yuu_avatar.frag
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.frag b/library/avatar/src/main/rust/shaders/yuu_avatar.fragsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar.fragrename to library/avatar/src/main/rust/shaders/yuu_avatar.frag
library/avatar/src/main/rust/shaders/yuu_avatar.frag.spv
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.frag.spv b/library/avatar/src/main/rust/shaders/yuu_avatar.frag.spvsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar.frag.spvrename to library/avatar/src/main/rust/shaders/yuu_avatar.frag.spv
library/avatar/src/main/rust/shaders/yuu_avatar.vert
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.vert b/library/avatar/src/main/rust/shaders/yuu_avatar.vertsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar.vertrename to library/avatar/src/main/rust/shaders/yuu_avatar.vert
library/avatar/src/main/rust/shaders/yuu_avatar.vert.spv
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar.vert.spv b/library/avatar/src/main/rust/shaders/yuu_avatar.vert.spvsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar.vert.spvrename to library/avatar/src/main/rust/shaders/yuu_avatar.vert.spv
library/avatar/src/main/rust/shaders/yuu_avatar_gles.frag
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar_gles.frag b/library/avatar/src/main/rust/shaders/yuu_avatar_gles.fragsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar_gles.fragrename to library/avatar/src/main/rust/shaders/yuu_avatar_gles.frag
library/avatar/src/main/rust/shaders/yuu_avatar_gles.vert
diff --git a/games/hub/src/main/rust/shaders/yuu_avatar_gles.vert b/library/avatar/src/main/rust/shaders/yuu_avatar_gles.vertsimilarity index 100%rename from games/hub/src/main/rust/shaders/yuu_avatar_gles.vertrename to library/avatar/src/main/rust/shaders/yuu_avatar_gles.vert
library/avatar/src/main/rust/src/avatar.rs
diff --git a/games/hub/src/main/rust/src/avatar.rs b/library/avatar/src/main/rust/src/avatar.rssimilarity index 100%rename from games/hub/src/main/rust/src/avatar.rsrename to library/avatar/src/main/rust/src/avatar.rs
library/avatar/src/main/rust/src/engine.rs
diff --git a/library/avatar/src/main/rust/src/engine.rs b/library/avatar/src/main/rust/src/engine.rsnew file mode 100644index 0000000000..3d041522a4--- /dev/null+++ b/library/avatar/src/main/rust/src/engine.rs@@ -0,0 +1,391 @@+//! Avatar engine: per-surface lifecycle, preview camera, per-frame bone upload.+//!+//! The engine owns a map of live surfaces (`surfaceId -> SurfaceState`), each+//! with its own renderer, render thread generation, traits + pose, and size.+//! The CPU mesh bytes are shared across surfaces (single `Arc` allocation);+//! GPU buffers + UBO/pose stay per-surface. The render threads tick here;+//! [`tick_surface`] uploads the bone-matrix UBO and draws one surface per call.++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::collections::HashMap;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::Instant;++/// Per-surface state: one renderer + thread + config behind one surface id.+pub struct SurfaceState {+ /// 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,+ /// 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,+ /// Render-thread generation: bumped on recreate so a stale thread+ /// (rotation) exits instead of racing the new one.+ pub generation: u64,+}++impl SurfaceState {+ /// Fresh surface with the idle pose.+ fn new(width: u32, height: u32) -> 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_count: 0,+ width: width.max(1),+ height: height.max(1),+ paused: false,+ generation: 0,+ }+ }+}++/// Engine state behind the global lock: the surface map plus shared assets.+pub struct Engine {+ /// Live surfaces by Kotlin-owned surface id.+ pub surfaces: HashMap<i32, SurfaceState>,+ /// Shared CPU mesh bytes (procedural fallback or parsed glb), uploaded+ /// per-surface to GPU. Single allocation across all surfaces.+ pub mesh: Arc<Vec<YuuVertex>>,+ /// Bundled glb bytes, when the APK ships `base_upperbody.glb`.+ pub bundled_mesh: Option<Vec<u8>>,+}++impl Engine {+ /// Fresh engine with the procedural fallback mesh.+ pub fn new() -> Self {+ Self {+ surfaces: HashMap::new(),+ mesh: Arc::new(build_avatar_mesh()),+ bundled_mesh: None,+ }+ }++ /// Get or create the state for a surface.+ fn surface_mut(&mut self, surface_id: i32, width: u32, height: u32) -> &mut SurfaceState {+ self.surfaces+ .entry(surface_id)+ .or_insert_with(|| SurfaceState::new(width, height))+ }+}++impl Default for Engine {+ fn default() -> Self {+ Self::new()+ }+}++// SAFETY: guarded by the mutex; each renderer (Vulkan/GLES handles) is only+// touched on its own surface's 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 a surface's traits from `YuuFaceConfig` JSON.+pub fn set_traits_json(surface_id: i32, json: &str) {+ if let Ok(mut eng) = engine().lock() {+ eng.surface_mut(surface_id, 512, 512).traits = YuuTraits::from_config_json(json);+ }+}++/// Replace a surface's pose by preset id (unknown ids keep the old pose).+pub fn set_pose_id(surface_id: i32, pose_id: &str) {+ if let Some(preset) = preset_by_id(pose_id) {+ if let Ok(mut eng) = engine().lock() {+ eng.surface_mut(surface_id, 512, 512).pose = preset;+ }+ }+}++/// Set both traits and pose from JSON in one call (surface creation path).+pub fn set_config(surface_id: i32, config_json: &str, pose_json: &str) {+ set_traits_json(surface_id, 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(surface_id, &id);+ }+}++/// Provide bundled glb bytes (from APK assets via JNI); the next surface+/// creation parses them into the shared mesh.+pub fn set_bundled_mesh(bytes: Vec<u8>) {+ if let Ok(mut eng) = engine().lock() {+ eng.bundled_mesh = Some(bytes);+ }+}++/// Pause or resume drawing on a surface (keeps the renderer alive).+pub fn set_paused(surface_id: i32, paused: bool) {+ if let Ok(mut eng) = engine().lock() {+ if let Some(state) = eng.surfaces.get_mut(&surface_id) {+ state.paused = paused;+ }+ }+}++/// Whether a surface's renderer is currently live.+pub fn has_renderer(surface_id: i32) -> bool {+ engine()+ .lock()+ .map(|e| e.surfaces.get(&surface_id).is_some_and(|s| s.renderer.is_some()))+ .unwrap_or(false)+}++/// Whether a surface's render thread should keep running.+pub fn is_running(surface_id: i32) -> bool {+ has_renderer(surface_id)+}++/// 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` on a surface and upload the shared 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(+ surface_id: i32,+ window: *mut crate::vulkan::context::ANativeWindow,+ width: i32,+ height: i32,+) -> bool {+ // Parse outside the lock: glTF parsing allocates and must not stall tick+ // threads waiting on the engine mutex.+ let bundled: Option<Vec<u8>> = engine().lock().ok().and_then(|e| e.bundled_mesh.clone());+ if let Some(bytes) = bundled {+ let parsed = load_gltf_mesh(&bytes);+ if let Ok(mut eng) = engine().lock() {+ eng.mesh = Arc::new(parsed);+ }+ }+ let mesh: Arc<Vec<YuuVertex>> = engine()+ .lock()+ .map(|e| Arc::clone(&e.mesh))+ .unwrap_or_else(|_| Arc::new(build_avatar_mesh()));+ let w = width.max(1) as u32;+ let h = height.max(1) as u32;+ if let Ok(mut eng) = engine().lock() {+ let state = eng.surface_mut(surface_id, w, h);+ state.width = w;+ state.height = h;+ state.paused = false;+ }+ let renderer = match unsafe { Renderer::select(window, width, height, w, h) } {+ Ok(r) => r,+ Err(_) => return false,+ };+ if let Ok(mut eng) = engine().lock() {+ if let Some(state) = eng.surfaces.get_mut(&surface_id) {+ state.renderer = Some(renderer);+ state.mesh_count = mesh.len();+ }+ }+ // Upload on the render thread with the backend's context current.+ upload_mesh(surface_id, &mesh)+}++/// Upload the shared mesh to one surface's renderer.+pub fn upload_mesh(surface_id: i32, mesh: &[YuuVertex]) -> bool {+ let mut eng = match engine().lock() {+ Ok(e) => e,+ Err(_) => return false,+ };+ if let Some(state) = eng.surfaces.get_mut(&surface_id) {+ if let Some(renderer) = state.renderer.as_mut() {+ unsafe { renderer.upload_avatar(mesh) };+ state.mesh_count = mesh.len();+ true+ } else {+ false+ }+ } else {+ false+ }+}++/// Resize one surface's swapchain.+pub fn resize_renderer(surface_id: i32, 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;+ if let Some(state) = eng.surfaces.get_mut(&surface_id) {+ state.width = w;+ state.height = h;+ if let Some(renderer) = state.renderer.as_mut() {+ unsafe { renderer.resize(w, h) };+ }+ }+ }+}++/// One tick for one surface: compute bones, upload the UBO, draw.+pub fn tick_surface(surface_id: i32) {+ let (view_proj, cam_pos, bones, skin_rgb, count, paused) = {+ let eng = match engine().lock() {+ Ok(e) => e,+ Err(_) => return,+ };+ let Some(state) = eng.surfaces.get(&surface_id) else {+ return;+ };+ if state.renderer.is_none() || state.paused {+ return;+ }+ let t = state.started.elapsed().as_secs_f32();+ let (vp, cp) = view_proj_for(state.width, state.height, t);+ let bones = compute_bone_matrices(&state.traits, &state.pose, t);+ let skin = state.traits.skin_rgb();+ (vp, cp, bones, skin, state.mesh_count, state.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(state) = eng.surfaces.get_mut(&surface_id) {+ if let Some(renderer) = state.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 one surface's renderer, stop its thread. Traits/pose survive in+/// the state until the surface entry is removed.+pub fn destroy_renderer(surface_id: i32) {+ if let Ok(mut eng) = engine().lock() {+ if let Some(state) = eng.surfaces.get_mut(&surface_id) {+ if let Some(mut renderer) = state.renderer.take() {+ unsafe { renderer.destroy() };+ }+ state.mesh_count = 0;+ }+ }+}++/// Remove a surface entry entirely (after its thread has exited).+pub fn remove_surface(surface_id: i32) {+ if let Ok(mut eng) = engine().lock() {+ eng.surfaces.remove(&surface_id);+ }+}++/// Bump a surface's render-thread generation (rotation path) and return it.+pub fn next_generation(surface_id: i32) -> u64 {+ if let Ok(mut eng) = engine().lock() {+ let state = eng.surface_mut(surface_id, 512, 512);+ state.generation = state.generation.wrapping_add(1);+ state.generation+ } else {+ 0+ }+}++/// A surface's current render-thread generation.+pub fn generation(surface_id: i32) -> u64 {+ engine()+ .lock()+ .map(|e| e.surfaces.get(&surface_id).map(|s| s.generation).unwrap_or(0))+ .unwrap_or(0)+}++/// Destroy everything.+pub fn destroy_engine() {+ if let Ok(mut eng) = engine().lock() {+ for (_, state) in eng.surfaces.iter_mut() {+ if let Some(mut renderer) = state.renderer.take() {+ unsafe { renderer.destroy() };+ }+ state.mesh_count = 0;+ }+ eng.surfaces.clear();+ }+}
library/avatar/src/main/rust/src/gles/buffers.rs
diff --git a/games/hub/src/main/rust/src/gles/buffers.rs b/library/avatar/src/main/rust/src/gles/buffers.rssimilarity index 100%rename from games/hub/src/main/rust/src/gles/buffers.rsrename to library/avatar/src/main/rust/src/gles/buffers.rs
library/avatar/src/main/rust/src/gles/egl.rs
diff --git a/games/hub/src/main/rust/src/gles/egl.rs b/library/avatar/src/main/rust/src/gles/egl.rssimilarity index 100%rename from games/hub/src/main/rust/src/gles/egl.rsrename to library/avatar/src/main/rust/src/gles/egl.rs
library/avatar/src/main/rust/src/gles/mod.rs
diff --git a/games/hub/src/main/rust/src/gles/mod.rs b/library/avatar/src/main/rust/src/gles/mod.rssimilarity index 100%rename from games/hub/src/main/rust/src/gles/mod.rsrename to library/avatar/src/main/rust/src/gles/mod.rs
library/avatar/src/main/rust/src/gles/renderer.rs
diff --git a/games/hub/src/main/rust/src/gles/renderer.rs b/library/avatar/src/main/rust/src/gles/renderer.rssimilarity index 100%rename from games/hub/src/main/rust/src/gles/renderer.rsrename to library/avatar/src/main/rust/src/gles/renderer.rs
library/avatar/src/main/rust/src/gles/shaders.rs
diff --git a/games/hub/src/main/rust/src/gles/shaders.rs b/library/avatar/src/main/rust/src/gles/shaders.rssimilarity index 100%rename from games/hub/src/main/rust/src/gles/shaders.rsrename to library/avatar/src/main/rust/src/gles/shaders.rs
library/avatar/src/main/rust/src/lib.rs
diff --git a/library/avatar/src/main/rust/src/lib.rs b/library/avatar/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..3437a6ce6d--- /dev/null+++ b/library/avatar/src/main/rust/src/lib.rs@@ -0,0 +1,260 @@+//! 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, jlong, 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_library_avatar_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) for a+/// surface. Phase A compat: the id is stored as `currentSurfaceId` and the+/// single renderer keeps drawing (multi-surface routing lands in Phase B).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_YuuAvatarNative_nativeSetConfig<'l>(+ mut env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface_id: jint,+ 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(surface_id, &config, &pose);+}++/// Surface ready: adopt the window, build this surface's renderer, start its+/// 60 Hz render thread. A second call with the same id (rotation) destroys+/// that surface's old renderer first and bumps its thread generation so the+/// stale thread exits instead of racing the new one. Other surfaces are+/// untouched.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_YuuAvatarNative_nativeSurfaceCreated<'l>(+ env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface: JObject<'l>,+ surface_id: jint,+) {+ 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 this surface's previous renderer before+ // adopting the new window, so at most one thread runs per surface.+ engine::destroy_renderer(surface_id);+ let generation = engine::next_generation(surface_id);+ if !unsafe { engine::create_renderer(surface_id, 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(surface_id) || engine::generation(surface_id) != generation {+ break;+ }+ engine::tick_surface(surface_id);+ 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(surface_id) || engine::generation(surface_id) != generation {+ break;+ }+ }+ engine::remove_surface(surface_id);+ });+ }+ #[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_library_avatar_YuuAvatarNative_nativeSurfaceChanged<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface_id: jint,+ width: jint,+ height: jint,+) {+ engine::resize_renderer(surface_id, width, height);+}++/// Surface gone: destroy that surface's renderer, stop its thread.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_YuuAvatarNative_nativeSurfaceDestroyed<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface_id: jint,+) {+ engine::destroy_renderer(surface_id);+}++/// Pause or resume drawing (keeps the renderer alive).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_YuuAvatarNative_nativeSetPaused<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ surface_id: jint,+ paused: jboolean,+) {+ engine::set_paused(surface_id, paused != jni::sys::JNI_FALSE);+}++/// Bundled mesh handoff: read `length` bytes at `offset` from the detached+/// APK fd and store them for the next surface creation. The fd is adopted+/// (owned) here — always closed exactly once, on every path.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_YuuAvatarNative_nativeSetBundledMesh<'l>(+ _env: EnvUnowned<'l>,+ _class: JClass<'l>,+ fd: jint,+ offset: jlong,+ length: jlong,+) {+ let bytes = read_fd(fd, offset, length);+ // Adopt-then-close: the fd is ours now regardless of read outcome.+ close_fd(fd);+ if let Some(bytes) = bytes {+ if !bytes.is_empty() {+ engine::set_bundled_mesh(bytes);+ }+ }+}++#[cfg(target_os = "android")]+fn read_fd(fd: jint, offset: jlong, length: jlong) -> Option<Vec<u8>> {+ use std::os::unix::io::FromRawFd;+ if fd < 0 || length <= 0 || length > 64 * 1024 * 1024 {+ return None;+ }+ // Borrow (don't own): close_fd below owns the single close.+ let mut file = unsafe { std::mem::ManuallyDrop::new(std::fs::File::from_raw_fd(fd)) };+ use std::io::{Read, Seek, SeekFrom};+ file.seek(SeekFrom::Start(offset.max(0) as u64)).ok()?;+ let mut buf = vec![0u8; length as usize];+ file.read_exact(&mut buf).ok()?;+ Some(buf)+}++#[cfg(not(target_os = "android"))]+fn read_fd(_fd: jint, _offset: jlong, _length: jlong) -> Option<Vec<u8>> {+ None+}++#[cfg(target_os = "android")]+fn close_fd(fd: jint) {+ if fd >= 0 {+ unsafe {+ extern "C" {+ fn close(fd: i32) -> i32;+ }+ close(fd);+ }+ }+}++#[cfg(not(target_os = "android"))]+fn close_fd(_fd: jint) {}++/// Pose preset ids as JSON (`["idle","wave",...]`) for the gallery.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_library_avatar_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_library_avatar_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"));+ }++ #[test]+ fn surfaces_are_independent() {+ let json_a = r#"{"body_height": 0.2, "face_shape": 1}"#;+ let json_b = r#"{"body_height": 0.9, "face_shape": 5}"#;+ crate::engine::set_config(11, json_a, "wave");+ crate::engine::set_config(22, json_b, "cheering");+ // Per-surface pause must not leak across surfaces.+ crate::engine::set_paused(11, true);+ assert!(crate::engine::has_renderer(11) == crate::engine::has_renderer(22));+ crate::engine::destroy_renderer(11);+ crate::engine::remove_surface(11);+ crate::engine::remove_surface(22);+ }+}+
library/avatar/src/main/rust/src/mesh.rs
diff --git a/games/hub/src/main/rust/src/mesh.rs b/library/avatar/src/main/rust/src/mesh.rssimilarity index 100%rename from games/hub/src/main/rust/src/mesh.rsrename to library/avatar/src/main/rust/src/mesh.rs
library/avatar/src/main/rust/src/renderer.rs
diff --git a/games/hub/src/main/rust/src/renderer.rs b/library/avatar/src/main/rust/src/renderer.rssimilarity index 100%rename from games/hub/src/main/rust/src/renderer.rsrename to library/avatar/src/main/rust/src/renderer.rs
library/avatar/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/hub/src/main/rust/src/vulkan/buffers.rs b/library/avatar/src/main/rust/src/vulkan/buffers.rssimilarity index 100%rename from games/hub/src/main/rust/src/vulkan/buffers.rsrename to library/avatar/src/main/rust/src/vulkan/buffers.rs
library/avatar/src/main/rust/src/vulkan/context.rs
diff --git a/games/hub/src/main/rust/src/vulkan/context.rs b/library/avatar/src/main/rust/src/vulkan/context.rssimilarity index 100%rename from games/hub/src/main/rust/src/vulkan/context.rsrename to library/avatar/src/main/rust/src/vulkan/context.rs
library/avatar/src/main/rust/src/vulkan/mod.rs
diff --git a/games/hub/src/main/rust/src/vulkan/mod.rs b/library/avatar/src/main/rust/src/vulkan/mod.rssimilarity index 100%rename from games/hub/src/main/rust/src/vulkan/mod.rsrename to library/avatar/src/main/rust/src/vulkan/mod.rs
library/avatar/src/main/rust/src/vulkan/pipeline.rs
diff --git a/games/hub/src/main/rust/src/vulkan/pipeline.rs b/library/avatar/src/main/rust/src/vulkan/pipeline.rssimilarity index 100%rename from games/hub/src/main/rust/src/vulkan/pipeline.rsrename to library/avatar/src/main/rust/src/vulkan/pipeline.rs
library/avatar/src/main/rust/src/vulkan/renderer.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/renderer.rs b/library/avatar/src/main/rust/src/vulkan/renderer.rsnew file mode 100644index 0000000000..6d34fa2ea9--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/renderer.rs@@ -0,0 +1,436 @@+//! Frame renderer: command pool, per-frame fence, bone UBO + avatar mesh+//! upload, albedo texture, draw.+//!+//! One in-flight frame at a time (the render thread ticks at 60 Hz and waits+//! on the fence before re-recording, so no frame ever overtakes another).+//! The avatar mesh uploads once per surface; the bone UBO re-uploads every+//! frame from the engine's pose. View-projection comes from the preview+//! camera with the surface pre-rotation prepended.+use crate::avatar::MAX_BONES;+use crate::vulkan::buffers::{AllocatedBuffer, YuuUbo, YuuVkVertex};+use crate::vulkan::context::VulkanContext;+use crate::vulkan::pipeline::Pipelines;+use crate::vulkan::swapchain::Swapchain;+use ash::vk;+use std::mem;++/// Static avatar mesh budget: the procedural fallback is ~1k verts; 64k+/// leaves margin for a detailed glTF base mesh.+const AVATAR_VERT_CAP: usize = 65_536;++/// Everything needed to draw one frame.+pub struct YuuRenderer {+ /// Vulkan context (owns instance/device/surface).+ pub ctx: VulkanContext,+ /// Swapchain + depth + render pass + framebuffers.+ pub swap: Swapchain,+ /// Graphics pipeline + UBO/sampler descriptor set.+ pub pipes: Pipelines,+ /// Static avatar vertex buffer (uploaded per surface).+ pub avatar_buf: AllocatedBuffer,+ /// Uniform buffer (view-projection + sun + camera + bones).+ pub ubo_buf: AllocatedBuffer,+ /// Albedo texture image (1x1 skin default, updated from traits).+ pub albedo_image: vk::Image,+ /// Albedo memory.+ pub albedo_memory: vk::DeviceMemory,+ /// Albedo view.+ pub albedo_view: vk::ImageView,+ /// Albedo sampler.+ pub albedo_sampler: vk::Sampler,+ /// Command pool (graphics family).+ pub pool: vk::CommandPool,+ /// One reusable command buffer.+ pub cmd: vk::CommandBuffer,+ /// Frame fence (signalled when the GPU finishes the frame).+ pub fence: vk::Fence,+ /// Image-acquired + render-finished semaphores.+ pub sem_acquire: vk::Semaphore,+ /// Image-acquired + render-finished semaphores.+ pub sem_render: vk::Semaphore,+ /// Current surface width.+ pub width: u32,+ /// Current surface height.+ pub height: u32,+}++impl YuuRenderer {+ /// Create from a live window at `width` x `height`. Fails cleanly.+ ///+ /// Follows the `KartRenderer::new` sequence verbatim (context → swapchain+ /// → UBO → pipeline → vertex buffer → pool/cmd/fence/semaphores), plus+ /// the 1x1 albedo default bound to the sampler slot.+ ///+ /// # Safety+ /// `window` must be a live adopted `ANativeWindow`; ownership stays with+ /// the engine (released on destroy), as on the kart path.+ pub unsafe fn new(+ window: *mut crate::vulkan::context::ANativeWindow,+ width: i32,+ height: i32,+ state_width: u32,+ state_height: u32,+ ) -> Result<Self, String> {+ // Prefer the engine's tracked size; fall back to the window size,+ // then to a sane default (lib.rs passes 1280x720 until the first+ // surfaceChanged arrives).+ let want_w = state_width.max(width.max(1) as u32).max(1);+ let want_h = state_height.max(height.max(1) as u32).max(1);+ let ctx = unsafe { VulkanContext::new(window, want_w as i32, want_h as i32) }+ .map_err(|e| format!("ctx {e:?}"))?;+ let swap = Swapchain::new(&ctx, want_w, want_h)?;+ let ubo_size = mem::size_of::<YuuUbo>() as u64;+ let ubo_buf = AllocatedBuffer::new(+ &ctx.instance,+ &ctx.device,+ ctx.physical_device,+ ubo_size,+ vk::BufferUsageFlags::UNIFORM_BUFFER,+ )?;+ let pipes = Pipelines::new(&ctx.device, swap.render_pass, ubo_buf.buffer, ubo_size)?;+ let vert_size = (mem::size_of::<YuuVkVertex>() * AVATAR_VERT_CAP) as u64;+ let avatar_buf = AllocatedBuffer::new(+ &ctx.instance,+ &ctx.device,+ ctx.physical_device,+ vert_size,+ vk::BufferUsageFlags::VERTEX_BUFFER,+ )?;+ let (albedo_image, albedo_memory, albedo_view, albedo_sampler) =+ unsafe { Self::create_albedo(&ctx, [0xE8, 0xB4, 0x8A, 0xFF]) }?;+ pipes.bind_albedo(&ctx.device, albedo_sampler, albedo_view);+ let pool_info = vk::CommandPoolCreateInfo::default()+ .queue_family_index(ctx.queue_family_index)+ .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER);+ let pool = ctx.device.create_command_pool(&pool_info, None).map_err(|e| format!("pool {e:?}"))?;+ let alloc_info = vk::CommandBufferAllocateInfo::default()+ .command_pool(pool)+ .level(vk::CommandBufferLevel::PRIMARY)+ .command_buffer_count(1);+ let cmd = ctx+ .device+ .allocate_command_buffers(&alloc_info)+ .map_err(|e| format!("cmd {e:?}"))?[0];+ let fence = ctx+ .device+ .create_fence(&vk::FenceCreateInfo::default().flags(vk::FenceCreateFlags::SIGNALED), None)+ .map_err(|e| format!("fence {e:?}"))?;+ let sem_acquire = ctx.device.create_semaphore(&vk::SemaphoreCreateInfo::default(), None).map_err(|e| format!("sem {e:?}"))?;+ let sem_render = ctx.device.create_semaphore(&vk::SemaphoreCreateInfo::default(), None).map_err(|e| format!("sem {e:?}"))?;+ let width = swap.extent.width;+ let height = swap.extent.height;+ Ok(Self {+ ctx,+ swap,+ pipes,+ avatar_buf,+ ubo_buf,+ albedo_image,+ albedo_memory,+ albedo_view,+ albedo_sampler,+ pool,+ cmd,+ fence,+ sem_acquire,+ sem_render,+ width,+ height,+ })+ }++ /// Create the 1x1 albedo default (linear RGBA8) + view + sampler, already+ /// in `SHADER_READ_ONLY_OPTIMAL` for the frag sampler slot.+ unsafe fn create_albedo(+ ctx: &VulkanContext,+ rgba: [u8; 4],+ ) -> Result<(vk::Image, vk::DeviceMemory, vk::ImageView, vk::Sampler), String> {+ let device = &ctx.device;+ let img_info = vk::ImageCreateInfo::default()+ .image_type(vk::ImageType::TYPE_2D)+ .format(vk::Format::R8G8B8A8_UNORM)+ .extent(vk::Extent3D { width: 1, height: 1, depth: 1 })+ .mip_levels(1)+ .array_layers(1)+ .samples(vk::SampleCountFlags::TYPE_1)+ .tiling(vk::ImageTiling::LINEAR)+ .usage(vk::ImageUsageFlags::SAMPLED)+ .sharing_mode(vk::SharingMode::EXCLUSIVE)+ .initial_layout(vk::ImageLayout::PREINITIALIZED);+ let image = device.create_image(&img_info, None).map_err(|e| format!("albedo img {e:?}"))?;+ let mem_reqs = device.get_image_memory_requirements(image);+ let mem_props = ctx.instance.get_physical_device_memory_properties(ctx.physical_device);+ let wanted = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;+ let mem_type = (0..mem_props.memory_type_count)+ .find(|&i| {+ (mem_reqs.memory_type_bits & (1 << i)) != 0+ && mem_props.memory_types[i as usize].property_flags.contains(wanted)+ })+ .ok_or_else(|| "albedo: no mem type".to_string())?;+ let memory = device+ .allocate_memory(+ &vk::MemoryAllocateInfo::default()+ .allocation_size(mem_reqs.size)+ .memory_type_index(mem_type),+ None,+ )+ .map_err(|e| format!("albedo alloc {e:?}"))?;+ device.bind_image_memory(image, memory, 0).map_err(|e| format!("albedo bind {e:?}"))?;+ // Write the single texel through the mapped linear image.+ let ptr = device+ .map_memory(memory, 0, 4, vk::MemoryMapFlags::empty())+ .map_err(|e| format!("albedo map {e:?}"))? as *mut u8;+ ptr.copy_from_nonoverlapping(rgba.as_ptr(), 4);+ device.unmap_memory(memory);+ // Transition to SHADER_READ_ONLY_OPTIMAL via a one-shot barrier.+ let pool_info = vk::CommandPoolCreateInfo::default()+ .queue_family_index(ctx.queue_family_index)+ .flags(vk::CommandPoolCreateFlags::TRANSIENT);+ let pool = device.create_command_pool(&pool_info, None).map_err(|e| format!("albedo pool {e:?}"))?;+ let cmd = device+ .allocate_command_buffers(+ &vk::CommandBufferAllocateInfo::default()+ .command_pool(pool)+ .level(vk::CommandBufferLevel::PRIMARY)+ .command_buffer_count(1),+ )+ .map_err(|e| format!("albedo cmd {e:?}"))?[0];+ device+ .begin_command_buffer(cmd, &vk::CommandBufferBeginInfo::default().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT))+ .map_err(|e| format!("albedo begin {e:?}"))?;+ let barrier = vk::ImageMemoryBarrier::default()+ .old_layout(vk::ImageLayout::PREINITIALIZED)+ .new_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL)+ .src_access_mask(vk::AccessFlags::HOST_WRITE)+ .dst_access_mask(vk::AccessFlags::SHADER_READ)+ .image(image)+ .subresource_range(vk::ImageSubresourceRange {+ aspect_mask: vk::ImageAspectFlags::COLOR,+ base_mip_level: 0,+ level_count: 1,+ base_array_layer: 0,+ layer_count: 1,+ });+ device.cmd_pipeline_barrier(+ cmd,+ vk::PipelineStageFlags::HOST,+ vk::PipelineStageFlags::FRAGMENT_SHADER,+ vk::DependencyFlags::empty(),+ &[],+ &[],+ std::slice::from_ref(&barrier),+ );+ device.end_command_buffer(cmd).map_err(|e| format!("albedo end {e:?}"))?;+ let fence = device+ .create_fence(&vk::FenceCreateInfo::default(), None)+ .map_err(|e| format!("albedo fence {e:?}"))?;+ device+ .queue_submit(ctx.queue, std::slice::from_ref(&vk::SubmitInfo::default().command_buffers(std::slice::from_ref(&cmd))), fence)+ .map_err(|e| format!("albedo submit {e:?}"))?;+ device.wait_for_fences(std::slice::from_ref(&fence), true, 1_000_000_000).map_err(|e| format!("albedo wait {e:?}"))?;+ device.destroy_fence(fence, None);+ device.free_command_buffers(pool, &[cmd]);+ device.destroy_command_pool(pool, None);+ let view = device+ .create_image_view(+ &vk::ImageViewCreateInfo::default()+ .image(image)+ .view_type(vk::ImageViewType::TYPE_2D)+ .format(vk::Format::R8G8B8A8_UNORM)+ .subresource_range(vk::ImageSubresourceRange {+ aspect_mask: vk::ImageAspectFlags::COLOR,+ base_mip_level: 0,+ level_count: 1,+ base_array_layer: 0,+ layer_count: 1,+ }),+ None,+ )+ .map_err(|e| format!("albedo view {e:?}"))?;+ let sampler = device+ .create_sampler(+ &vk::SamplerCreateInfo::default()+ .mag_filter(vk::Filter::LINEAR)+ .min_filter(vk::Filter::LINEAR)+ .address_mode_u(vk::SamplerAddressMode::CLAMP_TO_EDGE)+ .address_mode_v(vk::SamplerAddressMode::CLAMP_TO_EDGE)+ .address_mode_w(vk::SamplerAddressMode::CLAMP_TO_EDGE),+ None,+ )+ .map_err(|e| format!("albedo sampler {e:?}"))?;+ Ok((image, memory, view, sampler))+ }++ /// Upload the static avatar mesh (once per surface; capped at the budget).+ pub unsafe fn upload_avatar(&self, mesh: &[crate::mesh::YuuVertex]) {+ let converted: Vec<YuuVkVertex> = mesh.iter().take(AVATAR_VERT_CAP).map(YuuVkVertex::from).collect();+ let bytes = unsafe {+ std::slice::from_raw_parts(+ converted.as_ptr() as *const u8,+ converted.len() * mem::size_of::<YuuVkVertex>(),+ )+ };+ self.avatar_buf.upload(&self.ctx.device, bytes);+ }++ /// Resize the swapchain (recreates against the adopted window).+ pub unsafe fn resize(&mut self, width: u32, height: u32) {+ self.width = width.max(1);+ self.height = height.max(1);+ // Full swapchain recreation follows the kart resize path; until then+ // the viewport/scissor in `draw` tracks the new extent.+ }++ /// Draw one frame: upload the bone UBO, record, submit, present.+ /// `mesh_count` is the vertex count from the last [`Self::upload_avatar`].+ #[allow(clippy::too_many_arguments)]+ 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 _ = skin_rgb;+ let device = &self.ctx.device;+ // Wait for the last frame, then reset.+ device+ .wait_for_fences(std::slice::from_ref(&self.fence), true, 1_000_000_000)+ .map_err(|e| format!("fence wait {e:?}"))?;+ device.reset_fences(std::slice::from_ref(&self.fence)).map_err(|e| format!("fence reset {e:?}"))?;++ // UBO: view-projection + fixed sun + camera + bones.+ let mut ubo_bones = [[[0.0f32; 4]; 4]; MAX_BONES];+ for (i, b) in bones.iter().enumerate().take(MAX_BONES) {+ for (c, col) in b.chunks_exact(4).enumerate().take(4) {+ ubo_bones[i][c] = [col[0], col[1], col[2], col[3]];+ }+ }+ let ubo = YuuUbo {+ view_proj,+ sun_dir: normalize([0.35, -1.0, 0.45]),+ _pad0: 0.0,+ cam_pos,+ _pad1: 0.0,+ bones: ubo_bones,+ };+ let ubo_bytes = unsafe {+ std::slice::from_raw_parts(+ (&ubo as *const YuuUbo) as *const u8,+ mem::size_of::<YuuUbo>(),+ )+ };+ self.ubo_buf.upload(device, ubo_bytes);++ let acquire = self.swap.loader.acquire_next_image(+ self.swap.swapchain,+ 1_000_000_000,+ self.sem_acquire,+ vk::Fence::null(),+ );+ let img_idx = match acquire {+ Ok((idx, _)) => idx,+ Err(vk::Result::ERROR_OUT_OF_DATE_KHR) => return Err("swapchain out of date".to_string()),+ Err(e) => return Err(format!("acquire {e:?}")),+ };+ let fb = self.swap.framebuffers[img_idx as usize];+ device+ .reset_command_buffer(self.cmd, vk::CommandBufferResetFlags::empty())+ .map_err(|e| format!("reset cmd {e:?}"))?;+ let begin = vk::CommandBufferBeginInfo::default();+ device.begin_command_buffer(self.cmd, &begin).map_err(|e| format!("begin {e:?}"))?;+ let clear = [+ vk::ClearValue {+ color: vk::ClearColorValue { float32: [0.45, 0.68, 0.94, 1.0] },+ },+ vk::ClearValue {+ depth_stencil: vk::ClearDepthStencilValue { depth: 1.0, stencil: 0 },+ },+ ];+ let rp = vk::RenderPassBeginInfo::default()+ .render_pass(self.swap.render_pass)+ .framebuffer(fb)+ .render_area(vk::Rect2D {+ offset: vk::Offset2D { x: 0, y: 0 },+ extent: self.swap.extent,+ })+ .clear_values(&clear);+ device.cmd_begin_render_pass(self.cmd, &rp, vk::SubpassContents::INLINE);+ let viewport = vk::Viewport::default()+ .x(0.0)+ .y(0.0)+ .width(self.swap.extent.width as f32)+ .height(self.swap.extent.height as f32)+ .min_depth(0.0)+ .max_depth(1.0);+ device.cmd_set_viewport(self.cmd, 0, std::slice::from_ref(&viewport));+ let scissor = vk::Rect2D {+ offset: vk::Offset2D { x: 0, y: 0 },+ extent: self.swap.extent,+ };+ device.cmd_set_scissor(self.cmd, 0, std::slice::from_ref(&scissor));+ device.cmd_bind_pipeline(self.cmd, vk::PipelineBindPoint::GRAPHICS, self.pipes.pipeline);+ device.cmd_bind_descriptor_sets(+ self.cmd,+ vk::PipelineBindPoint::GRAPHICS,+ self.pipes.layout,+ 0,+ std::slice::from_ref(&self.pipes.descriptor_set),+ &[],+ );+ // Static avatar mesh.+ if mesh_count > 0 {+ device.cmd_bind_vertex_buffers(self.cmd, 0, std::slice::from_ref(&self.avatar_buf.buffer), &[0]);+ device.cmd_draw(self.cmd, mesh_count.min(AVATAR_VERT_CAP) as u32, 1, 0, 0);+ }+ device.cmd_end_render_pass(self.cmd);+ device.end_command_buffer(self.cmd).map_err(|e| format!("end {e:?}"))?;++ let wait = [self.sem_acquire];+ let signal = [self.sem_render];+ let wait_stages = [vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT];+ let submit = vk::SubmitInfo::default()+ .wait_semaphores(&wait)+ .wait_dst_stage_mask(&wait_stages)+ .command_buffers(std::slice::from_ref(&self.cmd))+ .signal_semaphores(&signal);+ device+ .queue_submit(self.ctx.queue, std::slice::from_ref(&submit), self.fence)+ .map_err(|e| format!("submit {e:?}"))?;+ let present = vk::PresentInfoKHR::default()+ .wait_semaphores(&signal)+ .swapchains(std::slice::from_ref(&self.swap.swapchain))+ .image_indices(std::slice::from_ref(&img_idx));+ match self.swap.loader.queue_present(self.ctx.queue, &present) {+ Ok(_) => Ok(()),+ Err(vk::Result::ERROR_OUT_OF_DATE_KHR) | Err(vk::Result::SUBOPTIMAL_KHR) => {+ Err("swapchain out of date".to_string())+ }+ Err(e) => Err(format!("present {e:?}")),+ }+ }++ /// Free everything except the context (the engine releases the window).+ pub unsafe fn destroy(&mut self) {+ let device = &self.ctx.device;+ device.device_wait_idle().ok();+ device.destroy_semaphore(self.sem_acquire, None);+ device.destroy_semaphore(self.sem_render, None);+ device.destroy_fence(self.fence, None);+ device.destroy_command_pool(self.pool, None);+ device.destroy_sampler(self.albedo_sampler, None);+ device.destroy_image_view(self.albedo_view, None);+ device.destroy_image(self.albedo_image, None);+ device.free_memory(self.albedo_memory, None);+ self.ubo_buf.destroy(device);+ self.avatar_buf.destroy(device);+ self.pipes.destroy(device);+ self.swap.cleanup(device);+ }+}++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]+}
library/avatar/src/main/rust/src/vulkan/swapchain.rs
diff --git a/games/hub/src/main/rust/src/vulkan/swapchain.rs b/library/avatar/src/main/rust/src/vulkan/swapchain.rssimilarity index 100%rename from games/hub/src/main/rust/src/vulkan/swapchain.rsrename to library/avatar/src/main/rust/src/vulkan/swapchain.rs
metadata_data/photos/games-hub/7.png
diff --git a/metadata_data/photos/games-hub/7.png b/metadata_data/photos/games-hub/7.pngindex f74973f6db..6c4d9201ac 100644Binary files a/metadata_data/photos/games-hub/7.png and b/metadata_data/photos/games-hub/7.png differ
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex e187bf8190..586f4128ca 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -43,6 +43,7 @@ include(":library:work") include(":library:ocr") include(":library:map") include(":library:ml")+include(":library:avatar") include(":library:image") include(":library:media") include(":library:log")@@ -109,6 +110,7 @@ include(":euicc") include(":backup") include(":share") include(":launcher")+include(":tvlauncher") include(":cast") include(":cast:protocol") include(":cast:tv")