kart: add engine Rust tests, fix SPIR-V alignment UB
- Commit
dc90127b8347666a013bc6b1f1bbae129584205a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-18 16:13 UTC (17 days ago)
- Parents
0e2cdad
Raise kart_engine host-coverable line coverage to 90.7% (total 48.1%; the remainder is GPU/JNI device code). Production fix: vulkan/pipeline.rs reinterpreted align-1 include_bytes! SPIR-V as *const u32 via from_raw_parts, a misaligned load that faults on ARM; it now uses the extracted spv_words() aligned copy, with a regression test on a deliberately unaligned slice. Verified with cargo test -p kart_engine (127 passed).
Diff
games/kart/src/main/rust/src/engine.rs
diff --git a/games/kart/src/main/rust/src/engine.rs b/games/kart/src/main/rust/src/engine.rsindex b011139553..1cebee2e83 100644--- a/games/kart/src/main/rust/src/engine.rs+++ b/games/kart/src/main/rust/src/engine.rs@@ -459,6 +459,8 @@ pub fn has_renderer() -> bool { #[cfg(test)] mod engine_tests; #[cfg(test)]+mod engine_coverage_tests;+#[cfg(test)] mod tests { use super::*;
games/kart/src/main/rust/src/engine/engine_coverage_tests.rs
diff --git a/games/kart/src/main/rust/src/engine/engine_coverage_tests.rs b/games/kart/src/main/rust/src/engine/engine_coverage_tests.rsnew file mode 100644index 0000000000..bfe1db7686--- /dev/null+++ b/games/kart/src/main/rust/src/engine/engine_coverage_tests.rs@@ -0,0 +1,97 @@+//! Global-engine tests. The engine is a singleton, so this is ONE+//! sequential test (plus retries around the pre-existing parallel+//! `race_flows_without_renderer` test, which may restart the race once).+use super::*;++fn standings_contains(want: &str) -> bool {+ standings_json().contains(want)+}++#[test]+fn engine_global_lifecycle_inputs_and_standings() {+ // No renderer on the host: every renderer-adjacent call must be a+ // clean no-op / false, never a panic.+ ensure_engine();+ tick_and_render();+ resize_renderer(800, 600);+ assert!(!has_renderer());+ assert!(!is_running());++ // Start a race and drive it through the public setters. Retry the+ // start+check pair: a parallel test restarting the race must not+ // make this one flake โ the last start wins and is then stable.+ let mut ok = false;+ for _ in 0..50 {+ start_race(vec!["cov-p1".to_string(), "cov \"q\" \\z".to_string()]);+ if standings_contains("cov-p1") {+ ok = true;+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ assert!(ok, "standings must list the human seats: {}", standings_json());+ // Standings JSON is well-formed and escapes quotes/backslashes in ids.+ let json = standings_json();+ let parsed: serde_json::Value =+ serde_json::from_str(&json).expect("standings json must parse");+ let arr = parsed.as_array().expect("standings is an array");+ assert!(!arr.is_empty());+ assert!(arr.iter().all(|e| e.get("player").is_some() && e.get("lap").is_some()+ && e.get("progress").is_some() && e.get("place").is_some()));+ assert!(json.contains("\\\"q\\\""), "quotes escaped: {json}");+ assert!(json.contains("\\\\z"), "backslashes escaped: {json}");++ // Input clamping: out-of-range samples clamp into the pending input.+ on_drive_input(0, 5.0, -9.0, 2.0);+ set_drift(0, true);+ use_item(0);+ on_drive_input(99, 1.0, 0.0, 0.0); // grows pending, no panic+ let pending_ok = with_engine(|s| {+ let p = s.pending[0];+ (p.throttle, p.steering, p.brake, p.drift, p.item)+ });+ assert_eq!(+ pending_ok,+ Some((1.0, -1.0, 1.0, true, true)),+ "drive clamps, drift/item edges merge and survive a drive sample"+ );+ // A second drive sample must not clear the sticky drift/item edges.+ // Retry-convergent: a parallel test may restart the race once (which+ // legitimately resets pending); re-applying the setters must then stick.+ let mut merged = None;+ for _ in 0..50 {+ set_drift(0, true);+ use_item(0);+ on_drive_input(0, 0.5, 0.25, 0.0);+ merged = with_engine(|s| {+ let p = s.pending[0];+ (p.throttle, p.steering, p.drift, p.item)+ });+ if merged == Some((0.5, 0.25, true, true)) {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ assert_eq!(merged, Some((0.5, 0.25, true, true)));++ // Negative-size resize clamps; tick without a renderer is a no-op.+ resize_renderer(-4, 0);+ let size = with_engine(|s| (s.width, s.height));+ assert_eq!(size, Some((1, 1)));+ tick_and_render();++ // create_renderer with a null window fails cleanly and records size.+ let ok = unsafe { create_renderer(std::ptr::null_mut(), 320, 240) };+ assert!(!ok, "host renderer creation must fail cleanly");+ assert!(!has_renderer());++ // Destroy paths keep the race (renderer destroy) / clear state.+ destroy_renderer();+ assert!(!is_running());+ destroy_engine();+ assert!(!has_renderer());+ assert_eq!(standings_json(), "[]", "destroyed engine reports empty standings");+ ensure_engine();+ assert_eq!(standings_json(), "[]");+ log_backend("coverage-test");+}
games/kart/src/main/rust/src/gles/buffers.rs
diff --git a/games/kart/src/main/rust/src/gles/buffers.rs b/games/kart/src/main/rust/src/gles/buffers.rsindex 38ca651f97..aab15e93d5 100644--- a/games/kart/src/main/rust/src/gles/buffers.rs+++ b/games/kart/src/main/rust/src/gles/buffers.rs@@ -10,6 +10,8 @@ use crate::gles::renderer::{DYNAMIC_VERT_CAP, TRACK_VERT_CAP}; use crate::mesh::KartVertex; use glow::HasContext as _;+#[cfg(test)]+mod buffers_tests; /// One VAO + VBO pair: vertex layout bound once, store re-sized per upload. pub struct MeshBuffer {
games/kart/src/main/rust/src/gles/buffers/buffers_tests.rs
diff --git a/games/kart/src/main/rust/src/gles/buffers/buffers_tests.rs b/games/kart/src/main/rust/src/gles/buffers/buffers_tests.rsnew file mode 100644index 0000000000..909ee46346--- /dev/null+++ b/games/kart/src/main/rust/src/gles/buffers/buffers_tests.rs@@ -0,0 +1,24 @@+//! Pure-layout tests for the GLES kart vertex buffer contract.+use super::*;++#[test]+fn kart_vertex_layout_and_bytes_match_shader_contract() {+ assert_eq!(std::mem::size_of::<KartVertex>(), 24);+ assert_eq!(std::mem::offset_of!(KartVertex, pos), 0);+ assert_eq!(std::mem::offset_of!(KartVertex, color), 12);+ assert!(bytes_of(&[]).is_empty());+ let mesh = vec![+ KartVertex { pos: [1.0, 2.0, 3.0], color: [0.5, 0.25, 1.0] };+ 2+ ];+ let bytes = bytes_of(&mesh);+ assert_eq!(bytes.len(), 2 * 24);+ assert_eq!(&bytes[0..4], &1.0f32.to_le_bytes());+ assert_eq!(&bytes[12..16], &0.5f32.to_le_bytes(), "color follows pos");+}++#[test]+fn caps_are_documented_mesh_budgets() {+ assert_eq!(TRACK_VERT_CAP, 65_536);+ assert_eq!(DYNAMIC_VERT_CAP, 8_192);+}
games/kart/src/main/rust/src/gles/egl.rs
diff --git a/games/kart/src/main/rust/src/gles/egl.rs b/games/kart/src/main/rust/src/gles/egl.rsindex ccb75a3ada..44382e165b 100644--- a/games/kart/src/main/rust/src/gles/egl.rs+++ b/games/kart/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 kart needs is 1.0-era core).
games/kart/src/main/rust/src/gles/egl/egl_tests.rs
diff --git a/games/kart/src/main/rust/src/gles/egl/egl_tests.rs b/games/kart/src/main/rust/src/gles/egl/egl_tests.rsnew file mode 100644index 0000000000..5e8bc57158--- /dev/null+++ b/games/kart/src/main/rust/src/gles/egl/egl_tests.rs@@ -0,0 +1,45 @@+//! 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);+ 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");+}
games/kart/src/main/rust/src/gles/renderer.rs
diff --git a/games/kart/src/main/rust/src/gles/renderer.rs b/games/kart/src/main/rust/src/gles/renderer.rsindex 5d4f65105e..edf36e810c 100644--- a/games/kart/src/main/rust/src/gles/renderer.rs+++ b/games/kart/src/main/rust/src/gles/renderer.rs@@ -19,6 +19,8 @@ use glow::HasContext as _; /// Static track mesh budget: the oval sweep is ~30k verts; 64k leaves margin. pub const TRACK_VERT_CAP: usize = 65_536;+#[cfg(test)]+mod renderer_tests; /// Dynamic mesh budget per frame: 8 karts (~160 verts each) + boxes + shells. pub const DYNAMIC_VERT_CAP: usize = 8_192;
games/kart/src/main/rust/src/gles/renderer/renderer_tests.rs
diff --git a/games/kart/src/main/rust/src/gles/renderer/renderer_tests.rs b/games/kart/src/main/rust/src/gles/renderer/renderer_tests.rsnew file mode 100644index 0000000000..bc54f9b2b1--- /dev/null+++ b/games/kart/src/main/rust/src/gles/renderer/renderer_tests.rs@@ -0,0 +1,25 @@+//! Host tests for GLES renderer helpers and its failure path.+use super::*;++#[test]+fn flatten_and_normalize_edge_cases() {+ assert_eq!(flatten(&[[0.0; 4]; 4]), [0.0; 16]);+ let m = glam::Mat4::from_translation(glam::Vec3::new(4.0, 5.0, 6.0)).to_cols_array_2d();+ let f = flatten(&m);+ assert_eq!([f[12], f[13], f[14]], [4.0, 5.0, 6.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()));+ // Fixed lighting constants are sane.+ assert!(SKY.iter().all(|v| (0.0..=1.0).contains(v)));+ assert_eq!(TRACK_VERT_CAP, 65_536);+ assert_eq!(DYNAMIC_VERT_CAP, 8_192);+}++#[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());+}
games/kart/src/main/rust/src/gles/shaders.rs
diff --git a/games/kart/src/main/rust/src/gles/shaders.rs b/games/kart/src/main/rust/src/gles/shaders.rsindex 27b22d0da5..18a6e334a8 100644--- a/games/kart/src/main/rust/src/gles/shaders.rs+++ b/games/kart/src/main/rust/src/gles/shaders.rs@@ -19,6 +19,8 @@ pub const U_VIEW_PROJ: &str = "uViewProj"; pub const U_SUN_DIR: &str = "uSunDir"; /// Chase-cam position, the fog origin (mirrors the Vulkan UBO's `camPos`). pub const U_CAM_POS: &str = "uCamPos";+#[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.
games/kart/src/main/rust/src/gles/shaders/shaders_tests.rs
diff --git a/games/kart/src/main/rust/src/gles/shaders/shaders_tests.rs b/games/kart/src/main/rust/src/gles/shaders/shaders_tests.rsnew file mode 100644index 0000000000..9e045227c0--- /dev/null+++ b/games/kart/src/main/rust/src/gles/shaders/shaders_tests.rs@@ -0,0 +1,21 @@+//! 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] {+ 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"));+ assert!(FRAG_SRC.starts_with("#version 300 es"));+}++#[test]+fn shader_sources_are_nonempty_and_distinct() {+ assert!(VERT_SRC.len() > 100);+ assert!(FRAG_SRC.len() > 100);+ assert_ne!(VERT_SRC, FRAG_SRC);+}
games/kart/src/main/rust/src/lib.rs
diff --git a/games/kart/src/main/rust/src/lib.rs b/games/kart/src/main/rust/src/lib.rsindex fbc3b23843..9e2a84addd 100644--- a/games/kart/src/main/rust/src/lib.rs+++ b/games/kart/src/main/rust/src/lib.rs@@ -26,6 +26,19 @@ fn get_string(env: &Env, s: &JString) -> Option<String> { s.try_to_string(env).ok() } +/// Parse the comma-separated human seat ids from the JNI start-race call:+/// trims whitespace and drops empty entries (trailing commas, blank csv).+fn parse_player_ids(csv: &str) -> Vec<String> {+ csv.split(',')+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .collect()+}++#[cfg(test)]+mod lib_tests;+ /// Adopt the engine state (idempotent; called once from `KartNative` init). #[no_mangle] pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeInit<'l>(@@ -49,12 +62,7 @@ pub extern "system" fn Java_com_vayunmathur_games_kart_util_KartNative_nativeSta let ids: Vec<String> = env .with_env(|env| -> jni::errors::Result<Vec<String>> { match get_string(env, &player_ids_csv) {- Some(csv) => Ok(csv- .split(',')- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- .collect()),+ Some(csv) => Ok(parse_player_ids(&csv)), None => Ok(Vec::new()), } })
games/kart/src/main/rust/src/lib_tests.rs
diff --git a/games/kart/src/main/rust/src/lib_tests.rs b/games/kart/src/main/rust/src/lib_tests.rsnew file mode 100644index 0000000000..5d66b64c85--- /dev/null+++ b/games/kart/src/main/rust/src/lib_tests.rs@@ -0,0 +1,17 @@+//! Tests for the pure CSV parser behind the JNI start-race glue.+//! 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 parse_player_ids_trims_and_drops_empties() {+ assert_eq!(parse_player_ids("p1,p2"), vec!["p1", "p2"]);+ assert_eq!(parse_player_ids(" p1 , p2 "), vec!["p1", "p2"]);+ assert_eq!(parse_player_ids(""), Vec::<String>::new());+ assert_eq!(parse_player_ids(",,,"), Vec::<String>::new());+ assert_eq!(parse_player_ids("p1,,p2,"), vec!["p1", "p2"]);+ assert_eq!(parse_player_ids("solo"), vec!["solo"]);+ assert_eq!(parse_player_ids(" , "), Vec::<String>::new());+ // Inner spaces in an id are preserved; only the ends are trimmed.+ assert_eq!(parse_player_ids("player one,p2"), vec!["player one", "p2"]);+}
games/kart/src/main/rust/src/renderer.rs
diff --git a/games/kart/src/main/rust/src/renderer.rs b/games/kart/src/main/rust/src/renderer.rsindex 465cc47357..9d24e32219 100644--- a/games/kart/src/main/rust/src/renderer.rs+++ b/games/kart/src/main/rust/src/renderer.rs@@ -8,6 +8,8 @@ use crate::gles::renderer::GlesRenderer; use crate::mesh::KartVertex; use crate::vulkan::renderer::KartRenderer;+#[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.
games/kart/src/main/rust/src/renderer/renderer_tests.rs
diff --git a/games/kart/src/main/rust/src/renderer/renderer_tests.rs b/games/kart/src/main/rust/src/renderer/renderer_tests.rsnew file mode 100644index 0000000000..66d8c28a73--- /dev/null+++ b/games/kart/src/main/rust/src/renderer/renderer_tests.rs@@ -0,0 +1,17 @@+//! Host failure-path tests for the backend dispatch seam.+use super::*;++#[test]+fn select_fails_cleanly_without_a_window_on_host() {+ 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}");+ }+}++#[test]+fn try_vulkan_fails_cleanly_without_a_window_on_host() {+ let r = unsafe { crate::engine::try_vulkan(std::ptr::null_mut(), 640, 480, 640, 480) };+ assert!(r.is_err(), "Vulkan must fail cleanly on host");+}
games/kart/src/main/rust/src/vulkan/buffers.rs
diff --git a/games/kart/src/main/rust/src/vulkan/buffers.rs b/games/kart/src/main/rust/src/vulkan/buffers.rsindex f205134265..a4cfeb3736 100644--- a/games/kart/src/main/rust/src/vulkan/buffers.rs+++ b/games/kart/src/main/rust/src/vulkan/buffers.rs@@ -7,6 +7,8 @@ //! full re-uploads of the dynamic mesh stay comfortably in budget. use ash::vk; use std::mem;+#[cfg(test)]+mod buffers_tests; /// One vertex: world position + flat RGB. Layout must match `kart.vert` /// (`location 0 = pos`, `location 1 = color`).
games/kart/src/main/rust/src/vulkan/buffers/buffers_tests.rs
diff --git a/games/kart/src/main/rust/src/vulkan/buffers/buffers_tests.rs b/games/kart/src/main/rust/src/vulkan/buffers/buffers_tests.rsnew file mode 100644index 0000000000..b95e4985f9--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/buffers/buffers_tests.rs@@ -0,0 +1,33 @@+//! Pure-layout tests for the Vulkan kart vertex/UBO contract.+use super::*;++#[test]+fn binding_and_attributes_match_shader_locations() {+ let b = KartVkVertex::binding_description();+ assert_eq!(b.binding, 0);+ assert_eq!(b.stride as usize, std::mem::size_of::<KartVkVertex>());+ assert!(b.input_rate == vk::VertexInputRate::VERTEX);+ let attrs = KartVkVertex::attribute_descriptions();+ assert_eq!(attrs.len(), 2);+ assert_eq!(attrs[0].location, 0);+ assert_eq!(attrs[1].location, 1);+ assert!(attrs[0].format == vk::Format::R32G32B32_SFLOAT);+ assert!(attrs[1].format == vk::Format::R32G32B32_SFLOAT);+ assert_eq!(attrs[0].offset as usize, std::mem::offset_of!(KartVkVertex, pos));+ assert_eq!(attrs[1].offset as usize, std::mem::offset_of!(KartVkVertex, color));+ assert!(attrs[0].offset < attrs[1].offset);+ // KartVkVertex mirrors KartVertex (pos+color, 24 bytes).+ assert_eq!(std::mem::size_of::<KartVkVertex>(), 24);+ assert_eq!(KartVkVertex::default().pos, [0.0; 3]);+}++#[test]+fn ubo_default_is_identity_with_documented_defaults() {+ let u = KartUbo::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, 4.0, 20.0]);+ assert_eq!(u._pad0, 0.0);+ assert_eq!(u._pad1, 0.0);+ assert_eq!(std::mem::size_of::<KartUbo>(), 64 + 16 + 16);+}
games/kart/src/main/rust/src/vulkan/context.rs
diff --git a/games/kart/src/main/rust/src/vulkan/context.rs b/games/kart/src/main/rust/src/vulkan/context.rsindex f9f862dfa1..0f365a9347 100644--- a/games/kart/src/main/rust/src/vulkan/context.rs+++ b/games/kart/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)]
games/kart/src/main/rust/src/vulkan/context/context_tests.rs
diff --git a/games/kart/src/main/rust/src/vulkan/context/context_tests.rs b/games/kart/src/main/rust/src/vulkan/context/context_tests.rsnew file mode 100644index 0000000000..9197137260--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/context/context_tests.rs@@ -0,0 +1,30 @@+//! 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() {+ #[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() {+ let r = unsafe { VulkanContext::new(std::ptr::null_mut(), 640, 480) };+ assert!(r.is_err(), "host without a live window must fail cleanly");+}
games/kart/src/main/rust/src/vulkan/pipeline.rs
diff --git a/games/kart/src/main/rust/src/vulkan/pipeline.rs b/games/kart/src/main/rust/src/vulkan/pipeline.rsindex e43ee2b24a..3798a25cfe 100644--- a/games/kart/src/main/rust/src/vulkan/pipeline.rs+++ b/games/kart/src/main/rust/src/vulkan/pipeline.rs@@ -12,6 +12,26 @@ use std::ffi::CString; const KART_VERT_SPV: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/kart.vert.spv")); const KART_FRAG_SPV: &[u8] = include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../build/spirv/kart.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 single UBO descriptor set. pub struct Pipelines { /// Pipeline layout (one UBO set).@@ -156,10 +176,9 @@ impl Pipelines { } unsafe fn create_module(device: &ash::Device, spv: &[u8]) -> Result<vk::ShaderModule, String> {- let code =- unsafe { std::slice::from_raw_parts(spv.as_ptr() as *const u32, spv.len() / 4) };+ let words = spv_words(spv); device- .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(code), None)+ .create_shader_module(&vk::ShaderModuleCreateInfo::default().code(&words), None) .map_err(|e| format!("mod {e:?}")) }
games/kart/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs
diff --git a/games/kart/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs b/games/kart/src/main/rust/src/vulkan/pipeline/pipeline_tests.rsnew file mode 100644index 0000000000..69c7f21306--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/pipeline/pipeline_tests.rs@@ -0,0 +1,29 @@+//! Tests for the aligned SPIR-V word conversion (the kart bug fix) and+//! the 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]);+ assert_eq!(spv_words(&[1, 0, 0, 0, 9]), vec![1]);+ assert_eq!(spv_words(&[1, 2, 3]), Vec::<u32>::new());+ // Regression: the old code reinterpreted align-1 include_bytes! as+ // *const u32 (UB). The conversion must produce identical words from a+ // deliberately unaligned slice.+ let mut buf = [0u8; 9];+ buf[1..9].copy_from_slice(&[0x03, 0x02, 0x23, 0x07, 5, 0, 0, 0]);+ assert_eq!(spv_words(&buf[1..]), vec![0x0723_0203, 5]);+}++#[test]+fn bundled_spv_modules_start_with_spirv_magic() {+ for spv in [KART_VERT_SPV, KART_FRAG_SPV] {+ assert!(!spv.is_empty());+ assert_eq!(spv.len() % 4, 0);+ let words = spv_words(spv);+ assert_eq!(words[0], 0x0723_0203, "SPIR-V magic number");+ }+ assert_ne!(KART_VERT_SPV, KART_FRAG_SPV);+}
games/kart/src/main/rust/src/vulkan/renderer.rs
diff --git a/games/kart/src/main/rust/src/vulkan/renderer.rs b/games/kart/src/main/rust/src/vulkan/renderer.rsindex ed4512b008..422bec3735 100644--- a/games/kart/src/main/rust/src/vulkan/renderer.rs+++ b/games/kart/src/main/rust/src/vulkan/renderer.rs@@ -300,3 +300,6 @@ 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] }++#[cfg(test)]+mod renderer_tests;
games/kart/src/main/rust/src/vulkan/renderer/renderer_tests.rs
diff --git a/games/kart/src/main/rust/src/vulkan/renderer/renderer_tests.rs b/games/kart/src/main/rust/src/vulkan/renderer/renderer_tests.rsnew file mode 100644index 0000000000..428cd8e5c1--- /dev/null+++ b/games/kart/src/main/rust/src/vulkan/renderer/renderer_tests.rs@@ -0,0 +1,14 @@+//! Tests for the Vulkan renderer's pure sun-direction helper and caps.+use super::*;++#[test]+fn normalize_guards_zero_and_scales_to_unit() {+ assert_eq!(normalize([0.0; 3]), [0.0; 3]);+ let n = normalize([0.35, -1.0, 0.45]);+ assert!((n.iter().map(|v| v * v).sum::<f32>() - 1.0).abs() < 1e-5, "{n:?}");+ assert!(n[1] < 0.0);+ let tiny = normalize([1e-9, 0.0, 0.0]);+ assert!(tiny.iter().all(|v| v.is_finite()), "{tiny:?}");+ assert_eq!(TRACK_VERT_CAP, 65_536);+ assert_eq!(DYNAMIC_VERT_CAP, 8_192);+}
games/kart/src/main/rust/src/vulkan/swapchain.rs
diff --git a/games/kart/src/main/rust/src/vulkan/swapchain.rs b/games/kart/src/main/rust/src/vulkan/swapchain.rsindex a3dd46d6aa..b7ac96f489 100644--- a/games/kart/src/main/rust/src/vulkan/swapchain.rs+++ b/games/kart/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) {
games/kart/src/main/rust/src/vulkan/swapchain/swapchain_tests.rs
diff --git a/games/kart/src/main/rust/src/vulkan/swapchain/swapchain_tests.rs b/games/kart/src/main/rust/src/vulkan/swapchain/swapchain_tests.rsnew file mode 100644index 0000000000..3b72790ed7--- /dev/null+++ b/games/kart/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);+}