various fixes
- Commit
38568b97f5e09c241cfaf2df29f19a20ddeac337- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-21 02:13 UTC (1 month ago)
- Parents
8adaedc
Diff
appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.ktindex 4ca8c0d59b..b1e76d9564 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/tv/TvStoreViewModel.kt@@ -7,7 +7,9 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.CatalogRepository+import com.vayunmathur.appstore.data.DefaultRepos import com.vayunmathur.appstore.data.InstalledAppsRepository+import com.vayunmathur.appstore.data.SyncStep import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.installer.InstallCoordinator@@ -15,6 +17,7 @@ import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.priority import com.vayunmathur.appstore.data.security.ApkCertificates+import com.vayunmathur.appstore.R import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted@@ -87,6 +90,7 @@ class TvStoreViewModel( viewModelScope.launch { installedRepo.refresh() if (AppSource.PLAYSTORE in enabledSourcesFlow.value) play.restore()+ syncIfNeverSynced() loadHome() } viewModelScope.launch {@@ -95,6 +99,58 @@ class TvStoreViewModel( } } + /**+ * Populate the offline catalogues the first time the TV store is opened.+ *+ * Same contract as the phone's `syncIfNeverSynced`: keyed off the catalogue being+ * empty rather than a first-run flag, so it also recovers a store whose first sync+ * failed or whose data was cleared — and stays quiet on every later launch, when+ * re-fetching full catalogues would be a poor trade for at-most-hours-stale data.+ * Progress reports through the existing status line the browse screen already shows.+ */+ private suspend fun syncIfNeverSynced() {+ val enabled = enabledSourcesFlow.value+ val offlineSources = setOf(+ DefaultRepos.FDROID.source, DefaultRepos.MODERN_APPS.source,+ DefaultRepos.PROPRIETARY.source,+ )+ if (enabled.intersect(offlineSources).isEmpty()) return+ if (catalog.recentlyUpdatedBySource(AppSource.FDROID, 1).isNotEmpty() ||+ catalog.recentlyUpdatedBySource(AppSource.MODERN_APPS, 1).isNotEmpty()+ ) {+ return+ }+ isLoadingFlow.value = true+ val report = catalog.sync(enabled) { step ->+ statusMessageFlow.value = context.getString(+ when (step) {+ SyncStep.FDROID -> R.string.sync_step_fdroid+ SyncStep.MODERN_APPS -> R.string.sync_step_modern_apps+ SyncStep.PROPRIETARY -> R.string.sync_step_proprietary+ },+ )+ }+ statusMessageFlow.value = ""+ isLoadingFlow.value = false+ AppMessages.show(+ when {+ report.allSkipped -> context.getString(R.string.sync_all_sources_off)+ !report.anyFailed -> context.getString(+ R.string.sync_done,+ (report.fdroidCount ?: 0) + (report.modernCount ?: 0) ++ (report.proprietaryCount ?: 0),+ )+ report.fdroidCount == null && report.modernCount == null &&+ report.proprietaryCount == null ->+ context.getString(R.string.sync_failed_all)+ report.fdroidCount == null -> context.getString(R.string.sync_failed_fdroid)+ report.proprietaryCount == null ->+ context.getString(R.string.sync_failed_proprietary)+ else -> context.getString(R.string.sync_failed_modern_apps)+ },+ )+ }+ /** Fill the browse rows from the TV-filtered catalogue. */ fun loadHome() { viewModelScope.launch {
library/avatar/src/main/rust/src/atlas.rs
diff --git a/library/avatar/src/main/rust/src/atlas.rs b/library/avatar/src/main/rust/src/atlas.rsnew file mode 100644index 0000000000..e4b1ba23bf--- /dev/null+++ b/library/avatar/src/main/rust/src/atlas.rs@@ -0,0 +1,313 @@+//! Procedural face atlas: skin-tone base + drawn face features.+//!+//! Split along module lines (repo `rustFileLength` gate). Generates a 256×256+//! RGBA atlas at runtime from traits — no `.glb` needed for faces. Layout:+//! - Full-atlas base fill = skin tone (so every skin UV keeps working).+//! - Face block [0, 128, 256, 256] (bottom half): 12 eye styles × rows,+//! 8 brow styles, 8 nose styles, 12 mouth styles, each drawn per style+//! index with trait colors. Mole/wrinkle/blush overlaid by index.+//! - Shirt block keeps procedural UV split (mesh UVs unchanged elsewhere).+//!+//! The head's face quad (mesh.rs) UVs point into the active eye/brow/nose/+//! mouth cells; sliders that move features shift the quad, styles select the+//! cell. Drawn-on but positioned by traits.++use crate::traits::YuuTraits;++/// Atlas edge in pixels.+pub const ATLAS_SIZE: usize = 256;++/// Face block origin (bottom half of the atlas).+pub const FACE_X: usize = 0;+pub const FACE_Y: usize = 128;+pub const FACE_W: usize = 256;+pub const FACE_H: usize = 128;++/// Cell grid inside the face block: 12 columns (max style count) × 4 rows+/// (eyes / brows / nose / mouth).+pub const FACE_COLS: usize = 12;+pub const FACE_ROWS: usize = 4;++/// Pixel width/height of one face cell.+pub fn face_cell() -> (usize, usize) {+ (FACE_W / FACE_COLS, FACE_H / FACE_ROWS)+}++/// UV rect (u0, v0, u1, v1) for a face cell.+/// Row 0 = eyes, 1 = brows, 2 = nose, 3 = mouth; col = style index clamped.+/// V matches sampler space (no flip — see [`cell_uv_by_col`]).+pub fn face_cell_uv(row: usize, style: i32) -> [f32; 4] {+ cell_uv_by_col(+ row.min(FACE_ROWS - 1),+ (style.max(0) as usize) % FACE_COLS,+ )+}++/// UV rect for a mole/wrinkle/blush overlay cell (sampler space, no flip).+///+/// Overlays share the spare brow-row cells (row 1, cols 8..11): column+/// `8 + (style mod 4)` — exactly the cells [`generate_atlas`] paints, so the+/// mesh decal UVs and the painted pixels always agree.+pub fn overlay_cell_uv(style: i32) -> [f32; 4] {+ cell_uv_by_col(1, 8 + (style.max(0) as usize % 4))+}++/// UV rect (u0, v0, u1, v1) for one face-block cell by explicit row/column.+///+/// No V flip: both backends sample memory row 0 at v=0 (Vulkan samples the+/// first texel at (0,0); GL unpacks the first byte to the bottom-left texel),+/// so v = memory_y / ATLAS_SIZE directly. (An earlier revision flipped V+/// here; every decal then sampled skin and faces rendered blank.)+fn cell_uv_by_col(row: usize, col: usize) -> [f32; 4] {+ let (cw, ch) = face_cell();+ let x0 = FACE_X + col * cw;+ let y0 = FACE_Y + row * ch;+ let s = ATLAS_SIZE as f32;+ [+ x0 as f32 / s,+ y0 as f32 / s,+ (x0 + cw) as f32 / s,+ (y0 + ch) as f32 / s,+ ]+}++/// Unpack an ARGB long to RGBA bytes.+fn argb_to_rgba(argb: u64, fallback: [u8; 3]) -> [u8; 4] {+ if argb == 0 {+ return [fallback[0], fallback[1], fallback[2], 0xFF];+ }+ [+ ((argb >> 16) & 0xFF) as u8,+ ((argb >> 8) & 0xFF) as u8,+ (argb & 0xFF) as u8,+ 0xFF,+ ]+}++/// Fill a rect in the pixel buffer (clipped).+fn fill_rect(+ px: &mut [u8],+ x: usize,+ y: usize,+ w: usize,+ h: usize,+ color: [u8; 4],+) {+ for j in y..(y + h).min(ATLAS_SIZE) {+ for i in x..(x + w).min(ATLAS_SIZE) {+ let o = (j * ATLAS_SIZE + i) * 4;+ px[o..o + 4].copy_from_slice(&color);+ }+ }+}++/// Fill an ellipse in the pixel buffer (clipped).+fn fill_ellipse(+ px: &mut [u8],+ cx: usize,+ cy: usize,+ rx: usize,+ ry: usize,+ color: [u8; 4],+) {+ let rx = rx.max(1);+ let ry = ry.max(1);+ for j in cy.saturating_sub(ry)..(cy + ry).min(ATLAS_SIZE) {+ for i in cx.saturating_sub(rx)..(cx + rx).min(ATLAS_SIZE) {+ let dx = (i as f32 - cx as f32) / rx as f32;+ let dy = (j as f32 - cy as f32) / ry as f32;+ if dx * dx + dy * dy <= 1.0 {+ let o = (j * ATLAS_SIZE + i) * 4;+ px[o..o + 4].copy_from_slice(&color);+ }+ }+ }+}++/// Generate the 256×256 RGBA face atlas for the given traits.+///+/// Base = skin tone everywhere (existing skin UVs keep working). Only the+/// SELECTED style cell per row is painted — other columns stay skin so style+/// selection visibly changes the atlas (and the mesh UVs, which point at the+/// selected cell, always hit painted pixels):+/// - Eyes (row 0): white sclera ellipse + dark pupil ellipse; size varies+/// with column, pupil offset zigzags so adjacent styles differ.+/// - Brows (row 1): horizontal bar; thickness/angle vary by column.+/// - Nose (row 2): vertical shaded bar; width/height vary by column.+/// - Mouth (row 3): horizontal smile bar; width/curve vary by column.+/// Mole/wrinkle/blush overlaid on the mouth-row spare cells when nonzero.+pub fn generate_atlas(traits: &YuuTraits) -> Vec<u8> {+ let skin = {+ let rgb = traits.skin_rgb();+ [+ (rgb[0].clamp(0.0, 1.0) * 255.0) as u8,+ (rgb[1].clamp(0.0, 1.0) * 255.0) as u8,+ (rgb[2].clamp(0.0, 1.0) * 255.0) as u8,+ 0xFF,+ ]+ };+ let mut px = vec![0u8; ATLAS_SIZE * ATLAS_SIZE * 4];+ // Base fill: skin everywhere.+ for o in px.chunks_exact_mut(4) {+ o.copy_from_slice(&skin);+ }++ let (cw, ch) = face_cell();+ let dark = [0x22, 0x1A, 0x14, 0xFF];+ let white = [0xFF, 0xFF, 0xFF, 0xFF];+ let eye_rgb = traits.eye_color;+ let brow_rgb = traits.brow_color;+ let mouth_rgb = traits.mouth_color;+ let eye_tint = argb_to_rgba(eye_rgb, [0x22, 0x1A, 0x14]);+ let brow_tint = argb_to_rgba(brow_rgb, [0x2A, 0x1E, 0x12]);+ let mouth_tint = argb_to_rgba(mouth_rgb, [0x8A, 0x3B, 0x2E]);++ // Row 0 — eyes: paint ONLY the selected style column. Other columns stay+ // skin so style selection visibly changes the atlas (and the mesh UVs,+ // which point at the selected cell, always hit painted pixels).+ let eye_col = (traits.eye_style.max(0) as usize) % FACE_COLS;+ {+ let x0 = FACE_X + eye_col * cw;+ let y0 = FACE_Y;+ let w = cw - 4;+ let ew = (w / 3).max(3) + eye_col % 3;+ let eh = (ch / 4).max(3);+ let cy = y0 + ch / 2;+ for side in [0, 1] {+ let cx = x0 + 2 + side * (w / 2) + (w / 4) % 3;+ fill_ellipse(&mut px, cx, cy, ew, eh, white);+ let pox = (cx as i32 + ((eye_col % 3) as i32 - 1)).max(x0 as i32 + 1) as usize;+ fill_ellipse(+ &mut px,+ pox,+ cy,+ (ew / 2).max(1),+ (eh / 2).max(1),+ eye_tint,+ );+ }+ }+ // Row 1 — brows: selected column only. Bar thickness/tilt vary.+ let brow_col = (traits.brow_style.max(0) as usize) % FACE_COLS;+ {+ let x0 = FACE_X + brow_col * cw;+ let y0 = FACE_Y + ch;+ let thick = 2 + brow_col % 3;+ let tilt = (brow_col % 3) as i32 - 1;+ for side in [0, 1] {+ let bx = x0 + 2 + side * ((cw - 4) / 2);+ for k in 0..thick {+ let yy = (y0 + ch / 2 + k) as i32 + tilt * (side as i32 * 2 - 1);+ if yy >= FACE_Y as i32 && (yy as usize) < FACE_Y + FACE_H {+ fill_rect(&mut px, bx, yy as usize, (cw - 4) / 2, 1, brow_tint);+ }+ }+ }+ }+ // Row 2 — nose: selected column only. Vertical shaded bar.+ let nose_col = (traits.nose_style.max(0) as usize) % FACE_COLS;+ {+ let x0 = FACE_X + nose_col * cw;+ let y0 = FACE_Y + 2 * ch;+ let nw = 2 + nose_col % 3;+ let nh = ch - 6 - (nose_col % 2) * 2;+ let shade = [+ (skin[0] as f32 * 0.85) as u8,+ (skin[1] as f32 * 0.82) as u8,+ (skin[2] as f32 * 0.80) as u8,+ 0xFF,+ ];+ fill_rect(&mut px, x0 + cw / 2 - nw / 2, y0 + 3, nw, nh, shade);+ fill_rect(&mut px, x0 + cw / 2 - nw / 2, y0 + 3 + nh, nw + 2, 2, dark);+ }+ // Row 3 — mouth: selected column only. Width/curve vary.+ let mouth_col = (traits.mouth_style.max(0) as usize) % FACE_COLS;+ {+ let x0 = FACE_X + mouth_col * cw;+ let y0 = FACE_Y + 3 * ch;+ let mw = (cw - 8).max(6) - (mouth_col % 4);+ let my = y0 + ch / 2 + (mouth_col % 3) - 1;+ fill_rect(&mut px, x0 + (cw - mw) / 2, my, mw, 3, mouth_tint);+ // Smile corners for even columns.+ if mouth_col % 2 == 0 {+ fill_rect(&mut px, x0 + (cw - mw) / 2, my.saturating_sub(2), 2, 2, mouth_tint);+ fill_rect(&mut px, x0 + (cw + mw) / 2 - 2, my.saturating_sub(2), 2, 2, mouth_tint);+ }+ }+ // Overlays: mole / wrinkle / blush on spare brow-row cells (cols 8..11).+ if traits.mole_style != 0 {+ let col = 8 + (traits.mole_style.max(0) as usize % 4);+ fill_ellipse(+ &mut px,+ FACE_X + col * cw + cw / 2,+ FACE_Y + ch + ch / 2,+ 2,+ 2,+ dark,+ );+ }+ if traits.wrinkle_style != 0 {+ let col = 8 + (traits.wrinkle_style.max(0) as usize % 4);+ for k in 0..3 {+ fill_rect(+ &mut px,+ FACE_X + col * cw + 3,+ FACE_Y + ch + 4 + k * 4,+ cw - 6,+ 1,+ dark,+ );+ }+ }+ if traits.blush_style != 0 {+ let col = 8 + (traits.blush_style.max(0) as usize % 4);+ let pink = [0xE8, 0x8A, 0x7A, 0xFF];+ fill_ellipse(&mut px, FACE_X + col * cw + 4, FACE_Y + ch + ch / 2, 3, 2, pink);+ fill_ellipse(+ &mut px,+ FACE_X + col * cw + cw - 4,+ FACE_Y + ch + ch / 2,+ 3,+ 2,+ pink,+ );+ }+ let _ = white;+ px+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::traits::YuuTraits;++ #[test]+ fn atlas_size_and_skin_base() {+ let t = YuuTraits::default();+ let px = generate_atlas(&t);+ assert_eq!(px.len(), ATLAS_SIZE * ATLAS_SIZE * 4);+ // Top-left pixel = skin fallback (default skin_tone 0 → [0.91,0.71,0.54]).+ assert_eq!(&px[0..4], &[232, 181, 137, 255]);+ }++ #[test]+ fn face_cell_uvs_in_face_block() {+ let uv = face_cell_uv(0, 3);+ // u inside [0,1]; eye row lives at memory rows 128..160 → v 0.5..0.625+ // (no V flip — samplers read memory row 0 at v=0 on both backends).+ assert!(uv[0] >= 0.0 && uv[2] <= 1.0);+ assert!(uv[1] >= 0.5 && uv[1] <= 0.625);+ assert!(uv[3] >= 0.5 && uv[3] <= 0.625);+ assert!(uv[2] > uv[0] && uv[3] > uv[1]);+ }++ #[test]+ fn styles_change_pixels() {+ let a = generate_atlas(&YuuTraits::default());+ let mut varied = YuuTraits::default();+ varied.eye_style = 7;+ varied.mouth_style = 9;+ let b = generate_atlas(&varied);+ assert_ne!(a, b, "style indices must change atlas pixels");+ }+}
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.rsindex 1ec41eba6d..cbff80937f 100644--- a/library/avatar/src/main/rust/src/engine.rs+++ b/library/avatar/src/main/rust/src/engine.rs@@ -44,6 +44,13 @@ pub struct SurfaceState { pub pitch: f32, /// Whether the camera auto-orbits. The editor sets false on creation. pub auto_rotate: bool,+ /// Face atlas needs (re)upload: set on creation + every trait change,+ /// consumed by the tick thread (which owns the GPU context).+ pub atlas_dirty: bool,+ /// Procedural mesh needs rebuild + re-upload (trait-dependent decal UVs):+ /// set on trait change when no bundled glb is active, consumed by the+ /// tick thread. glTF surfaces never set this (asset UVs are static).+ pub mesh_dirty: bool, } /// Max orbit pitch: enough to inspect top/bottom, never straight down/up.@@ -69,6 +76,8 @@ impl SurfaceState { yaw: 0.0, pitch: 0.0, auto_rotate: true,+ atlas_dirty: true,+ mesh_dirty: false, } } }@@ -95,8 +104,10 @@ pub struct Engine { /// Orbit prefs by surface id: written on input, restored on (re)create, /// never cleared by surface removal. pub orbit: HashMap<i32, OrbitPrefs>,- /// Shared CPU mesh bytes (procedural fallback or parsed glb), uploaded- /// per-surface to GPU. Single allocation across all surfaces.+ /// Shared CPU mesh (parsed glb when bundled, else the procedural fallback+ /// with default-trait decals), uploaded per-surface to GPU at creation.+ /// Procedural surfaces rebuild their own mesh from traits on change (the+ /// decal UVs are trait-dependent); glTF surfaces keep sharing this. pub mesh: Arc<Vec<YuuVertex>>, /// Bundled glb bytes, when the APK ships `base_upperbody.glb`. pub bundled_mesh: Option<Vec<u8>>,@@ -108,7 +119,7 @@ impl Engine { Self { surfaces: HashMap::new(), orbit: HashMap::new(),- mesh: Arc::new(build_avatar_mesh()),+ mesh: Arc::new(build_avatar_mesh(&crate::traits::YuuTraits::default())), bundled_mesh: None, } }@@ -145,7 +156,16 @@ pub fn ensure_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);+ let has_bundled = eng.bundled_mesh.is_some();+ let state = eng.surface_mut(surface_id, 512, 512);+ state.traits = YuuTraits::from_config_json(json);+ // Face atlas depends on traits — the tick thread re-uploads it.+ state.atlas_dirty = true;+ // Procedural decal UVs are trait-dependent — the tick thread rebuilds+ // + re-uploads the mesh. glTF surfaces keep the shared asset mesh.+ if !has_bundled {+ state.mesh_dirty = true;+ } } } @@ -292,7 +312,10 @@ pub fn view_proj_for( (view_proj.to_cols_array_2d(), eye.to_array()) } -/// Create the renderer for `window` on a surface and upload the shared mesh.+/// Create the renderer for `window` on a surface and upload the mesh.+///+/// Procedural surfaces get a mesh built from their own traits (decal UVs are+/// trait-dependent); bundled-glb surfaces share the parsed asset mesh. /// /// # Safety /// `window` must be a live adopted `ANativeWindow`; ownership stays with the@@ -312,12 +335,25 @@ pub unsafe fn create_renderer( 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;+ // Build this surface's mesh: shared asset when bundled, trait-specific+ // procedural mesh otherwise (done outside the tick path — creation is rare).+ let mesh: Vec<YuuVertex> = engine()+ .lock()+ .map(|e| {+ if e.bundled_mesh.is_some() {+ e.mesh.to_vec()+ } else {+ let traits = e+ .surfaces+ .get(&surface_id)+ .map(|s| s.traits.clone())+ .unwrap_or_default();+ build_avatar_mesh(&traits)+ }+ })+ .unwrap_or_else(|_| build_avatar_mesh(&crate::traits::YuuTraits::default())); if let Ok(mut eng) = engine().lock() { let prefs = eng.orbit.get(&surface_id).copied().unwrap_or_default(); let state = eng.surface_mut(surface_id, w, h);@@ -329,6 +365,7 @@ pub unsafe fn create_renderer( state.yaw = prefs.yaw; state.pitch = prefs.pitch; state.auto_rotate = prefs.auto_rotate;+ state.mesh_dirty = false; } let renderer = match unsafe { Renderer::select(window, width, height, w, h) } { Ok(r) => r,@@ -380,7 +417,7 @@ pub fn resize_renderer(surface_id: i32, width: i32, height: i32) { /// 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 (view_proj, cam_pos, bones, skin_rgb, count, paused, atlas, remesh) = { let eng = match engine().lock() { Ok(e) => e, Err(_) => return,@@ -402,7 +439,22 @@ pub fn tick_surface(surface_id: i32) { ); 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)+ // Regenerate the face atlas when traits changed (config path sets the+ // flag; generation is cheap CPU work done once per change, not per+ // frame — upload happens below on the render thread).+ let atlas = if state.atlas_dirty {+ Some(crate::atlas::generate_atlas(&state.traits))+ } else {+ None+ };+ // Rebuild the procedural mesh when traits changed (decal UVs are+ // trait-dependent). glTF surfaces never set this flag.+ let remesh = if state.mesh_dirty {+ Some(build_avatar_mesh(&state.traits))+ } else {+ None+ };+ (vp, cp, bones, skin, state.mesh_count, state.paused, atlas, remesh) }; if paused { return;@@ -412,6 +464,16 @@ pub fn tick_surface(surface_id: i32) { 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() {+ if let Some(mesh) = remesh {+ unsafe { renderer.upload_avatar(&mesh) };+ state.mesh_count = mesh.len();+ state.mesh_dirty = false;+ }+ if let Some(pixels) = atlas {+ if unsafe { renderer.upload_atlas(&pixels) }.is_ok() {+ state.atlas_dirty = false;+ }+ } let _ = unsafe { renderer.draw(view_proj, cam_pos, bone_arrays, skin_rgb, count) }; } }
library/avatar/src/main/rust/src/gles/renderer.rs
diff --git a/library/avatar/src/main/rust/src/gles/renderer.rs b/library/avatar/src/main/rust/src/gles/renderer.rsindex d71abebecc..80c4c38927 100644--- a/library/avatar/src/main/rust/src/gles/renderer.rs+++ b/library/avatar/src/main/rust/src/gles/renderer.rs@@ -10,6 +10,7 @@ //! GL objects then tears down EGL. The avatar mesh uploads once per surface, //! exactly like Vulkan. +use crate::atlas::ATLAS_SIZE; use crate::avatar::MAX_BONES; use crate::gles::buffers::{self, MeshBuffer}; use crate::gles::egl::Egl;@@ -43,6 +44,10 @@ pub struct GlesRenderer { u_cam_pos: glow::UniformLocation, /// `uBones` uniform location. u_bones: glow::UniformLocation,+ /// `uAlbedo` sampler location (texture unit 0 at draw).+ u_albedo: glow::UniformLocation,+ /// Albedo atlas texture (256x256 RGBA8; re-uploaded on trait change).+ albedo_tex: glow::Texture, /// Static avatar VAO/VBO (uploaded per surface). avatar: MeshBuffer, /// Current surface width.@@ -91,7 +96,7 @@ impl GlesRenderer { }; let program = unsafe { shaders::compile_program(&gl)? }; crate::gles::egl::step_log("program compiled+linked");- let (u_view_proj, u_sun_dir, u_cam_pos, u_bones) = unsafe {+ let (u_view_proj, u_sun_dir, u_cam_pos, u_bones, u_albedo) = unsafe { let view = gl .get_uniform_location(program, U_VIEW_PROJ) .ok_or_else(|| format!("missing uniform {U_VIEW_PROJ}"))?;@@ -104,13 +109,62 @@ impl GlesRenderer { let bones = gl .get_uniform_location(program, U_BONES) .ok_or_else(|| format!("missing uniform {U_BONES}"))?;- // Albedo must exist even though v1 binds no texture yet (Mali- // linkers dislike dead cross-stage uniforms, so the frag keeps a- // 1x1 default bound at draw time).- let _ = gl.get_uniform_location(program, U_ALBEDO);- (view, sun, cam, bones)+ // Mali linkers keep the sampler alive since the frag samples it.+ let albedo = gl+ .get_uniform_location(program, U_ALBEDO)+ .ok_or_else(|| format!("missing uniform {U_ALBEDO}"))?;+ (view, sun, cam, bones, albedo) }; crate::gles::egl::step_log("uniforms located");+ let albedo_tex = unsafe {+ let tex = gl+ .create_texture()+ .map_err(|e| format!("glGenTextures albedo: {e}"))?;+ gl.bind_texture(glow::TEXTURE_2D, Some(tex));+ gl.tex_parameter_i32(+ glow::TEXTURE_2D,+ glow::TEXTURE_MIN_FILTER,+ glow::LINEAR as i32,+ );+ gl.tex_parameter_i32(+ glow::TEXTURE_2D,+ glow::TEXTURE_MAG_FILTER,+ glow::LINEAR as i32,+ );+ gl.tex_parameter_i32(+ glow::TEXTURE_2D,+ glow::TEXTURE_WRAP_S,+ glow::CLAMP_TO_EDGE as i32,+ );+ gl.tex_parameter_i32(+ glow::TEXTURE_2D,+ glow::TEXTURE_WRAP_T,+ glow::CLAMP_TO_EDGE as i32,+ );+ // No uninitialized reads: allocate a skin-tone flat before the+ // engine's first upload_atlas. UNPACK_ALIGNMENT 1 is a no-op+ // safeguard (256*4 rows are already 4-aligned).+ gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);+ let size = ATLAS_SIZE as i32;+ let mut filled = vec![0u8; ATLAS_SIZE * ATLAS_SIZE * 4];+ for o in filled.chunks_exact_mut(4) {+ o.copy_from_slice(&[232, 181, 137, 255]);+ }+ gl.tex_image_2d(+ glow::TEXTURE_2D,+ 0,+ glow::RGBA8 as i32,+ size,+ size,+ 0,+ glow::RGBA,+ glow::UNSIGNED_BYTE,+ Some(&filled),+ );+ gl.bind_texture(glow::TEXTURE_2D, None);+ tex+ };+ crate::gles::egl::step_log("albedo texture created"); let avatar = unsafe { MeshBuffer::new(&gl)? }; crate::gles::egl::step_log("avatar MeshBuffer created"); let renderer = Self {@@ -121,6 +175,8 @@ impl GlesRenderer { u_sun_dir, u_cam_pos, u_bones,+ u_albedo,+ albedo_tex, avatar, width: width.max(1), height: height.max(1),@@ -137,6 +193,40 @@ impl GlesRenderer { unsafe { buffers::upload_avatar_mesh(&self.gl, &mut self.avatar, mesh) }; } + /// Upload a fresh 256x256 RGBA atlas (from `atlas::generate_atlas`) when+ /// traits change; the engine calls this right after creation and on every+ /// trait update.+ ///+ /// # Safety+ /// Must be called on the render thread with the EGL context current.+ pub unsafe fn upload_atlas(&mut self, pixels: &[u8]) -> Result<(), String> {+ let want = ATLAS_SIZE * ATLAS_SIZE * 4;+ if pixels.len() != want {+ return Err(format!(+ "atlas size mismatch: got {} bytes, want {want}",+ pixels.len()+ ));+ }+ unsafe {+ self.gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);+ self.gl+ .bind_texture(glow::TEXTURE_2D, Some(self.albedo_tex));+ self.gl.tex_sub_image_2d(+ glow::TEXTURE_2D,+ 0,+ 0,+ 0,+ ATLAS_SIZE as i32,+ ATLAS_SIZE as i32,+ glow::RGBA,+ glow::UNSIGNED_BYTE,+ glow::PixelUnpackData::Slice(pixels),+ );+ self.gl.bind_texture(glow::TEXTURE_2D, None);+ }+ Ok(())+ }+ /// Draw one frame: clear, set uniforms (view-proj, sun, cam, bones), /// draw the avatar, `eglSwapBuffers`. ///@@ -169,9 +259,14 @@ impl GlesRenderer { self.gl .uniform_3_f32(Some(&self.u_cam_pos), cam_pos[0], cam_pos[1], cam_pos[2]); self.gl.uniform_matrix_4_f32_slice(Some(&self.u_bones), false, &bone_flat);+ self.gl.active_texture(glow::TEXTURE0);+ self.gl+ .bind_texture(glow::TEXTURE_2D, Some(self.albedo_tex));+ self.gl.uniform_1_i32(Some(&self.u_albedo), 0); } unsafe { self.avatar.draw(&self.gl);+ self.gl.bind_texture(glow::TEXTURE_2D, None); self.gl.use_program(None); } self.egl.swap_buffers()@@ -189,14 +284,16 @@ impl GlesRenderer { unsafe { self.apply_state() }; } - /// Free program + VAO/VBOs, then tear down EGL. The engine releases the- /// window itself.+ /// Free program + albedo texture + VAO/VBOs, then tear down EGL. The+ /// engine releases the window itself. /// /// # Safety /// Must be called on the render thread that owns the EGL context. pub unsafe fn destroy(&mut self) { unsafe { self.gl.use_program(None);+ self.gl.bind_texture(glow::TEXTURE_2D, None);+ self.gl.delete_texture(self.albedo_tex); self.avatar.destroy(&self.gl); self.gl.delete_program(self.program); }
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.rsindex fa3907c5bc..4a9ac71f8d 100644--- a/library/avatar/src/main/rust/src/lib.rs+++ b/library/avatar/src/main/rust/src/lib.rs@@ -6,6 +6,7 @@ //! API: native methods receive `EnvUnowned` and adapt via `with_env`. pub mod avatar;+pub mod atlas; pub mod engine; pub mod gles; pub mod mesh;@@ -263,7 +264,7 @@ mod tests { #[test] fn engine_smoke() {- let mesh = build_avatar_mesh();+ let mesh = build_avatar_mesh(&crate::traits::YuuTraits::default()); assert!(!mesh.is_empty()); let poses = crate::pose::preset_poses(); assert!(poses.iter().any(|p| p.id == "wave"));
library/avatar/src/main/rust/src/mesh.rs
diff --git a/library/avatar/src/main/rust/src/mesh.rs b/library/avatar/src/main/rust/src/mesh.rsindex 4b4e7f920d..432875f273 100644--- a/library/avatar/src/main/rust/src/mesh.rs+++ b/library/avatar/src/main/rust/src/mesh.rs@@ -6,7 +6,9 @@ //! `base_upperbody.glb` when one is bundled, remapping its joints onto the //! same UBO order so poses behave identically either way. +use crate::atlas::{face_cell_uv, overlay_cell_uv}; use crate::avatar::{joint_by_name, ALL_JOINTS, JOINT_COUNT};+use crate::traits::YuuTraits; /// One skinned vertex. Matches `yuu_avatar.vert` locations 0..4. ///@@ -182,11 +184,87 @@ fn j(name: &str) -> f32 { joint_by_name(name).map(|jj| jj as u32 as f32).unwrap_or(0.0) } +/// Face decal plane: just proud of the head front (the head box front face+/// sits at z = 0.14 and stays flat under rounding) so the decal never+/// z-fights the skull.+const FACE_Z: f32 = 0.145;++/// Push one axis-aligned decal quad on the face plane as two triangles.+///+/// Fully bound to the head joint with a forward normal; `uv` is a v-up atlas+/// rect `[u0, v0, u1, v1]` (see [`face_cell_uv`](crate::atlas::face_cell_uv)).+fn push_decal_quad(out: &mut Vec<YuuVertex>, cx: f32, cy: f32, hw: f32, hh: f32, uv: [f32; 4]) {+ let head = j("head");+ let corners = [+ ([cx - hw, cy - hh], [uv[0], uv[1]]),+ ([cx + hw, cy - hh], [uv[2], uv[1]]),+ ([cx + hw, cy + hh], [uv[2], uv[3]]),+ ([cx - hw, cy + hh], [uv[0], uv[3]]),+ ];+ for k in [0, 1, 2, 0, 2, 3] {+ let (xy, t) = corners[k];+ out.push(YuuVertex {+ pos: [xy[0], xy[1], FACE_Z],+ normal: [0.0, 0.0, 1.0],+ uv: t,+ joints: [head, 0.0, 0.0, 0.0],+ weights: [1.0, 0.0, 0.0, 0.0],+ });+ }+}++/// Append the face decal quads for `traits`.+///+/// Four horizontal bands (eyes / brows / nose / mouth) tile the head front;+/// each band's rectangle is derived from the matching trait sliders so a+/// later slider drag can shift it live, and each band's UVs point at the+/// matching atlas cell. Mole/wrinkle/blush append small overlay quads (same+/// cells [`generate_atlas`](crate::atlas::generate_atlas) paints) when set.+fn push_face_decals(out: &mut Vec<YuuVertex>, traits: &YuuTraits) {+ // Eye band: the eye cell draws a twin-eye pair, so the band spans outer+ // edge to outer edge — per-eye offset plus per-eye half-width.+ let eye_off = 0.03 + traits.eye_spacing.clamp(0.0, 1.0) * 0.03;+ let eye_hw = eye_off + 0.035 + traits.eye_size.clamp(0.0, 1.0) * 0.03;+ let eye_cy = 1.32 + (traits.eye_height.clamp(0.0, 1.0) - 0.5) * 0.06;+ let eye_hh = 0.015 + traits.eye_size.clamp(0.0, 1.0) * 0.02;+ push_decal_quad(out, 0.0, eye_cy, eye_hw, eye_hh, face_cell_uv(0, traits.eye_style));+ // Brow band above the eyes; height slider slides it vertically.+ let brow_cy = 1.375 + (traits.brow_height.clamp(0.0, 1.0) - 0.5) * 0.05;+ push_decal_quad(out, 0.0, brow_cy, 0.085, 0.012, face_cell_uv(1, traits.brow_style));+ // Nose band between eyes and mouth; height slider slides it vertically.+ let nose_cy = 1.26 + (traits.nose_height.clamp(0.0, 1.0) - 0.5) * 0.05;+ push_decal_quad(out, 0.0, nose_cy, 0.02, 0.02, face_cell_uv(2, traits.nose_style));+ // Mouth band; width follows mouth_size, height follows mouth_height.+ let mouth_cy = 1.19 + (traits.mouth_height.clamp(0.0, 1.0) - 0.5) * 0.05;+ let mouth_hw = 0.03 + traits.mouth_size.clamp(0.0, 1.0) * 0.04;+ push_decal_quad(out, 0.0, mouth_cy, mouth_hw, 0.015, face_cell_uv(3, traits.mouth_style));+ // Mole: one cheek quad, side + offset picked by style index.+ if traits.mole_style != 0 {+ let idx = traits.mole_style.max(0) as usize;+ let side = if idx % 2 == 0 { -1.0 } else { 1.0 };+ let mx = side * (0.055 + 0.01 * (idx % 4) as f32);+ let my = 1.25 - 0.008 * (idx % 3) as f32;+ push_decal_quad(out, mx, my, 0.012, 0.012, overlay_cell_uv(traits.mole_style));+ }+ // Wrinkle: thin wide quad across the forehead.+ if traits.wrinkle_style != 0 {+ push_decal_quad(out, 0.0, 1.40, 0.06, 0.008, overlay_cell_uv(traits.wrinkle_style));+ }+ // Blush: one small quad per cheek.+ if traits.blush_style != 0 {+ let uv = overlay_cell_uv(traits.blush_style);+ push_decal_quad(out, -0.07, 1.22, 0.015, 0.012, uv);+ push_decal_quad(out, 0.07, 1.22, 0.015, 0.012, uv);+ }+}+ /// Build the procedural fallback upper-body mesh bound to the v1 skeleton. /// /// Proportions are Mii-like (big head, simple torso/arms); the renderer tints-/// skin vs shirt regions via the UV split in [`box_skinned`].-pub fn build_avatar_mesh() -> Vec<YuuVertex> {+/// skin vs shirt regions via the UV split in [`box_skinned`]. `traits` only+/// feeds the face decal quads (band placement + atlas style cells); the body+/// boxes are trait-independent.+pub fn build_avatar_mesh(traits: &YuuTraits) -> Vec<YuuVertex> { let mut out = Vec::with_capacity(1024); // Head: stacked boxes approximating a rounded skull + jaw. let head = Part { center: [0.0, 1.28, 0.0], size: [0.30, 0.30, 0.28], joint: j("head"), blend_joint: j("neck"), blend: 0.15, skin: true };@@ -217,6 +295,7 @@ pub fn build_avatar_mesh() -> Vec<YuuVertex> { let hand = Part { center: [side * 0.31, 0.34, 0.0], size: [0.10, 0.10, 0.10], joint: j(hand), blend_joint: j(fore), blend: 0.3, skin: true }; box_skinned(&mut out, &hand); }+ push_face_decals(&mut out, traits); out } @@ -228,7 +307,7 @@ pub fn build_avatar_mesh() -> Vec<YuuVertex> { pub fn load_gltf_mesh(bytes: &[u8]) -> Vec<YuuVertex> { match parse_gltf(bytes) { Some(mesh) if !mesh.is_empty() => mesh,- _ => build_avatar_mesh(),+ _ => build_avatar_mesh(&crate::traits::YuuTraits::default()), } } @@ -327,12 +406,14 @@ pub fn joint_names() -> Vec<&'static str> { #[cfg(test)] mod tests { use super::*;+ use crate::traits::YuuTraits; #[test] fn fallback_mesh_is_nonempty_and_weighted() {- let mesh = build_avatar_mesh();+ let mesh = build_avatar_mesh(&YuuTraits::default()); assert!(!mesh.is_empty());- // Rounded-box S=4 budget: 13 parts × 6 faces × 16 cells × 6 verts.+ // Rounded-box S=4 budget: 13 parts × 6 faces × 16 cells × 6 verts,+ // plus face decal quads (4 bands × 6 verts, overlays off by default). assert!( mesh.len() <= 8_192, "mesh {} verts exceeds dynamic budget",@@ -356,11 +437,10 @@ mod tests { // waving hand UP. Catches FK/weight/remap breakage that unit tests on // bones alone would miss. use crate::avatar::compute_bone_matrices;- use crate::traits::YuuTraits; use crate::pose::preset_by_id; use glam::Vec3;- let mesh = build_avatar_mesh(); let traits = YuuTraits::default();+ let mesh = build_avatar_mesh(&traits); let wave = preset_by_id("wave").expect("wave preset"); let bones = compute_bone_matrices(&traits, &wave, 0.0); // Skin the hand-box verts (fully hand-weighted region near x=0.31).@@ -392,4 +472,90 @@ mod tests { "waving hand should rise above y=1.0, got max {hand_max_y}" ); }++ #[test]+ fn face_quad_verts_use_face_block_uvs() {+ // Face decal verts: forward normal, head-bound, UVs inside the painted+ // face block (memory rows 128..256 → v 0.5..1.0, no V flip — samplers+ // read memory row 0 at v=0 on both backends).+ use crate::atlas::face_cell_uv;+ let traits = YuuTraits::default();+ let mesh = build_avatar_mesh(&traits);+ assert!(mesh.len() <= 8_192, "mesh {} verts exceeds budget", mesh.len());+ let head = j("head");+ let rows = [+ face_cell_uv(0, traits.eye_style),+ face_cell_uv(1, traits.brow_style),+ face_cell_uv(2, traits.nose_style),+ face_cell_uv(3, traits.mouth_style),+ ];+ let mut face_count = 0;+ for v in &mesh {+ // Rounded-box front-face centers also carry a [0,0,1] normal, so+ // the decal plane z is the real discriminator (body fronts sit at+ // z <= 0.14, decals at FACE_Z = 0.145).+ if v.normal != [0.0, 0.0, 1.0] || (v.pos[2] - FACE_Z).abs() >= 1e-6 {+ continue;+ }+ assert_eq!(v.joints, [head, 0.0, 0.0, 0.0]);+ assert_eq!(v.weights, [1.0, 0.0, 0.0, 0.0]);+ // Overlays are off under default traits: every head-on quad vert+ // is one of the four band quads (6 verts each).+ assert!((v.pos[2] - FACE_Z).abs() < 1e-6);+ assert!(v.uv[0] >= 0.0 && v.uv[0] <= 1.0);+ assert!(v.uv[1] >= 0.5 && v.uv[1] <= 1.0);+ assert!(+ rows.iter().any(|r| {+ v.uv[0] >= r[0] - 1e-6+ && v.uv[0] <= r[2] + 1e-6+ && v.uv[1] >= r[1] - 1e-6+ && v.uv[1] <= r[3] + 1e-6+ }),+ "face vert uv {:?} outside the four band cells",+ v.uv+ );+ face_count += 1;+ }+ assert_eq!(face_count, 24, "expected 4 bands x 6 verts, got {face_count}");+ }++ #[test]+ fn overlay_styles_append_extra_quads() {+ // Nonzero mole/wrinkle/blush each append quads pointing at the exact+ // spare brow-row cells generate_atlas paints.+ use crate::atlas::{face_cell_uv, overlay_cell_uv};+ fn is_decal(v: &&YuuVertex) -> bool {+ v.normal == [0.0, 0.0, 1.0] && (v.pos[2] - FACE_Z).abs() < 1e-6+ }+ let mut traits = YuuTraits::default();+ traits.mole_style = 1;+ traits.wrinkle_style = 2;+ traits.blush_style = 3;+ let mesh = build_avatar_mesh(&traits);+ // 24 band verts + mole 6 + wrinkle 6 + blush 12.+ let face_count = mesh.iter().filter(is_decal).count();+ assert_eq!(face_count, 48, "overlay quads missing, got {face_count}");+ let cells = [+ face_cell_uv(0, traits.eye_style),+ face_cell_uv(1, traits.brow_style),+ face_cell_uv(2, traits.nose_style),+ face_cell_uv(3, traits.mouth_style),+ overlay_cell_uv(traits.mole_style),+ overlay_cell_uv(traits.wrinkle_style),+ overlay_cell_uv(traits.blush_style),+ ];+ for v in mesh.iter().filter(is_decal) {+ assert!(+ cells.iter().any(|r| {+ v.uv[0] >= r[0] - 1e-6+ && v.uv[0] <= r[2] + 1e-6+ && v.uv[1] >= r[1] - 1e-6+ && v.uv[1] <= r[3] + 1e-6+ }),+ "overlay vert uv {:?} outside band/overlay cells",+ v.uv+ );+ }+ assert!(mesh.len() <= 8_192);+ } }
library/avatar/src/main/rust/src/renderer.rs
diff --git a/library/avatar/src/main/rust/src/renderer.rs b/library/avatar/src/main/rust/src/renderer.rsindex 0e86ef7559..e7ec9b007e 100644--- a/library/avatar/src/main/rust/src/renderer.rs+++ b/library/avatar/src/main/rust/src/renderer.rs@@ -46,6 +46,17 @@ impl Renderer { } } + /// Upload a fresh face atlas (regenerated when traits change).+ ///+ /// # Safety+ /// Must be called on the render thread with the backend's context current.+ pub unsafe fn upload_atlas(&mut self, pixels: &[u8]) -> Result<(), String> {+ match self {+ Self::Vulkan(r) => unsafe { r.upload_atlas(pixels) },+ Self::Gles(r) => unsafe { r.upload_atlas(pixels) },+ }+ }+ /// Resize the swapchain/surface. /// /// # Safety
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.rsindex 6d34fa2ea9..1f170c610d 100644--- a/library/avatar/src/main/rust/src/vulkan/renderer.rs+++ b/library/avatar/src/main/rust/src/vulkan/renderer.rs@@ -6,6 +6,7 @@ //! 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::atlas::ATLAS_SIZE; use crate::avatar::MAX_BONES; use crate::vulkan::buffers::{AllocatedBuffer, YuuUbo, YuuVkVertex}; use crate::vulkan::context::VulkanContext;@@ -30,7 +31,8 @@ pub struct YuuRenderer { pub avatar_buf: AllocatedBuffer, /// Uniform buffer (view-projection + sun + camera + bones). pub ubo_buf: AllocatedBuffer,- /// Albedo texture image (1x1 skin default, updated from traits).+ /// Albedo texture image (ATLAS_SIZE×ATLAS_SIZE skin-flat default,+ /// re-uploaded in place from [`generate_atlas`](crate::atlas::generate_atlas)). pub albedo_image: vk::Image, /// Albedo memory. pub albedo_memory: vk::DeviceMemory,@@ -59,7 +61,7 @@ impl YuuRenderer { /// /// 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.+ /// the ATLAS_SIZE x ATLAS_SIZE skin-flat albedo bound to the sampler slot. /// /// # Safety /// `window` must be a live adopted `ANativeWindow`; ownership stays with@@ -139,17 +141,32 @@ impl YuuRenderer { }) } - /// Create the 1x1 albedo default (linear RGBA8) + view + sampler, already- /// in `SHADER_READ_ONLY_OPTIMAL` for the frag sampler slot.+ /// Create the ATLAS_SIZE×ATLAS_SIZE albedo (linear RGBA8) + view ++ /// sampler, already in `SHADER_READ_ONLY_OPTIMAL` for the frag sampler+ /// slot. Every texel is pre-filled with `rgba` (the skin tone), so if+ /// [`Self::upload_atlas`] is never called the avatar renders exactly as+ /// the old 1x1 skin-flat default did — same texel value under+ /// CLAMP_TO_EDGE on every UV. unsafe fn create_albedo( ctx: &VulkanContext, rgba: [u8; 4],+ ) -> Result<(vk::Image, vk::DeviceMemory, vk::ImageView, vk::Sampler), String> {+ Self::create_albedo_image(ctx, &rgba.repeat(ATLAS_SIZE * ATLAS_SIZE))+ }++ /// Allocate an ATLAS_SIZE×ATLAS_SIZE linear RGBA8 image, fill it with+ /// `pixels`, transition to `SHADER_READ_ONLY_OPTIMAL`, and create the+ /// view + sampler. `pixels` must be exactly ATLAS_SIZE×ATLAS_SIZE×4+ /// bytes (checked in [`Self::write_linear_image`]).+ unsafe fn create_albedo_image(+ ctx: &VulkanContext,+ pixels: &[u8], ) -> 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 })+ .extent(vk::Extent3D { width: ATLAS_SIZE as u32, height: ATLAS_SIZE as u32, depth: 1 }) .mip_levels(1) .array_layers(1) .samples(vk::SampleCountFlags::TYPE_1)@@ -176,12 +193,9 @@ impl YuuRenderer { ) .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);+ // Write the texels through the mapped linear image, row by row:+ // LINEAR tiling may pad rows (row_pitch > width*4).+ Self::write_linear_image(device, image, memory, pixels)?; // Transition to SHADER_READ_ONLY_OPTIMAL via a one-shot barrier. let pool_info = vk::CommandPoolCreateInfo::default() .queue_family_index(ctx.queue_family_index)@@ -261,6 +275,86 @@ impl YuuRenderer { Ok((image, memory, view, sampler)) } + /// Copy `pixels` (exactly ATLAS_SIZE×ATLAS_SIZE×4 bytes) into a mapped+ /// LINEAR-tiled image, one row at a time honoring the driver's row pitch.+ /// LINEAR tiling does NOT guarantee tightly packed rows — `row_pitch`+ /// may exceed `width * 4` — so a single flat memcpy would shear the+ /// atlas on drivers that pad. The caller must hold the mapping contract+ /// (memory is HOST_VISIBLE | HOST_COHERENT).+ unsafe fn write_linear_image(+ device: &ash::Device,+ image: vk::Image,+ memory: vk::DeviceMemory,+ pixels: &[u8],+ ) -> Result<(), String> {+ const EXPECTED: usize = ATLAS_SIZE * ATLAS_SIZE * 4;+ if pixels.len() != EXPECTED {+ return Err(format!(+ "albedo: expected {EXPECTED} bytes, got {}",+ pixels.len()+ ));+ }+ let layout = device.get_image_subresource_layout(+ image,+ vk::ImageSubresource {+ aspect_mask: vk::ImageAspectFlags::COLOR,+ mip_level: 0,+ array_layer: 0,+ },+ );+ let row_pitch = layout.row_pitch as usize;+ let row_bytes = ATLAS_SIZE * 4;+ if row_pitch < row_bytes {+ return Err(format!("albedo: row_pitch {row_pitch} < row {row_bytes}"));+ }+ let base = device+ .map_memory(memory, 0, layout.size, vk::MemoryMapFlags::empty())+ .map_err(|e| format!("albedo map {e:?}"))? as *mut u8;+ let dst_base = unsafe { base.add(layout.offset as usize) };+ for row in 0..ATLAS_SIZE {+ let src = unsafe { pixels.as_ptr().add(row * row_bytes) };+ let dst = unsafe { dst_base.add(row * row_pitch) };+ unsafe { std::ptr::copy_nonoverlapping(src, dst, row_bytes) };+ }+ device.unmap_memory(memory);+ Ok(())+ }++ /// (Re)upload a 256×256 RGBA atlas into the existing albedo image, in+ /// place — no image/view recreation, no descriptor rebind (the sampler+ /// slot still points at the same view).+ ///+ /// The engine calls this on the render thread when traits change with+ /// the output of+ /// [`generate_atlas`](crate::atlas::generate_atlas). Until the first+ /// call, the image holds the skin-flat seed from [`Self::create_albedo`],+ /// so rendering is identical to the old 1x1 default.+ ///+ /// Synchronization: this blocks on `device_wait_idle()` before touching+ /// mapped memory, which is a host-write → fragment-shader-read barrier+ /// by brute force — no in-flight draw may still be sampling the image.+ /// A full idle is acceptable here because this path fires at most a few+ /// times per second on trait/config changes, never per frame; the+ /// per-frame path (`draw`) stays on its lightweight per-frame fence.+ /// A finer barrier (per-frame fence wait + layout-preserving+ /// HOST→FRAGMENT_SHADER image barrier) would avoid the stall but adds+ /// command-buffer churn for zero visible gain on a config-change path.+ ///+ /// # Safety+ /// Must be called on the render thread (the same thread that draws).+ pub unsafe fn upload_atlas(&mut self, pixels: &[u8]) -> Result<(), String> {+ const EXPECTED: usize = ATLAS_SIZE * ATLAS_SIZE * 4;+ if pixels.len() != EXPECTED {+ return Err(format!(+ "albedo: expected {EXPECTED} bytes, got {}",+ pixels.len()+ ));+ }+ let device = &self.ctx.device;+ device.device_wait_idle().map_err(|e| format!("albedo idle {e:?}"))?;+ unsafe { Self::write_linear_image(device, self.albedo_image, self.albedo_memory, pixels) }+ }+ /// 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();
youpipe/src/main/rust/src/lib.rs
diff --git a/youpipe/src/main/rust/src/lib.rs b/youpipe/src/main/rust/src/lib.rsindex 199afd1d15..590e60b58d 100644--- a/youpipe/src/main/rust/src/lib.rs+++ b/youpipe/src/main/rust/src/lib.rs@@ -40,7 +40,7 @@ pub mod suggestions; mod android { use jni::objects::{JClass, JString}; use jni::sys::jstring;- use jni::JNIEnv;+ use jni::{Env, EnvUnowned}; use crate::native_http::BridgeHttpClient; @@ -58,12 +58,12 @@ mod android { serde_json::json!({ "ok": false, "error": message }).to_string() } - fn text(env: &mut JNIEnv<'_>, value: &JString<'_>) -> String {+ fn text(env: &mut Env<'_>, value: &JString<'_>) -> String { env.get_string(value).map(Into::into).unwrap_or_default() } /// Optional strings arrive as null; treat empty as absent too.- fn optional_text(env: &mut JNIEnv<'_>, value: &JString<'_>) -> Option<String> {+ fn optional_text(env: &mut Env<'_>, value: &JString<'_>) -> Option<String> { if value.is_null() { return None; }@@ -71,197 +71,204 @@ mod android { (!s.is_empty()).then_some(s) } - fn to_jstring(env: &mut JNIEnv<'_>, value: String) -> jstring {+ fn to_jstring(env: &mut Env<'_>, value: String) -> jstring { env.new_string(value).map(|s| s.into_raw()).unwrap_or(std::ptr::null_mut()) } + /// Runs `body` with an attached [`Env`], returning null (which Kotlin reads as failure)+ /// if the attach fails. Every entry point has the same shape: read the arguments, build+ /// a [`BridgeHttpClient`] over the Kotlin downloader, call one extractor, return a JSON+ /// envelope. Exceptions never cross the boundary — failures come back as+ /// `{"ok":false,"error":"..."}`.+ fn with_attached_env(+ env: &mut EnvUnowned<'_>,+ body: impl FnOnce(&mut Env<'_>) -> String,+ ) -> jstring {+ env.with_env(|env| {+ let payload = body(env);+ Ok::<jstring, jni::errors::Error>(to_jstring(env, payload))+ })+ .resolve::<jni::errors::LogErrorAndDefault>()+ }+ #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_search<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, query: JString<'l>, filter: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let query = text(&mut env, &query);- let filter = optional_text(&mut env, &filter);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let query = text(env, &query);+ let filter = optional_text(env, &filter);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::search::search(&client, &query, filter.as_deref(), &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_searchPage<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, token: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let token = text(&mut env, &token);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let token = text(env, &token);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::search::search_page(&client, &token, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_suggestions<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, query: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let query = text(&mut env, &query);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let query = text(env, &query);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::suggestions::suggestions_for(&client, &query, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_channelInfo<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, id: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let id = text(&mut env, &id);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let id = text(env, &id);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::channel_info(&client, &id, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_playlistInfo<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, id: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let id = text(&mut env, &id);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let id = text(env, &id);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::playlist_info(&client, &id, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_trending<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::trending(&client, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_browseContinuation<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, token: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let token = text(&mut env, &token);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let token = text(env, &token);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::browse_continuation(&client, &token, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_comments<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, video_id: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let video_id = text(&mut env, &video_id);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let video_id = text(env, &video_id);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::comments(&client, &video_id, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_commentsPage<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, token: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let token = text(&mut env, &token);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let token = text(env, &token);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); envelope(crate::browse::comments_page(&client, &token, &hl, &gl))- };- to_jstring(&mut env, payload)+ }) } /// Stream extraction runs two requests: `player` for the media, then `next` for the metadata@@ -269,19 +276,19 @@ mod android { /// non-fatal — playback still works without those fields, so it is recorded and ignored. #[no_mangle] pub extern "system" fn Java_com_vayunmathur_youpipe_nativeext_YouPipeNative_streamInfo<'l>(- mut env: JNIEnv<'l>,+ env: &mut EnvUnowned<'l>, _class: JClass<'l>, video_id: JString<'l>, hl: JString<'l>, gl: JString<'l>, ) -> jstring {- let video_id = text(&mut env, &video_id);- let hl = text(&mut env, &hl);- let gl = text(&mut env, &gl);+ with_attached_env(env, |env| {+ let video_id = text(env, &video_id);+ let hl = text(env, &hl);+ let gl = text(env, &gl); - let payload = { // Resolve the bridge class on this thread before the first request.- crate::native_http::init(&mut env);+ crate::native_http::init(env); let client = BridgeHttpClient::new(); let result = crate::stream::stream_info(&client, &video_id, &hl, &gl).map(|mut info| { if let Err(e) =@@ -292,7 +299,6 @@ mod android { info }); envelope(result)- };- to_jstring(&mut env, payload)+ }) } }