avatar: add engine Rust tests
- Commit
0e2cdad5bf823bfaf39b74e4180f75c398da1cc1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-18 16:13 UTC (17 days ago)
- Parents
c6ac8db
Raise yuu_avatar host-coverable line coverage to 92% with engine lifecycle, Vulkan/EGL/GLES helper, swapchain and shader-contract tests. Total crate coverage is 55.9%: the remainder is Vulkan/GLES device code that cannot execute without a GPU, EGL display, and ANativeWindow. Also extracts spv_words() (aligned SPIR-V words) shared with kart. Verified with cargo test -p yuu_avatar (90 passed).
Diff
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 639f80c011..98f9b386dc 100644--- a/library/avatar/src/main/rust/src/engine.rs+++ b/library/avatar/src/main/rust/src/engine.rs@@ -162,3 +162,5 @@ pub fn ensure_engine() { include!("engine_config.rs"); include!("engine_frame.rs"); include!("engine_lifecycle.rs");+#[cfg(test)]+mod engine_coverage_tests;
library/avatar/src/main/rust/src/engine/engine_coverage_tests.rs
diff --git a/library/avatar/src/main/rust/src/engine/engine_coverage_tests.rs b/library/avatar/src/main/rust/src/engine/engine_coverage_tests.rsnew file mode 100644index 0000000000..7eeaa74dbc--- /dev/null+++ b/library/avatar/src/main/rust/src/engine/engine_coverage_tests.rs@@ -0,0 +1,103 @@+//! Global-engine lifecycle tests using unique surface ids (93xxx) so they+//! stay parallel-safe alongside the other engine tests that share the map.+use super::*;+use crate::mesh::build_avatar_mesh;++fn cleanup(id: i32) {+ if let Ok(mut eng) = engine().lock() {+ eng.surfaces.remove(&id);+ eng.orbit.remove(&id);+ }+}++#[test]+fn upload_resize_tick_and_destroy_without_renderer() {+ let id = 93_001;+ cleanup(id);+ // Unknown surface: upload fails, tick/resize/destroy are no-ops.+ let mesh = build_avatar_mesh(&crate::traits::YuuTraits::default());+ assert!(!upload_mesh(id, &mesh));+ resize_renderer(id, 800, 600);+ tick_surface(id);+ destroy_renderer(id);+ assert_eq!(generation(id), 0);++ // Known surface without a renderer: upload still fails, resize records+ // the clamped size, tick returns early, paused tick returns early.+ set_config(id, "{}", "idle");+ assert!(!upload_mesh(id, &mesh));+ resize_renderer(id, 0, -3);+ {+ let eng = engine().lock().expect("engine");+ let s = eng.surfaces.get(&id).expect("surface");+ assert_eq!((s.width, s.height), (1, 1), "sizes clamp to at least 1");+ }+ resize_renderer(id, 640, 480);+ {+ let eng = engine().lock().expect("engine");+ let s = eng.surfaces.get(&id).expect("surface");+ assert_eq!((s.width, s.height), (640, 480));+ }+ tick_surface(id); // no renderer -> early return, no panic+ set_paused(id, true);+ tick_surface(id); // paused -> early return+ set_paused(id, false);+ destroy_renderer(id); // no renderer to destroy, mesh_count resets below+ {+ let eng = engine().lock().expect("engine");+ let s = eng.surfaces.get(&id).expect("surface");+ assert_eq!(s.mesh_count, 0);+ assert!(s.renderer.is_none());+ }+ remove_surface(id);+ assert!(!engine().lock().expect("engine").surfaces.contains_key(&id));+ cleanup(id);+}++#[test]+fn bundled_mesh_and_trait_paths_via_create_renderer_failure() {+ let id = 93_002;+ cleanup(id);+ // With no bundled mesh, create_renderer builds the procedural mesh,+ // sets surface size/orbit, then fails cleanly on the host (no window).+ set_config(id, r#"{"bodyHeight":0.5}"#, "wave");+ let ok = unsafe { create_renderer(id, std::ptr::null_mut(), 640, 480) };+ assert!(!ok, "host without a window must fail renderer creation");+ {+ let eng = engine().lock().expect("engine");+ let s = eng.surfaces.get(&id).expect("surface state is set before backend selection");+ assert_eq!((s.width, s.height), (640, 480));+ assert!(!s.paused);+ }+ // Bundled-mesh branch: corrupt bytes parse to a fallback, still fail cleanly.+ set_bundled_mesh(b"not a glb".to_vec());+ let ok = unsafe { create_renderer(id, std::ptr::null_mut(), 0, 0) };+ assert!(!ok);+ // Clear the bundled bytes for other tests (restore pristine engine state).+ if let Ok(mut eng) = engine().lock() {+ eng.bundled_mesh = None;+ eng.pack = None;+ }+ cleanup(id);+}++#[test]+fn try_vulkan_fails_cleanly_on_host() {+ let r = unsafe { try_vulkan(std::ptr::null_mut(), 640, 480, 640, 480) };+ assert!(r.is_err(), "host Vulkan attempt must fail cleanly: {:?}", r.map(|_| ()));+}++#[test]+fn lifecycle_generation_and_remove() {+ let id = 93_003;+ cleanup(id);+ assert_eq!(generation(id), 0);+ let g = next_generation(id);+ assert_eq!(g, 1);+ assert_eq!(next_generation(id), 2);+ assert_eq!(generation(id), 2);+ destroy_renderer(id);+ remove_surface(id);+ assert_eq!(generation(id), 0, "removed surface reports generation 0");+ cleanup(id);+}
library/avatar/src/main/rust/src/gles/egl.rs
diff --git a/library/avatar/src/main/rust/src/gles/egl.rs b/library/avatar/src/main/rust/src/gles/egl.rsindex 446223e2b4..0dd1e86fa6 100644--- a/library/avatar/src/main/rust/src/gles/egl.rs+++ b/library/avatar/src/main/rust/src/gles/egl.rs@@ -16,6 +16,8 @@ use khronos_egl as egl; use std::os::raw::c_void;+#[cfg(test)]+mod egl_tests; /// EGL API instance: dynamically loaded `libEGL.so` (EGL 1.4 entry points โ /// everything this engine needs is 1.0-era core).
library/avatar/src/main/rust/src/gles/egl/egl_tests.rs
diff --git a/library/avatar/src/main/rust/src/gles/egl/egl_tests.rs b/library/avatar/src/main/rust/src/gles/egl/egl_tests.rsnew file mode 100644index 0000000000..ae0fd113c7--- /dev/null+++ b/library/avatar/src/main/rust/src/gles/egl/egl_tests.rs@@ -0,0 +1,48 @@+//! Tests for the EGL config attribute tables (pure data, no display needed).+use super::*;++fn pairs(attribs: &[egl::Int]) -> Vec<(egl::Int, egl::Int)> {+ assert_eq!(attribs.last(), Some(&egl::NONE), "table must be NONE-terminated");+ attribs[..attribs.len() - 1]+ .chunks_exact(2)+ .map(|c| (c[0], c[1]))+ .collect()+}++fn depth_of(attribs: &[egl::Int]) -> egl::Int {+ pairs(attribs)+ .into_iter()+ .find(|(k, _)| *k == egl::DEPTH_SIZE)+ .map(|(_, v)| v)+ .expect("depth entry")+}++#[test]+fn config_tables_are_wellformed_and_ordered_richest_first() {+ for t in [CONFIG_ATTRIBS_D24, CONFIG_ATTRIBS_D16, CONFIG_ATTRIBS_565] {+ let p = pairs(t);+ assert!(p.iter().any(|(k, v)| *k == egl::RENDERABLE_TYPE && *v == egl::OPENGL_ES3_BIT));+ assert!(p.iter().any(|(k, v)| *k == egl::SURFACE_TYPE && *v == egl::WINDOW_BIT));+ }+ assert_eq!(depth_of(CONFIG_ATTRIBS_D24), 24);+ assert_eq!(depth_of(CONFIG_ATTRIBS_D16), 16);+ assert_eq!(depth_of(CONFIG_ATTRIBS_565), 16);+ // D24 has 8-bit colour; the 565 fallback trades colour for availability.+ let d24 = pairs(CONFIG_ATTRIBS_D24);+ assert!(d24.iter().any(|(k, v)| *k == egl::RED_SIZE && *v == 8));+ let f = pairs(CONFIG_ATTRIBS_565);+ assert!(f.iter().any(|(k, v)| *k == egl::RED_SIZE && *v == 5));+ assert!(f.iter().any(|(k, v)| *k == egl::GREEN_SIZE && *v == 6));+ assert!(f.iter().any(|(k, v)| *k == egl::BLUE_SIZE && *v == 5));+}++#[test]+fn context_attribs_request_es3() {+ assert_eq!(CONTEXT_ATTRIBS, &[egl::CONTEXT_CLIENT_VERSION, 3, egl::NONE]);+}++#[test]+fn egl_new_fails_cleanly_without_a_window_on_host() {+ let r = unsafe { Egl::new(std::ptr::null_mut()) };+ assert!(r.is_err(), "host without EGL/window must fail cleanly");+}
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 c507d571a7..da5d9fd54e 100644--- a/library/avatar/src/main/rust/src/gles/renderer.rs+++ b/library/avatar/src/main/rust/src/gles/renderer.rs@@ -17,6 +17,8 @@ use crate::gles::egl::Egl; use crate::gles::shaders::{self, U_ALBEDO, U_BONES, U_CAM_POS, U_SUN_DIR, U_VIEW_PROJ}; use crate::mesh::YuuVertex; use glow::HasContext as _;+#[cfg(test)]+mod renderer_tests; /// Static avatar mesh budget: the procedural fallback is ~1k verts; 64k /// leaves margin for a detailed glTF base mesh.
library/avatar/src/main/rust/src/gles/renderer/renderer_tests.rs
diff --git a/library/avatar/src/main/rust/src/gles/renderer/renderer_tests.rs b/library/avatar/src/main/rust/src/gles/renderer/renderer_tests.rsnew file mode 100644index 0000000000..a48da292ed--- /dev/null+++ b/library/avatar/src/main/rust/src/gles/renderer/renderer_tests.rs@@ -0,0 +1,23 @@+//! Host tests for GLES renderer helpers and its failure path.+use super::*;++#[test]+fn flatten_and_normalize_edge_cases() {+ let zero = [[0.0; 4]; 4];+ assert_eq!(flatten(&zero), [0.0; 16]);+ let m = glam::Mat4::from_translation(glam::Vec3::new(1.0, 2.0, 3.0)).to_cols_array_2d();+ let f = flatten(&m);+ // Translation lives in the fourth column (indices 12..14).+ assert_eq!([f[12], f[13], f[14]], [1.0, 2.0, 3.0]);+ assert_eq!(normalize([0.0, -5.0, 0.0]), [0.0, -1.0, 0.0]);+ let n = normalize([1e-12, 0.0, 0.0]);+ assert!(n.iter().all(|v| v.is_finite()));+}++#[test]+fn gles_renderer_new_fails_cleanly_without_a_window_on_host() {+ let r = unsafe { GlesRenderer::new(std::ptr::null_mut(), 640, 480) };+ assert!(r.is_err(), "host without EGL/window must fail cleanly");+ let r = unsafe { GlesRenderer::new(std::ptr::null_mut(), 0, 0) };+ assert!(r.is_err());+}
library/avatar/src/main/rust/src/gles/shaders.rs
diff --git a/library/avatar/src/main/rust/src/gles/shaders.rs b/library/avatar/src/main/rust/src/gles/shaders.rsindex d2824d298d..e38319e303 100644--- a/library/avatar/src/main/rust/src/gles/shaders.rs+++ b/library/avatar/src/main/rust/src/gles/shaders.rs@@ -23,6 +23,8 @@ pub const U_CAM_POS: &str = "uCamPos"; pub const U_BONES: &str = "uBones"; /// Albedo sampler. pub const U_ALBEDO: &str = "uAlbedo";+#[cfg(test)]+mod shaders_tests; /// Compile `VERT_SRC` + `FRAG_SRC`, link, return the program. On any failure /// the returned string carries the shader/program info log from the driver.
library/avatar/src/main/rust/src/gles/shaders/shaders_tests.rs
diff --git a/library/avatar/src/main/rust/src/gles/shaders/shaders_tests.rs b/library/avatar/src/main/rust/src/gles/shaders/shaders_tests.rsnew file mode 100644index 0000000000..515bba4ebb--- /dev/null+++ b/library/avatar/src/main/rust/src/gles/shaders/shaders_tests.rs@@ -0,0 +1,24 @@+//! Shader-source contract tests (compilation itself needs a GL context).+use super::*;++#[test]+fn uniform_name_constants_appear_in_shader_sources() {+ for name in [U_VIEW_PROJ, U_SUN_DIR, U_CAM_POS, U_BONES, U_ALBEDO] {+ assert!(+ VERT_SRC.contains(name) || FRAG_SRC.contains(name),+ "uniform {name} must be declared in a shader"+ );+ }+ assert!(VERT_SRC.starts_with("#version 300 es"), "vert: {}", &VERT_SRC[..30]);+ assert!(FRAG_SRC.starts_with("#version 300 es"), "frag: {}", &FRAG_SRC[..30]);+ // Skinning inputs: joints + weights + bones uniform in the vertex shader.+ assert!(VERT_SRC.contains("uBones"));+ assert!(FRAG_SRC.contains("uAlbedo"));+}++#[test]+fn shader_sources_are_nonempty_and_distinct() {+ assert!(VERT_SRC.len() > 100);+ assert!(FRAG_SRC.len() > 100);+ assert_ne!(VERT_SRC, FRAG_SRC);+}
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 4a9ac71f8d..0e1fa4e351 100644--- a/library/avatar/src/main/rust/src/lib.rs+++ b/library/avatar/src/main/rust/src/lib.rs@@ -205,16 +205,22 @@ fn close_fd(fd: jint) { #[cfg(not(target_os = "android"))] fn close_fd(_fd: jint) {} +/// Pose preset ids as JSON (`["idle","wave",...]`) for the gallery.+fn poses_json() -> String {+ serde_json::to_string(&pose::preset_poses().iter().map(|p| &p.id).collect::<Vec<_>>())+ .unwrap_or_else(|_| "[]".to_string())+}++#[cfg(test)]+mod lib_tests;+ /// 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(- &pose::preset_poses().iter().map(|p| &p.id).collect::<Vec<_>>(),- )- .unwrap_or_else(|_| "[]".to_string());+ let json = poses_json(); env.with_env(|env| -> jni::errors::Result<jstring> { let null = std::ptr::null_mut(); match env.new_string(json) {
library/avatar/src/main/rust/src/lib_tests.rs
diff --git a/library/avatar/src/main/rust/src/lib_tests.rs b/library/avatar/src/main/rust/src/lib_tests.rsnew file mode 100644index 0000000000..48aed0df7b--- /dev/null+++ b/library/avatar/src/main/rust/src/lib_tests.rs@@ -0,0 +1,30 @@+//! Tests for the pure helpers behind the JNI glue in `lib.rs`.+//! The `extern "system"` entry points themselves need a JVM `Env` and are+//! pure JNI glue โ they forward to the engine functions tested elsewhere.+use super::*;++#[test]+fn poses_json_lists_every_preset_id_once() {+ let json = poses_json();+ let ids: Vec<String> = serde_json::from_str(&json).expect("poses json is a string array");+ let expected: Vec<String> = crate::pose::preset_poses()+ .iter()+ .map(|p| p.id.clone())+ .collect();+ assert_eq!(ids, expected);+ assert!(ids.iter().any(|i| i == "idle"));+ assert!(ids.iter().any(|i| i == "wave"));+ let mut dedup = ids.clone();+ dedup.sort();+ dedup.dedup();+ assert_eq!(dedup.len(), ids.len(), "preset ids are unique");+}++#[test]+fn host_read_fd_and_close_fd_are_safe_noops() {+ // Non-Android stub: never fabricates bytes, close is a no-op for any fd.+ assert!(read_fd(-1, 0, 10).is_none());+ assert!(read_fd(0, 0, 10).is_none());+ close_fd(-1);+ close_fd(0);+}
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 4937dfc426..98bde8fc34 100644--- a/library/avatar/src/main/rust/src/renderer.rs+++ b/library/avatar/src/main/rust/src/renderer.rs@@ -8,6 +8,8 @@ use crate::avatar::MAX_BONES; use crate::gles::renderer::GlesRenderer; use crate::mesh::YuuVertex; use crate::vulkan::renderer::YuuRenderer;+#[cfg(test)]+mod renderer_tests; /// Which GPU backend drew the frame. `create_renderer` tries Vulkan first, /// falls back to GLES, and fails only when both fail.
library/avatar/src/main/rust/src/renderer/renderer_tests.rs
diff --git a/library/avatar/src/main/rust/src/renderer/renderer_tests.rs b/library/avatar/src/main/rust/src/renderer/renderer_tests.rsnew file mode 100644index 0000000000..9c00b70db1--- /dev/null+++ b/library/avatar/src/main/rust/src/renderer/renderer_tests.rs@@ -0,0 +1,16 @@+//! Host failure-path tests for the backend dispatch seam.+use super::*;++#[test]+fn vulkan_only_and_select_fail_cleanly_without_a_window_on_host() {+ let r = unsafe { Renderer::try_vulkan_only(std::ptr::null_mut(), 640, 480, 640, 480) };+ assert!(r.is_err(), "Vulkan-only must fail cleanly on host");+ if let Err(e) = r {+ assert!(!e.is_empty(), "error must describe the failure");+ }+ let r = unsafe { Renderer::select(std::ptr::null_mut(), 640, 480, 640, 480) };+ assert!(r.is_err(), "both backends must fail cleanly on host");+ if let Err(e) = r {+ assert!(e.contains("no renderer"), "combined error: {e}");+ }+}
library/avatar/src/main/rust/src/vulkan/buffers.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/buffers.rs b/library/avatar/src/main/rust/src/vulkan/buffers.rsindex 4746357339..2fffe3c715 100644--- a/library/avatar/src/main/rust/src/vulkan/buffers.rs+++ b/library/avatar/src/main/rust/src/vulkan/buffers.rs@@ -9,6 +9,8 @@ use crate::avatar::MAX_BONES; use crate::mesh::YuuVertex; use ash::vk; use std::mem;+#[cfg(test)]+mod buffers_tests; /// One skinned vertex: position + normal + UV + joints + weights. Layout must /// match `yuu_avatar.vert` (locations 0..4).
library/avatar/src/main/rust/src/vulkan/buffers/buffers_tests.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/buffers/buffers_tests.rs b/library/avatar/src/main/rust/src/vulkan/buffers/buffers_tests.rsnew file mode 100644index 0000000000..0bffc7585a--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/buffers/buffers_tests.rs@@ -0,0 +1,64 @@+//! Pure-layout tests for the Vulkan vertex/UBO contract (no device needed).+use super::*;+use crate::mesh::YuuVertex;++#[test]+fn vk_vertex_conversion_copies_every_field() {+ let v = YuuVertex {+ pos: [1.0, 2.0, 3.0],+ normal: [0.0, 1.0, 0.0],+ uv: [0.25, 0.75],+ joints: [1.0, 2.0, 3.0, 0.0],+ weights: [0.5, 0.3, 0.2, 0.0],+ };+ let k = YuuVkVertex::from(&v);+ assert_eq!(k.pos, v.pos);+ assert_eq!(k.normal, v.normal);+ assert_eq!(k.uv, v.uv);+ assert_eq!(k.joints, v.joints);+ assert_eq!(k.weights, v.weights);+ // Default is all-zero (matches a T-posed unweighted vertex before skinning).+ assert_eq!(YuuVkVertex::default().pos, [0.0; 3]);+}++#[test]+fn binding_and_attributes_match_shader_locations() {+ let b = YuuVkVertex::binding_description();+ assert_eq!(b.binding, 0);+ assert_eq!(b.stride as usize, std::mem::size_of::<YuuVkVertex>());+ assert!(b.input_rate == vk::VertexInputRate::VERTEX);+ let attrs = YuuVkVertex::attribute_descriptions();+ assert_eq!(attrs.len(), 5);+ for (i, a) in attrs.iter().enumerate() {+ assert_eq!(a.binding, 0);+ assert_eq!(a.location, i as u32);+ }+ assert!(attrs[0].format == vk::Format::R32G32B32_SFLOAT);+ assert!(attrs[1].format == vk::Format::R32G32B32_SFLOAT);+ assert!(attrs[2].format == vk::Format::R32G32_SFLOAT);+ assert!(attrs[3].format == vk::Format::R32G32B32A32_SFLOAT);+ assert!(attrs[4].format == vk::Format::R32G32B32A32_SFLOAT);+ assert_eq!(attrs[0].offset as usize, std::mem::offset_of!(YuuVkVertex, pos));+ assert_eq!(attrs[1].offset as usize, std::mem::offset_of!(YuuVkVertex, normal));+ assert_eq!(attrs[2].offset as usize, std::mem::offset_of!(YuuVkVertex, uv));+ assert_eq!(attrs[3].offset as usize, std::mem::offset_of!(YuuVkVertex, joints));+ assert_eq!(attrs[4].offset as usize, std::mem::offset_of!(YuuVkVertex, weights));+ // Offsets are strictly increasing (no overlapping attributes).+ assert!(attrs.windows(2).all(|w| w[0].offset < w[1].offset));+}++#[test]+fn ubo_default_is_identity_viewproj_with_documented_defaults() {+ let u = YuuUbo::default();+ assert_eq!(u.view_proj, glam::Mat4::IDENTITY.to_cols_array_2d());+ assert_eq!(u.sun_dir, [0.35, -1.0, 0.45]);+ assert_eq!(u.cam_pos, [0.0, 1.1, 2.6]);+ assert_eq!(u._pad0, 0.0);+ assert_eq!(u._pad1, 0.0);+ assert_eq!(u.bones.len(), MAX_BONES);+ // std140 layout: vec3+pad, vec3+pad, then bones.+ assert_eq!(+ std::mem::size_of::<YuuUbo>(),+ 64 + 16 + 16 + MAX_BONES * 64+ );+}
library/avatar/src/main/rust/src/vulkan/context.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/context.rs b/library/avatar/src/main/rust/src/vulkan/context.rsindex 69e488e710..b2f6a19573 100644--- a/library/avatar/src/main/rust/src/vulkan/context.rs+++ b/library/avatar/src/main/rust/src/vulkan/context.rs@@ -7,6 +7,8 @@ use ash::vk; use ash::Entry; use std::ffi::{CString, c_char}; use std::os::raw::c_void;+#[cfg(test)]+mod context_tests; /// Opaque Android window handle, filled in from the JNI surface. #[repr(C)]
library/avatar/src/main/rust/src/vulkan/context/context_tests.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/context/context_tests.rs b/library/avatar/src/main/rust/src/vulkan/context/context_tests.rsnew file mode 100644index 0000000000..6f0e016fe1--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/context/context_tests.rs@@ -0,0 +1,36 @@+//! Host-side tests for Vulkan bootstrap helpers that need no device.+use super::*;++#[test]+fn required_extensions_are_surface_and_android_surface() {+ let exts = VulkanContext::required_instance_extensions();+ let names: Vec<String> = exts+ .iter()+ .map(|s| s.to_string_lossy().into_owned())+ .collect();+ assert_eq!(names.len(), 2);+ assert!(names.iter().any(|n| n.contains("VK_KHR_surface")), "{names:?}");+ assert!(+ names.iter().any(|n| n.contains("android_surface")),+ "{names:?}"+ );+}++#[test]+fn host_window_stubs_are_null_and_noop() {+ // On non-Android hosts the NDK stubs must never fabricate a window.+ #[cfg(not(target_os = "android"))]+ unsafe {+ assert!(ANativeWindow_fromSurface(std::ptr::null_mut(), std::ptr::null_mut()).is_null());+ ANativeWindow_acquire(std::ptr::null_mut());+ ANativeWindow_release(std::ptr::null_mut());+ }+}++#[test]+fn context_new_fails_cleanly_without_a_window_on_host() {+ // No Vulkan loader / no real ANativeWindow on the host: creation must+ // return Err (for the GLES fallback), never panic or crash.+ let r = unsafe { VulkanContext::new(std::ptr::null_mut(), 640, 480) };+ assert!(r.is_err(), "host without a live window must fail cleanly");+}
library/avatar/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/pipeline.rs b/library/avatar/src/main/rust/src/vulkan/pipeline.rsindex 1c88f420a3..15a0a07b16 100644--- a/library/avatar/src/main/rust/src/vulkan/pipeline.rs+++ b/library/avatar/src/main/rust/src/vulkan/pipeline.rs@@ -11,6 +11,26 @@ use std::ffi::CString; const YUU_VERT_SPV: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/yuu_avatar.vert.spv")); const YUU_FRAG_SPV: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/yuu_avatar.frag.spv")); +/// Convert SPIR-V bytes to aligned words for `create_shader_module`.+///+/// `include_bytes!` is align-1; reinterpreting its bytes as `u32` is UB+/// (misaligned word loads fault on ARM), so copy into an aligned `Vec`+/// first. Trailing bytes of a non-multiple-of-4 input are dropped, as+/// SPIR-V is always a whole number of words.+pub fn spv_words(spv: &[u8]) -> Vec<u32> {+ let mut words = vec![0u32; spv.len().div_ceil(4)];+ if !spv.is_empty() {+ unsafe {+ std::ptr::copy_nonoverlapping(spv.as_ptr(), words.as_mut_ptr() as *mut u8, spv.len());+ }+ }+ words.truncate(spv.len() / 4);+ words+}++#[cfg(test)]+mod pipeline_tests;+ /// Pipeline + layout + the UBO/sampler descriptor set. pub struct Pipelines { /// Pipeline layout (UBO + sampler set).@@ -192,16 +212,9 @@ impl Pipelines { } unsafe fn create_module(device: &ash::Device, spv: &[u8]) -> Result<vk::ShaderModule, String> {- // `include_bytes!` is align-1; `create_shader_module` needs align-4- // words. Copy into an aligned vec first โ reinterpreting the byte- // slice as u32 is UB (misaligned word load faults on ARM).- let mut words = vec![0u32; spv.len().div_ceil(4)];- unsafe {- std::ptr::copy_nonoverlapping(spv.as_ptr(), words.as_mut_ptr() as *mut u8, spv.len());- }- let code_len = spv.len() / 4;+ let words = spv_words(spv); device- .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words[..code_len]), None)+ .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None) .map_err(|e| format!("mod {e:?}")) }
library/avatar/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs b/library/avatar/src/main/rust/src/vulkan/pipeline/pipeline_tests.rsnew file mode 100644index 0000000000..e2e8363236--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs@@ -0,0 +1,27 @@+//! Tests for the SPIR-V word conversion and bundled shader modules.+use super::*;++#[test]+fn spv_words_are_little_endian_aligned_and_drop_trailing_bytes() {+ assert!(spv_words(&[]).is_empty());+ assert_eq!(spv_words(&[0x03, 0x02, 0x23, 0x07]), vec![0x0723_0203]);+ assert_eq!(+ spv_words(&[1, 0, 0, 0, 2, 0, 0, 0]),+ vec![1, 2]+ );+ // Non-multiple-of-4: trailing partial word is dropped (SPIR-V is whole words).+ assert_eq!(spv_words(&[1, 0, 0, 0, 9]), vec![1]);+ assert_eq!(spv_words(&[1, 2, 3]), Vec::<u32>::new());+}++#[test]+fn bundled_spv_modules_start_with_spirv_magic() {+ for spv in [YUU_VERT_SPV, YUU_FRAG_SPV] {+ assert!(!spv.is_empty());+ assert_eq!(spv.len() % 4, 0, "SPIR-V must be whole words");+ let words = spv_words(spv);+ assert_eq!(words[0], 0x0723_0203, "SPIR-V magic number");+ assert_eq!(words.len(), spv.len() / 4);+ }+ assert_ne!(YUU_VERT_SPV, YUU_FRAG_SPV, "vertex and fragment shaders differ");+}
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 fc1afe6f60..f1d7ff4994 100644--- a/library/avatar/src/main/rust/src/vulkan/renderer.rs+++ b/library/avatar/src/main/rust/src/vulkan/renderer.rs@@ -146,3 +146,5 @@ impl YuuRenderer { // files so each file stays under the 500-line Rust limit (same module scope via `include!`). include!("renderer_albedo.rs"); include!("renderer_frame.rs");+#[cfg(test)]+mod renderer_tests;
library/avatar/src/main/rust/src/vulkan/renderer/renderer_tests.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/renderer/renderer_tests.rs b/library/avatar/src/main/rust/src/vulkan/renderer/renderer_tests.rsnew file mode 100644index 0000000000..a7ead06d98--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/renderer/renderer_tests.rs@@ -0,0 +1,13 @@+//! Host failure-path tests for the Vulkan renderer constructor.+use super::*;++#[test]+fn renderer_new_fails_cleanly_without_a_window_on_host() {+ let r = unsafe { YuuRenderer::new(std::ptr::null_mut(), 640, 480, 0, 0) };+ assert!(r.is_err(), "host without Vulkan/window must fail cleanly");+ // Negative / zero window sizes are clamped, still fail cleanly (no panic).+ let r = unsafe { YuuRenderer::new(std::ptr::null_mut(), -5, 0, 0, 0) };+ assert!(r.is_err());+ let r = unsafe { YuuRenderer::new(std::ptr::null_mut(), 1280, 720, 800, 600) };+ assert!(r.is_err());+}
library/avatar/src/main/rust/src/vulkan/swapchain.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/swapchain.rs b/library/avatar/src/main/rust/src/vulkan/swapchain.rsindex ed76dc8fda..0d109d9f74 100644--- a/library/avatar/src/main/rust/src/vulkan/swapchain.rs+++ b/library/avatar/src/main/rust/src/vulkan/swapchain.rs@@ -43,16 +43,73 @@ impl Swapchain { /// rotation_radians): whether width/height swap for the aspect ratio, and /// the clip-space Z rotation to prepend to the view-projection. pub fn pre_rotation(&self) -> (bool, f32) {- use vk::SurfaceTransformFlagsKHR as T;- match self.pre_transform {- t if t == T::ROTATE_90 => (true, std::f32::consts::FRAC_PI_2),- t if t == T::ROTATE_180 => (false, std::f32::consts::PI),- t if t == T::ROTATE_270 => (true, std::f32::consts::FRAC_PI_2 * 3.0),- _ => (false, 0.0),+ pre_rotation_for(self.pre_transform)+ }+}++/// Map a surface pre-transform to (swap_aspect, rotation_radians).+pub fn pre_rotation_for(pre_transform: vk::SurfaceTransformFlagsKHR) -> (bool, f32) {+ use vk::SurfaceTransformFlagsKHR as T;+ match pre_transform {+ t if t == T::ROTATE_90 => (true, std::f32::consts::FRAC_PI_2),+ t if t == T::ROTATE_180 => (false, std::f32::consts::PI),+ t if t == T::ROTATE_270 => (true, std::f32::consts::FRAC_PI_2 * 3.0),+ _ => (false, 0.0),+ }+}+++/// Choose the surface format: prefer B8G8R8A8_UNORM (Pixel gralloc rejects+/// SRGB); if the first format is SRGB, fall back to any UNORM offered.+pub fn choose_format(formats: &[vk::SurfaceFormatKHR]) -> Option<vk::SurfaceFormatKHR> {+ let mut chosen = formats.first().copied()?;+ for fmt in formats {+ if fmt.format == vk::Format::B8G8R8A8_UNORM {+ chosen = *fmt;+ break;+ }+ }+ if chosen.format == vk::Format::B8G8R8A8_SRGB {+ if let Some(&f) = formats.iter().find(|f| {+ f.format == vk::Format::B8G8R8A8_UNORM || f.format == vk::Format::R8G8B8A8_UNORM+ }) {+ chosen = f;+ }+ }+ Some(chosen)+}++/// Choose the present mode: MAILBOX when available, FIFO otherwise.+pub fn choose_present_mode(modes: &[vk::PresentModeKHR]) -> vk::PresentModeKHR {+ if modes.contains(&vk::PresentModeKHR::MAILBOX) {+ vk::PresentModeKHR::MAILBOX+ } else {+ vk::PresentModeKHR::FIFO+ }+}++/// Choose the swapchain extent: the surface's current extent when fixed+/// (width != u32::MAX), else the requested size; always at least 1x1.+pub fn choose_extent(caps: &vk::SurfaceCapabilitiesKHR, width: u32, height: u32) -> vk::Extent2D {+ if caps.current_extent.width == u32::MAX {+ vk::Extent2D { width: width.max(1), height: height.max(1) }+ } else {+ vk::Extent2D {+ width: caps.current_extent.width.max(1),+ height: caps.current_extent.height.max(1), } } } +/// Choose the image count: min+1, capped by max (0 means unbounded, cap 3).+pub fn choose_image_count(caps: &vk::SurfaceCapabilitiesKHR) -> u32 {+ (caps.min_image_count + 1)+ .min(if caps.max_image_count == 0 { 3 } else { caps.max_image_count })+}++#[cfg(test)]+mod swapchain_tests;+ impl Swapchain { /// Create from a live context at `width` x `height`. Fails cleanly. pub fn new(ctx: &VulkanContext, width: u32, height: u32) -> Result<Self, String> {@@ -72,36 +129,10 @@ impl Swapchain { .surface_loader .get_physical_device_surface_present_modes(ctx.physical_device, ctx.surface) .map_err(|e| format!("present_modes {e:?}"))?;- // Fix black screen: Pixel gralloc rejects SRGB 0x3b, prefer B8G8R8A8_UNORM.- let mut chosen_format = formats.first().copied().ok_or("no surface formats")?;- for fmt in &formats {- if fmt.format == vk::Format::B8G8R8A8_UNORM {- chosen_format = *fmt;- break;- }- }- if chosen_format.format == vk::Format::B8G8R8A8_SRGB {- if let Some(&f) = formats.iter().find(|f| {- f.format == vk::Format::B8G8R8A8_UNORM || f.format == vk::Format::R8G8B8A8_UNORM- }) {- chosen_format = f;- }- }- let extent = if caps.current_extent.width == u32::MAX {- vk::Extent2D { width, height }- } else {- vk::Extent2D {- width: caps.current_extent.width.max(1),- height: caps.current_extent.height.max(1),- }- };- let present_mode = if present_modes.contains(&vk::PresentModeKHR::MAILBOX) {- vk::PresentModeKHR::MAILBOX- } else {- vk::PresentModeKHR::FIFO- };- let image_count =- (caps.min_image_count + 1).min(if caps.max_image_count == 0 { 3 } else { caps.max_image_count });+ let chosen_format = choose_format(&formats).ok_or("no surface formats")?;+ let extent = choose_extent(&caps, width, height);+ let present_mode = choose_present_mode(&present_modes);+ let image_count = choose_image_count(&caps); let loader = ash::khr::swapchain::Device::new(&ctx.instance, &ctx.device); let pre_transform = if caps.supported_transforms.contains(vk::SurfaceTransformFlagsKHR::IDENTITY) {
library/avatar/src/main/rust/src/vulkan/swapchain/swapchain_tests.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/swapchain/swapchain_tests.rs b/library/avatar/src/main/rust/src/vulkan/swapchain/swapchain_tests.rsnew file mode 100644index 0000000000..3b72790ed7--- /dev/null+++ b/library/avatar/src/main/rust/src/vulkan/swapchain/swapchain_tests.rs@@ -0,0 +1,63 @@+//! Tests for the surface pre-rotation mapping.+use super::*;+use ash::vk;++#[test]+fn pre_rotation_maps_each_transform() {+ use vk::SurfaceTransformFlagsKHR as T;+ assert_eq!(pre_rotation_for(T::IDENTITY), (false, 0.0));+ assert_eq!(+ pre_rotation_for(T::ROTATE_90),+ (true, std::f32::consts::FRAC_PI_2)+ );+ assert_eq!(pre_rotation_for(T::ROTATE_180), (false, std::f32::consts::PI));+ let (swap, rot) = pre_rotation_for(T::ROTATE_270);+ assert!(swap);+ assert!((rot - std::f32::consts::FRAC_PI_2 * 3.0).abs() < 1e-7);+ // Anything else (mirror etc.) is treated as no rotation.+ assert_eq!(pre_rotation_for(T::HORIZONTAL_MIRROR), (false, 0.0));+ assert_eq!(pre_rotation_for(vk::SurfaceTransformFlagsKHR::empty()), (false, 0.0));+}++fn fmt(f: vk::Format) -> vk::SurfaceFormatKHR {+ vk::SurfaceFormatKHR { format: f, color_space: vk::ColorSpaceKHR::SRGB_NONLINEAR }+}++fn caps(min: u32, max: u32, cur: vk::Extent2D) -> vk::SurfaceCapabilitiesKHR {+ vk::SurfaceCapabilitiesKHR {+ min_image_count: min,+ max_image_count: max,+ current_extent: cur,+ ..Default::default()+ }+}++#[test]+fn choose_format_prefers_unorm_and_avoids_srgb_first() {+ assert!(choose_format(&[]).is_none());+ let srgb_first = [fmt(vk::Format::B8G8R8A8_SRGB), fmt(vk::Format::R8G8B8A8_UNORM)];+ assert!(choose_format(&srgb_first).expect("choice").format == vk::Format::R8G8B8A8_UNORM);+ let with_b8 = [fmt(vk::Format::R8G8B8A8_UNORM), fmt(vk::Format::B8G8R8A8_UNORM)];+ assert!(choose_format(&with_b8).expect("choice").format == vk::Format::B8G8R8A8_UNORM, "B8 is preferred over R8");+ // Only SRGB offered: keep it (only option, no invented format).+ let only_srgb = [fmt(vk::Format::B8G8R8A8_SRGB)];+ assert!(choose_format(&only_srgb).expect("choice").format == vk::Format::B8G8R8A8_SRGB);+ let plain = [fmt(vk::Format::R8G8B8A8_UNORM)];+ assert!(choose_format(&plain).expect("choice").format == vk::Format::R8G8B8A8_UNORM);+}++#[test]+fn choose_present_mode_extent_and_image_count() {+ use vk::PresentModeKHR as M;+ assert!(choose_present_mode(&[M::FIFO, M::MAILBOX]) == M::MAILBOX);+ assert!(choose_present_mode(&[M::FIFO]) == M::FIFO);+ assert!(choose_present_mode(&[]) == M::FIFO);+ let fixed = caps(2, 0, vk::Extent2D { width: 800, height: 600 });+ assert!(choose_extent(&fixed, 1, 1) == vk::Extent2D { width: 800, height: 600 });+ let any = caps(2, 0, vk::Extent2D { width: u32::MAX, height: u32::MAX });+ assert!(choose_extent(&any, 640, 480) == vk::Extent2D { width: 640, height: 480 });+ assert!(choose_extent(&any, 0, 0) == vk::Extent2D { width: 1, height: 1 });+ assert_eq!(choose_image_count(&caps(2, 0, vk::Extent2D::default())), 3);+ assert_eq!(choose_image_count(&caps(1, 2, vk::Extent2D::default())), 2);+ assert_eq!(choose_image_count(&caps(2, 4, vk::Extent2D::default())), 3);+}