Modern Apps git

← Modern-Apps.git

yuu_avatar: fix clippy warnings

Commit
6d8662b6d0d04df55c978446e2669f30e515f22e
Author
Vayun Mathur <[email protected]>
When
2026-11-17 14:11 UTC (18 days ago)
Parents
ce71ead
Fix all cargo check and clippy warnings in the yuu_avatar crate
(library/avatar/src/main/rust/): 1 check warning and 23 clippy
warnings at baseline in the lib target (26 in the lib-test
target, which adds the 3 test-only warnings).

Autofixes applied via cargo clippy --fix and reviewed:
values_mut() for surface teardown iteration, size_of_val for
the GLES vertex byte slice, and first() instead of get(0) in
swapchain format selection.

Manual fixes:
- Add # Safety docs to the 15 unsafe functions that lacked
  them (Vulkan buffers/context/pipeline/renderer_frame, host
  ANativeWindow stubs, and the GLES program compile entry).
- Make OrbitPrefs pub, clearing the private_interfaces check
  warning on Engine::orbit.
- Initialise test YuuTraits values in struct literals instead
  of field assignment after Default::default().
- Name the rounded-box grid type (RoundedGrid) to clear
  type_complexity, and iterate with enumerate().skip(1) to
  clear the range-loop index warning.
- Box both Renderer variants (Vulkan and GLES) to clear
  large_enum_variant; construction sites updated.
- Turn the atlas mole/wrinkle/blush doc line into its own
  paragraph, clearing the doc list-continuation warning.

No crate-level allow blankets were added.

Verified with PATH=$HOME/.cargo/bin:$PATH:
cargo check -p yuu_avatar --all-targets (0 crate warnings),
cargo clippy -p yuu_avatar --all-targets (0 crate warnings;
only the pre-existing workspace profile warnings remain), and
cargo test -p yuu_avatar (21 passed).

Diff

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.rsindex 5e6efbde30..37c0638152 100644--- a/library/avatar/src/main/rust/src/atlas.rs+++ b/library/avatar/src/main/rust/src/atlas.rs@@ -135,7 +135,9 @@ fn fill_ellipse( /// - 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 brow-row spare cells when nonzero.+///+/// Mole/wrinkle/blush are overlaid on the brow-row spare cells when+/// nonzero. pub fn generate_atlas(traits: &YuuTraits) -> Vec<u8> {     let skin = {         let rgb = traits.skin_rgb();@@ -304,9 +306,7 @@ mod tests {     #[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 varied = YuuTraits { eye_style: 7, mouth_style: 9, ..Default::default() };         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 d15a2fd4aa..639f80c011 100644--- a/library/avatar/src/main/rust/src/engine.rs+++ b/library/avatar/src/main/rust/src/engine.rs@@ -85,7 +85,7 @@ impl SurfaceState { /// User orbit preference: survives surface removal (rotation) so the editor /// keeps its drag position and auto-rotate opt-out. #[derive(Clone, Copy, Debug)]-struct OrbitPrefs {+pub struct OrbitPrefs {     yaw: f32,     pitch: f32,     auto_rotate: bool,
library/avatar/src/main/rust/src/engine_lifecycle.rs
diff --git a/library/avatar/src/main/rust/src/engine_lifecycle.rs b/library/avatar/src/main/rust/src/engine_lifecycle.rsindex a031687960..ea689c8175 100644--- a/library/avatar/src/main/rust/src/engine_lifecycle.rs+++ b/library/avatar/src/main/rust/src/engine_lifecycle.rs@@ -45,7 +45,7 @@ pub fn generation(surface_id: i32) -> u64 { /// Destroy everything. pub fn destroy_engine() {     if let Ok(mut eng) = engine().lock() {-        for (_, state) in eng.surfaces.iter_mut() {+        for state in eng.surfaces.values_mut() {             if let Some(mut renderer) = state.renderer.take() {                 unsafe { renderer.destroy() };             }
library/avatar/src/main/rust/src/gles/buffers.rs
diff --git a/library/avatar/src/main/rust/src/gles/buffers.rs b/library/avatar/src/main/rust/src/gles/buffers.rsindex 2f696dcf9e..e5810138f5 100644--- a/library/avatar/src/main/rust/src/gles/buffers.rs+++ b/library/avatar/src/main/rust/src/gles/buffers.rs@@ -113,7 +113,7 @@ fn bytes_of(mesh: &[YuuVertex]) -> &[u8] {     unsafe {         std::slice::from_raw_parts(             mesh.as_ptr() as *const u8,-            mesh.len() * mem::size_of::<YuuVertex>(),+            std::mem::size_of_val(mesh),         )     } }
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 fbe9284d13..d2824d298d 100644--- a/library/avatar/src/main/rust/src/gles/shaders.rs+++ b/library/avatar/src/main/rust/src/gles/shaders.rs@@ -26,6 +26,9 @@ pub const U_ALBEDO: &str = "uAlbedo";  /// 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
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 8ec780ee98..c5455e3ebe 100644--- a/library/avatar/src/main/rust/src/mesh.rs+++ b/library/avatar/src/main/rust/src/mesh.rs@@ -181,10 +181,12 @@ mod tests {         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 traits = YuuTraits {+            mole_style: 1,+            wrinkle_style: 2,+            blush_style: 3,+            ..Default::default()+        };         let mesh = build_avatar_mesh(&traits);         // 24 band verts + mole 6 + wrinkle 6 + blush 12.         let face_count = mesh.iter().filter(is_decal).count();
library/avatar/src/main/rust/src/mesh_attachments.rs
diff --git a/library/avatar/src/main/rust/src/mesh_attachments.rs b/library/avatar/src/main/rust/src/mesh_attachments.rsindex 9379e69bb2..e25be4b6f0 100644--- a/library/avatar/src/main/rust/src/mesh_attachments.rs+++ b/library/avatar/src/main/rust/src/mesh_attachments.rs@@ -248,8 +248,7 @@ mod pack_tests {         assert_eq!(base.len(), 3);         assert!(max_y(&base) < 1.5);         // hairStyle 3 → hair_03 joins the assembly.-        let mut t = YuuTraits::default();-        t.hair_style = 3;+        let mut t = YuuTraits { hair_style: 3, ..Default::default() };         let hairy = assemble_pack(&pack, &t).expect("assemble");         assert_eq!(hairy.len(), 6);         assert!(max_y(&hairy) > 1.5);
library/avatar/src/main/rust/src/mesh_procedural.rs
diff --git a/library/avatar/src/main/rust/src/mesh_procedural.rs b/library/avatar/src/main/rust/src/mesh_procedural.rsindex c8696deb9b..b0ea1dacf5 100644--- a/library/avatar/src/main/rust/src/mesh_procedural.rs+++ b/library/avatar/src/main/rust/src/mesh_procedural.rs@@ -3,6 +3,9 @@ // Split out of `mesh.rs` so each file stays under the 500-line Rust limit. // Same module scope via `mesh.rs` (`include!`), so item order is irrelevant. +/// One rounded-box face grid: rows of (rounded position, normal, UV).+type RoundedGrid = Vec<Vec<([f32; 3], [f32; 3], [f32; 2])>>;+ /// Push a rounded axis-aligned box as skinned triangles into `out`. /// /// Same `Part` contract as the old sharp box (centers/sizes, joint/blend,@@ -41,7 +44,7 @@ fn box_skinned(out: &mut Vec<YuuVertex>, part: &Part) {     let s = ROUND_SUBDIV;     for (corners, face_uv) in faces {         // Bilinear grid over the quad, storing (rounded pos, smooth normal, uv).-        let mut grid: Vec<Vec<([f32; 3], [f32; 3], [f32; 2])>> = Vec::with_capacity(s + 1);+        let mut grid: RoundedGrid = Vec::with_capacity(s + 1);         for iy in 0..=s {             let v = iy as f32 / s as f32;             let mut row = Vec::with_capacity(s + 1);@@ -116,9 +119,9 @@ fn rounded_normal_from_offset(local: [f32; 3], clamped: [f32; 3]) -> [f32; 3] {     if len < 1e-6 {         let mut ax = 0;         let mut best = local[0].abs();-        for a in 1..3 {-            if local[a].abs() > best {-                best = local[a].abs();+        for (a, value) in local.iter().enumerate().skip(1) {+            if value.abs() > best {+                best = value.abs();                 ax = a;             }         }
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 e7ec9b007e..4937dfc426 100644--- a/library/avatar/src/main/rust/src/renderer.rs+++ b/library/avatar/src/main/rust/src/renderer.rs@@ -13,9 +13,11 @@ use crate::vulkan::renderer::YuuRenderer; /// falls back to GLES, and fails only when both fail. pub enum Renderer {     /// Vulkan path (`ash` loaded): instance + swapchain + pipeline.-    Vulkan(YuuRenderer),+    /// Boxed so the enum stays pointer-sized (both renderers are large).+    Vulkan(Box<YuuRenderer>),     /// 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 {@@ -117,7 +119,7 @@ impl Renderer {         state_height: u32,     ) -> Result<Self, String> {         match crate::vulkan::renderer::YuuRenderer::new(window, width, height, state_width, state_height) {-            Ok(r) => Ok(Self::Vulkan(r)),+            Ok(r) => Ok(Self::Vulkan(Box::new(r))),             Err(e) => Err(e),         }     }@@ -142,7 +144,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 unsafe { Self::try_vulkan_only(window, width, height, state_width, state_height) } {@@ -172,7 +174,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})"
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 afc9147c4a..4746357339 100644--- a/library/avatar/src/main/rust/src/vulkan/buffers.rs+++ b/library/avatar/src/main/rust/src/vulkan/buffers.rs@@ -126,6 +126,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,@@ -165,6 +169,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;@@ -182,6 +190,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);
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 5dea11b4b8..69e488e710 100644--- a/library/avatar/src/main/rust/src/vulkan/context.rs+++ b/library/avatar/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("YuuAvatar").unwrap();
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 758b69f119..1c88f420a3 100644--- a/library/avatar/src/main/rust/src/vulkan/pipeline.rs+++ b/library/avatar/src/main/rust/src/vulkan/pipeline.rs@@ -29,6 +29,10 @@ impl Pipelines {     /// Build against the swapchain's render pass, binding `ubo_buffer`.     /// `sampler`, `image_view` may be null when no albedo is uploaded yet —     /// the set is updated by [`Self::bind_albedo`] once the texture exists.+    ///+    /// # 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,@@ -165,6 +169,10 @@ impl Pipelines {     }      /// Bind the albedo texture to the sampler slot (after upload).+    ///+    /// # Safety+    /// `device`, `sampler`, and `image_view` must be valid handles from+    /// the same live Vulkan context as this pipeline; render thread only.     pub unsafe fn bind_albedo(         &self,         device: &ash::Device,@@ -198,6 +206,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);
library/avatar/src/main/rust/src/vulkan/renderer_frame.rs
diff --git a/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs b/library/avatar/src/main/rust/src/vulkan/renderer_frame.rsindex 26fd6d0c75..4a899ef6c2 100644--- a/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs+++ b/library/avatar/src/main/rust/src/vulkan/renderer_frame.rs@@ -5,6 +5,10 @@  impl YuuRenderer {     /// Upload the static avatar mesh (once per surface; 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_avatar(&self, mesh: &[crate::mesh::YuuVertex]) {         let converted: Vec<YuuVkVertex> = mesh.iter().take(AVATAR_VERT_CAP).map(YuuVkVertex::from).collect();         let bytes = unsafe {@@ -17,6 +21,9 @@ impl YuuRenderer {     }      /// Resize the swapchain (recreates against the adopted window).+    ///+    /// # Safety+    /// Must be called on the render thread that owns this renderer.     pub unsafe fn resize(&mut self, width: u32, height: u32) {         self.width = width.max(1);         self.height = height.max(1);@@ -26,6 +33,10 @@ impl YuuRenderer {      /// Draw one frame: upload the bone UBO, record, submit, present.     /// `mesh_count` is the vertex count from the last [`Self::upload_avatar`].+    ///+    /// # 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,@@ -155,6 +166,10 @@ impl YuuRenderer {     }      /// 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();
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 f00b7c4a89..ed76dc8fda 100644--- a/library/avatar/src/main/rust/src/vulkan/swapchain.rs+++ b/library/avatar/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;