Modern Apps git

← Modern-Apps.git

kart_engine: fix clippy warnings

Commit
ce71eadef3383e3fdfabfbf2f3fa59e004495168
Author
Vayun Mathur <[email protected]>
When
2026-11-17 14:09 UTC (18 days ago)
Parents
6b00468
Fix all cargo check and clippy warnings in the kart_engine crate
(games/kart/src/main/rust/): 0 check warnings and 31 clippy
warnings at baseline (counted once; the lib-test target repeats
them).

Autofixes applied via cargo clippy --fix and reviewed:
size_of_val for the GLES vertex byte slice, needless borrows in
mesh building, and first() instead of get(0) in swapchain format
selection.

Manual fixes:
- Add # Safety docs to the 14 unsafe functions that lacked them
  (Vulkan buffers/context/pipeline/renderer, host ANativeWindow
  stubs, and the GLES program compile entry point).
- Group box_at arguments into center/size arrays and introduce
  KartMeshSpec for build_kart_mesh, clearing too_many_arguments
  without any allow attribute; callers and tests updated.
- Box both Renderer variants (Vulkan and GLES) to clear
  large_enum_variant; construction sites updated.
- Reword the vulkan/pipeline module doc to clear the doc
  list-continuation warnings.

No crate-level allow blankets were added.

Verified with PATH=$HOME/.cargo/bin:$PATH:
cargo check -p kart_engine --all-targets (0 crate warnings),
cargo clippy -p kart_engine --all-targets (0 crate warnings;
only the pre-existing workspace profile warnings remain), and
cargo test -p kart_engine (29 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 8ac60d26d7..10783ed823 100644--- a/games/kart/src/main/rust/src/engine.rs+++ b/games/kart/src/main/rust/src/engine.rs@@ -215,7 +215,7 @@ pub(crate) unsafe fn try_vulkan(         Err(e) => return Err(format!("context: {e}")),     };     match unsafe { KartRenderer::new(ctx, state_width, state_height) } {-        Ok(r) => Ok(Renderer::Vulkan(r)),+        Ok(r) => Ok(Renderer::Vulkan(Box::new(r))),         Err(e) => Err(format!("renderer: {e}")),     } }@@ -285,7 +285,7 @@ pub fn resize_renderer(width: i32, height: i32) {             };             match unsafe { KartRenderer::new(ctx, state.width, state.height) } {                 Ok(fresh) => {-                    let mut fresh = Renderer::Vulkan(fresh);+                    let mut fresh = Renderer::Vulkan(Box::new(fresh));                     let mesh = mesh::build_track_mesh();                     state.track_count = mesh.len();                     unsafe { fresh.upload_track(&mesh) };@@ -369,7 +369,18 @@ pub fn tick_and_render() {         // Dynamic mesh: karts + shells + boxes.         let mut dynamic: Vec<KartVertex> = Vec::new();         for (seat, (x, z, yaw, ai)) in race.kart_transforms().iter().enumerate() {-            mesh::build_kart_mesh(&mut dynamic, *x, *z, *yaw, seat, *ai, 0.0, false);+            mesh::build_kart_mesh(+                &mut dynamic,+                mesh::KartMeshSpec {+                    x: *x,+                    z: *z,+                    yaw: *yaw,+                    seat,+                    ai: *ai,+                    spin: 0.0,+                    boost: false,+                },+            );         }         for (x, z) in race.shell_positions() {             mesh::build_shell_mesh(&mut dynamic, x, z, race.ticks);
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 6e482f542f..38ca651f97 100644--- a/games/kart/src/main/rust/src/gles/buffers.rs+++ b/games/kart/src/main/rust/src/gles/buffers.rs@@ -10,7 +10,6 @@ use crate::gles::renderer::{DYNAMIC_VERT_CAP, TRACK_VERT_CAP}; use crate::mesh::KartVertex; use glow::HasContext as _;-use std::mem;  /// One VAO + VBO pair: vertex layout bound once, store re-sized per upload. pub struct MeshBuffer {@@ -98,7 +97,7 @@ fn bytes_of(mesh: &[KartVertex]) -> &[u8] {     unsafe {         std::slice::from_raw_parts(             mesh.as_ptr() as *const u8,-            mesh.len() * mem::size_of::<KartVertex>(),+            std::mem::size_of_val(mesh),         )     } }
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 02fc571bdd..27b22d0da5 100644--- a/games/kart/src/main/rust/src/gles/shaders.rs+++ b/games/kart/src/main/rust/src/gles/shaders.rs@@ -22,6 +22,9 @@ pub const U_CAM_POS: &str = "uCamPos";  /// Compile `VERT_SRC` + `FRAG_SRC`, link, return the program. On any failure /// the returned string carries the shader/program info log from the driver.+///+/// # Safety+/// The EGL context must be current on this thread. pub unsafe fn compile_program(gl: &glow::Context) -> Result<glow::Program, String> {     // Prove the linker itself survives on this driver before feeding it the     // real shaders: some Mali revisions SIGSEGV inside glLinkProgram on
games/kart/src/main/rust/src/mesh.rs
diff --git a/games/kart/src/main/rust/src/mesh.rs b/games/kart/src/main/rust/src/mesh.rsindex 87ff28f6c0..09014654e3 100644--- a/games/kart/src/main/rust/src/mesh.rs+++ b/games/kart/src/main/rust/src/mesh.rs@@ -72,8 +72,11 @@ fn quad(     } } -/// Push an axis-aligned box centred at (`x`, `y`, `z`) into `out`.-fn box_at(out: &mut Vec<KartVertex>, x: f32, y: f32, z: f32, sx: f32, sy: f32, sz: f32, color: [f32; 3]) {+/// Push an axis-aligned box into `out`: `center` is the bottom-centre+/// ([x, y, z]) and `size` the full extents ([sx, sy, sz]).+fn box_at(out: &mut Vec<KartVertex>, center: [f32; 3], size: [f32; 3], color: [f32; 3]) {+    let (x, y, z) = (center[0], center[1], center[2]);+    let (sx, sy, sz) = (size[0], size[1], size[2]);     let x0 = x - sx / 2.0;     let x1 = x + sx / 2.0;     let y0 = y;@@ -188,18 +191,28 @@ pub fn build_track_mesh() -> Vec<KartVertex> {     out } -/// Build one kart mesh at (`x`, `z`, `yaw`) with seat color `seat`.-/// `spin` rotates the body (item-hit feedback); `boost` stretches it slightly.-pub fn build_kart_mesh(-    mut out: &mut Vec<KartVertex>,-    x: f32,-    z: f32,-    yaw: f32,-    seat: usize,-    ai: bool,-    spin: f32,-    boost: bool,-) {+/// Placement and identity for one kart in [`build_kart_mesh`].+#[derive(Clone, Copy, Debug)]+pub struct KartMeshSpec {+    /// World X of the kart centre.+    pub x: f32,+    /// World Z of the kart centre.+    pub z: f32,+    /// Heading in radians.+    pub yaw: f32,+    /// Seat index (selects the body colour).+    pub seat: usize,+    /// AI karts use a darkened body colour.+    pub ai: bool,+    /// Extra rotation in radians (item-hit feedback).+    pub spin: f32,+    /// Stretch the body slightly (boost feedback).+    pub boost: bool,+}++/// Build one kart mesh from `spec` into `out`.+pub fn build_kart_mesh(out: &mut Vec<KartVertex>, spec: KartMeshSpec) {+    let KartMeshSpec { x, z, yaw, seat, ai, spin, boost } = spec;     let mut color = KART_COLORS[seat % KART_COLORS.len()];     if ai {         color = darken(color, AI_DARKEN);@@ -228,11 +241,11 @@ pub fn build_kart_mesh(         put(-hx, y0 + 0.55, hz),         put(hx, y0 + 0.55, hz),     ];-    quad(&mut out, top[0], top[1], top[2], top[3], body);-    quad(&mut out, corners[2], corners[3], top[2], top[3], darken(body, 0.9));-    quad(&mut out, corners[1], corners[0], top[1], top[0], darken(body, 0.85));-    quad(&mut out, corners[0], corners[2], top[0], top[2], darken(body, 0.75));-    quad(&mut out, corners[3], corners[1], top[3], top[1], darken(body, 0.75));+    quad(out, top[0], top[1], top[2], top[3], body);+    quad(out, corners[2], corners[3], top[2], top[3], darken(body, 0.9));+    quad(out, corners[1], corners[0], top[1], top[0], darken(body, 0.85));+    quad(out, corners[0], corners[2], top[0], top[2], darken(body, 0.75));+    quad(out, corners[3], corners[1], top[3], top[1], darken(body, 0.75));     // Cabin: smaller darker box on top.     let cabin = darken(color, 0.6);     let (cx, cz) = (1.0 / 2.0, 1.1 / 2.0);@@ -248,14 +261,14 @@ pub fn build_kart_mesh(         put(-cx, y0 + 1.15, cz),         put(cx, y0 + 1.15, cz),     ];-    quad(&mut out, ct[0], ct[1], ct[2], ct[3], cabin);-    quad(&mut out, cc[0], cc[2], ct[0], ct[2], darken(cabin, 0.85));-    quad(&mut out, cc[3], cc[1], ct[3], ct[1], darken(cabin, 0.85));+    quad(out, ct[0], ct[1], ct[2], ct[3], cabin);+    quad(out, cc[0], cc[2], ct[0], ct[2], darken(cabin, 0.85));+    quad(out, cc[3], cc[1], ct[3], ct[1], darken(cabin, 0.85));     // Wheels: four dark boxes.     let wheel = [0.10, 0.10, 0.10];     for (wx, wz) in [(-0.85, -0.85), (0.85, -0.85), (-0.85, 0.85), (0.85, 0.85)] {         let c = put(wx, 0.0, wz * stretch);-        box_at(&mut out, c[0], c[1], c[2], 0.42, 0.5, 0.42, wheel);+        box_at(out, c, [0.42, 0.5, 0.42], wheel);     }     let _ = corners; }@@ -263,13 +276,13 @@ pub fn build_kart_mesh( /// Build one item box marker (floating cube, bobbed by `ticks`). pub fn build_box_mesh(out: &mut Vec<KartVertex>, x: f32, z: f32, ticks: u64) {     let bob = 0.9 + 0.25 * ((ticks as f32 / 30.0).sin());-    box_at(out, x, bob, z, 1.2, 1.2, 1.2, BOX_COLOR);+    box_at(out, [x, bob, z], [1.2, 1.2, 1.2], BOX_COLOR); }  /// Build one shell marker (low spinning tetra-ish box). pub fn build_shell_mesh(out: &mut Vec<KartVertex>, x: f32, z: f32, ticks: u64) {     let _ = ticks;-    box_at(out, x, 0.35, z, 0.9, 0.7, 0.9, SHELL_COLOR);+    box_at(out, [x, 0.35, z], [0.9, 0.7, 0.9], SHELL_COLOR); }  #[cfg(test)]@@ -288,7 +301,10 @@ mod tests {     #[test]     fn kart_mesh_has_body_cabin_wheels() {         let mut out = Vec::new();-        build_kart_mesh(&mut out, 0.0, 0.0, 0.0, 0, false, 0.0, false);+        build_kart_mesh(+            &mut out,+            KartMeshSpec { x: 0.0, z: 0.0, yaw: 0.0, seat: 0, ai: false, spin: 0.0, boost: false },+        );         // Body top (6) + front/back/sides (24) + cabin (12) + 4 wheels (4x30).         assert!(out.len() >= 100, "verts={}", out.len());     }
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 c2f68d72de..465cc47357 100644--- a/games/kart/src/main/rust/src/renderer.rs+++ b/games/kart/src/main/rust/src/renderer.rs@@ -13,9 +13,11 @@ use crate::vulkan::renderer::KartRenderer; /// falls back to GLES, and fails only when both fail. pub enum Renderer {     /// Vulkan path (`ash` loaded): instance + swapchain + pipeline.-    Vulkan(KartRenderer),+    /// Boxed so the enum stays pointer-sized (both renderers are large).+    Vulkan(Box<KartRenderer>),     /// GLES 3.0 path (`glow` + `khronos-egl`): EGL surface + GL program.-    Gles(GlesRenderer),+    /// Boxed for the same reason as the Vulkan variant.+    Gles(Box<GlesRenderer>), }  impl Renderer {@@ -114,7 +116,7 @@ impl Renderer {             match unsafe { GlesRenderer::new(window, state_width, state_height) } {                 Ok(r) => {                     crate::engine::log_backend("GLES");-                    Ok(Self::Gles(r))+                    Ok(Self::Gles(Box::new(r)))                 }                 Err(gles_err) => {                     match crate::engine::try_vulkan(window, width, height, state_width, state_height)@@ -145,7 +147,7 @@ impl Renderer {                             crate::engine::log_backend(&format!(                                 "GLES (Vulkan init failed: {vulkan_err})"                             ));-                            Ok(Self::Gles(r))+                            Ok(Self::Gles(Box::new(r)))                         }                         Err(gles_err) => Err(format!(                             "no renderer (Vulkan: {vulkan_err}; GLES: {gles_err})"
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 05a5c68488..f205134265 100644--- a/games/kart/src/main/rust/src/vulkan/buffers.rs+++ b/games/kart/src/main/rust/src/vulkan/buffers.rs@@ -86,6 +86,10 @@ pub struct AllocatedBuffer {  impl AllocatedBuffer {     /// Allocate host-visible coherent memory and bind it. Fails cleanly.+    ///+    /// # Safety+    /// `instance`, `device`, and `phys` must be valid handles from a live+    /// Vulkan context that outlives the returned buffer.     pub unsafe fn new(         instance: &ash::Instance,         device: &ash::Device,@@ -125,6 +129,10 @@ impl AllocatedBuffer {     }      /// Map, copy, unmap. Empty uploads are a no-op.+    ///+    /// # Safety+    /// `device` must be the device that created this buffer, and the buffer+    /// memory must not be in use by the GPU. Render thread only.     pub unsafe fn upload(&self, device: &ash::Device, data: &[u8]) {         if data.is_empty() {             return;@@ -142,6 +150,10 @@ impl AllocatedBuffer {     }      /// Free memory + buffer.+    ///+    /// # Safety+    /// `device` must be the device that created this buffer; the buffer+    /// must not be in use by the GPU and must not be destroyed twice.     pub unsafe fn destroy(&mut self, device: &ash::Device) {         device.destroy_buffer(self.buffer, None);         device.free_memory(self.memory, None);
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 4ae7a22530..f9f862dfa1 100644--- a/games/kart/src/main/rust/src/vulkan/context.rs+++ b/games/kart/src/main/rust/src/vulkan/context.rs@@ -22,14 +22,27 @@ extern "C" {     pub fn ANativeWindow_release(window: *mut ANativeWindow); } +/// Host stub for the NDK function (returns null).+///+/// # Safety+/// The pointers are ignored; callers must not use the returned null+/// window as a real `ANativeWindow`. #[cfg(not(target_os = "android"))] #[allow(non_snake_case)] pub unsafe fn ANativeWindow_fromSurface(_env: *mut c_void, _surface: *mut c_void) -> *mut ANativeWindow {     std::ptr::null_mut() }+/// Host stub for the NDK function (no-op).+///+/// # Safety+/// The pointer is ignored. #[cfg(not(target_os = "android"))] #[allow(non_snake_case)] pub unsafe fn ANativeWindow_acquire(_window: *mut ANativeWindow) {}+/// Host stub for the NDK function (no-op).+///+/// # Safety+/// The pointer is ignored. #[cfg(not(target_os = "android"))] #[allow(non_snake_case)] pub unsafe fn ANativeWindow_release(_window: *mut ANativeWindow) {}@@ -61,6 +74,10 @@ pub struct VulkanContext { impl VulkanContext {     /// Create everything from a live `ANativeWindow`. Fails cleanly (the     /// caller logs and keeps the placeholder) rather than panicking.+    ///+    /// # Safety+    /// `window` must be a live `ANativeWindow` adopted from the JNI+    /// surface; ownership stays with the caller. Render thread only.     pub unsafe fn new(window: *mut ANativeWindow, _width: i32, _height: i32) -> Result<Self, String> {         let entry = unsafe { Entry::load().map_err(|e| format!("Entry::load failed: {e:?}"))? };         let app_name = CString::new("Kart").unwrap();
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 93706a1264..e43ee2b24a 100644--- a/games/kart/src/main/rust/src/vulkan/pipeline.rs+++ b/games/kart/src/main/rust/src/vulkan/pipeline.rs@@ -1,10 +1,11 @@ //! Graphics pipeline: one unlit vertex-color pipeline for the whole world. //!-//! The kart shader takes per-vertex colors and a single UBO (view-projection-//! + sun + camera), so one descriptor set with one uniform buffer is the-//! entire layout — no samplers, no atlases. Culling is off: the shader's-//! Vulkan Y flip inverts winding (same fix as games/voxels, where BACK-//! culled everything to black).+//! The kart shader takes per-vertex colors and a single UBO+//! (view-projection, sun, and camera), so one descriptor set with one+//! uniform buffer is the entire layout: no samplers, no atlases.+//!+//! Culling is off: the shader's Vulkan Y flip inverts winding (the same+//! fix as games/voxels, where BACK culled everything to black). use ash::vk; use std::ffi::CString; @@ -27,6 +28,10 @@ pub struct Pipelines {  impl Pipelines {     /// Build against the swapchain's render pass, binding `ubo_buffer`.+    ///+    /// # Safety+    /// `device`, `render_pass`, and `ubo_buffer` must be valid handles+    /// from a live Vulkan context that outlives the returned pipelines.     pub unsafe fn new(         device: &ash::Device,         render_pass: vk::RenderPass,@@ -159,6 +164,10 @@ impl Pipelines {     }      /// Free pipeline, layout, pool, set layout.+    ///+    /// # Safety+    /// `device` must be the device that created these objects; they must+    /// not be in use by the GPU and must not be destroyed twice.     pub unsafe fn destroy(&mut self, device: &ash::Device) {         device.destroy_pipeline(self.pipeline, None);         device.destroy_pipeline_layout(self.layout, None);
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 330b92dfd6..ed4512b008 100644--- a/games/kart/src/main/rust/src/vulkan/renderer.rs+++ b/games/kart/src/main/rust/src/vulkan/renderer.rs@@ -50,6 +50,10 @@ pub struct KartRenderer {  impl KartRenderer {     /// Create from a live window at `width` x `height`. Fails cleanly.+    ///+    /// # Safety+    /// `ctx` must come from a live `ANativeWindow` (see+    /// [`VulkanContext::new`]); render thread only.     pub unsafe fn new(         ctx: VulkanContext,         width: u32,@@ -119,6 +123,10 @@ impl KartRenderer {     }      /// Upload the static track mesh (once per race; capped at the budget).+    ///+    /// # Safety+    /// Must be called on the render thread while this renderer's device+    /// is live and its buffers are not in use by the GPU.     pub unsafe fn upload_track(&self, mesh: &[KartVertex]) {         let n = mesh.len().min(TRACK_VERT_CAP);         let bytes = unsafe {@@ -134,6 +142,10 @@ impl KartRenderer {      /// Draw one frame: upload UBO + dynamic mesh, record, submit, present.     /// `track_count` is the vertex count from the last [`Self::upload_track`].+    ///+    /// # Safety+    /// Must be called on the render thread while this renderer's device+    /// and swapchain are live.     #[allow(clippy::too_many_arguments)]     pub unsafe fn draw(         &mut self,@@ -265,6 +277,10 @@ impl KartRenderer {     }      /// Free everything except the context (the engine releases the window).+    ///+    /// # Safety+    /// Must be called on the render thread that owns this renderer, at+    /// most once.     pub unsafe fn destroy(&mut self) {         let device = &self.ctx.device;         device.device_wait_idle().ok();
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 94ffa356f4..a3dd46d6aa 100644--- a/games/kart/src/main/rust/src/vulkan/swapchain.rs+++ b/games/kart/src/main/rust/src/vulkan/swapchain.rs@@ -73,7 +73,7 @@ impl Swapchain {             .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.get(0).copied().ok_or("no surface formats")?;+        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;