From 9ffac336d1534527e87f02bc199f7857d32d8ce9 Mon Sep 17 00:00:00 2001 From: IllusionMan1212 Date: Wed, 15 Nov 2023 01:50:08 +0200 Subject: [PATCH] misc: ran clippy --- src/aabb.rs | 6 ++-- src/camera.rs | 6 ++-- src/importer/mod.rs | 12 ++++---- src/importer/obj.rs | 56 +++++++++++++++++----------------- src/importer/stl.rs | 2 +- src/ipc.rs | 4 +-- src/logger.rs | 2 +- src/main.rs | 73 +++++++++++++++++++++------------------------ src/mesh.rs | 13 ++++---- src/model.rs | 4 +-- src/ui/ui.rs | 24 +++++++-------- src/utils.rs | 15 ++++++---- 12 files changed, 106 insertions(+), 111 deletions(-) diff --git a/src/aabb.rs b/src/aabb.rs index 00157a4..59d07f0 100644 --- a/src/aabb.rs +++ b/src/aabb.rs @@ -61,7 +61,7 @@ impl AABB { }, ]; - let indices = vec![ + let indices = [ 0, 1, 2, 2, 3, 0, // front 1, 5, 6, 6, 2, 1, // right 5, 4, 7, 7, 6, 5, // back @@ -88,7 +88,7 @@ impl AABB { gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, - (std::mem::size_of::() * indices.len() as usize) as isize, + (std::mem::size_of::() * indices.len()) as isize, indices.as_ptr() as *const std::ffi::c_void, gl::STATIC_DRAW, ); @@ -142,7 +142,7 @@ impl AABB { pub fn draw(&self, shader: &Shader, model_mat: &glm::Mat4) { shader.use_shader(); - shader.set_mat4fv("model", &model_mat); + shader.set_mat4fv("model", model_mat); shader.set_3fv("material.ambient", glm::vec3(1.0, 0.627, 0.157)); shader.set_3fv("material.diffuse", glm::vec3(1.0, 0.627, 0.157)); diff --git a/src/camera.rs b/src/camera.rs index 223eee6..e0c1b40 100644 --- a/src/camera.rs +++ b/src/camera.rs @@ -14,8 +14,8 @@ pub struct Camera { pub fov: f32, } -impl Camera { - pub fn new() -> Camera { +impl Default for Camera { + fn default() -> Self { Camera { position: glm::vec3(0.0, 3.0, 3.0), front: glm::vec3(0.0, 0.0, -1.0), @@ -28,7 +28,9 @@ impl Camera { fov: 45.0, } } +} +impl Camera { pub fn handle_mouse_scroll(&mut self, yoffset: f32, can_capture_cursor: bool, fov_zoom: bool) { if !can_capture_cursor { return; diff --git a/src/importer/mod.rs b/src/importer/mod.rs index b2b2ee4..a4c7d57 100644 --- a/src/importer/mod.rs +++ b/src/importer/mod.rs @@ -1,7 +1,7 @@ mod obj; mod stl; -use std::path::PathBuf; +use std::{path::Path, str::FromStr}; use crate::{ aabb::AABB, @@ -133,7 +133,7 @@ pub struct Object { pub aabb: AABB, } -pub fn load_from_file(path: &PathBuf) -> Result> { +pub fn load_from_file(path: &Path) -> Result> { let path_str = match path.to_str() { Some(s) => s, None => return Err("Failed to convert path to string".into()), @@ -143,10 +143,10 @@ pub fn load_from_file(path: &PathBuf) -> Result stl::load_stl(file)?, - Some(SupportedFileExtensions::OBJ) => obj::load_obj(path, file)?, - _ => panic!("Unsupported file extension: {}", path_str), + let obj = match SupportedFileExtensions::from_str(path.extension().unwrap().to_str().unwrap())? + { + SupportedFileExtensions::STL => stl::load_stl(file)?, + SupportedFileExtensions::OBJ => obj::load_obj(path, file)?, }; Ok(obj) diff --git a/src/importer/obj.rs b/src/importer/obj.rs index a44d00b..be8182c 100644 --- a/src/importer/obj.rs +++ b/src/importer/obj.rs @@ -1,7 +1,7 @@ use std::{ collections::HashMap, io::{BufRead, BufReader}, - path::PathBuf, + path::{Path, PathBuf}, }; use log::{error, trace, warn}; @@ -29,7 +29,7 @@ enum ObjToken { } impl ObjToken { - fn from_str<'a>(s: &'a str) -> Option { + fn from_str(s: &str) -> Option { match s { "o" => Some(ObjToken::Object), "g" => Some(ObjToken::Group), @@ -113,7 +113,7 @@ fn parse_mtl( for line in reader.lines() { let line = line?; // skip empty lines and comments - if line.is_empty() || line.chars().nth(0).is_some_and(|c| c == '#') { + if line.is_empty() || line.chars().next().is_some_and(|c| c == '#') { continue; } @@ -174,12 +174,9 @@ fn parse_mtl( let tex_type = TextureType::from_material_str(token).unwrap(); let name = iter.next().unwrap().to_string(); - let tex = if obj_textures.contains_key(&name) { - let mut tex = obj_textures.get(&name).unwrap().clone(); - - tex.typ = tex_type; - tex - } else { + let tex = if let std::collections::hash_map::Entry::Vacant(e) = + obj_textures.entry(name.clone()) + { let path = path.parent().unwrap().join(&name); let tex = match Texture::new(path, tex_type) { Ok(v) => v, @@ -188,8 +185,11 @@ fn parse_mtl( continue; } }; - - obj_textures.insert(name, tex.clone()); + e.insert(tex.clone()); + tex + } else { + let mut tex = obj_textures.get(&name).unwrap().clone(); + tex.typ = tex_type; tex }; @@ -218,7 +218,7 @@ fn parse_mtl( } pub fn load_obj( - obj_path: &PathBuf, + obj_path: &Path, file: std::fs::File, ) -> Result> { let now = std::time::Instant::now(); @@ -241,7 +241,7 @@ pub fn load_obj( for line in reader.lines() { let line = line?; // skip empty lines and comments - if line.is_empty() || line.chars().nth(0).is_some_and(|c| c == '#') { + if line.is_empty() || line.chars().next().is_some_and(|c| c == '#') { continue; } @@ -338,9 +338,9 @@ pub fn load_obj( let mut calculated_normal = glm::vec3(0.0, 0.0, 0.0); if normals.is_empty() { - let part0 = face[0].split("/").next().unwrap(); - let part1 = face[1].split("/").next().unwrap(); - let part2 = face[2].split("/").next().unwrap(); + let part0 = face[0].split('/').next().unwrap(); + let part1 = face[1].split('/').next().unwrap(); + let part2 = face[2].split('/').next().unwrap(); calculated_normal = glm::normalize(glm::cross( temp_vertices[part1.parse::().unwrap() as usize - 1] @@ -355,13 +355,13 @@ pub fn load_obj( let mut it = vert.split("//"); let mut vert = it.next().unwrap().parse::().unwrap(); if vert < 0 { - vert = temp_vertices.len() as i32 + vert; + vert += temp_vertices.len() as i32; } else { vert -= 1; } let mut normal = it.next().unwrap().parse::().unwrap(); if normal < 0 { - normal = normals.len() as i32 + normal; + normal += normals.len() as i32; } else { normal -= 1; } @@ -370,23 +370,23 @@ pub fn load_obj( normal: *normals.get(normal as usize).unwrap(), tex_coords: glm::vec2(0.0, 0.0), }); - } else if vert.matches("/").count() == 2 { - let mut it = vert.split("/"); + } else if vert.matches('/').count() == 2 { + let mut it = vert.split('/'); let mut vertex = it.next().unwrap().parse::().unwrap(); if vertex < 0 { - vertex = temp_vertices.len() as i32 + vertex; + vertex += temp_vertices.len() as i32; } else { vertex -= 1; } let mut t_coords = it.next().unwrap().parse::().unwrap(); if t_coords < 0 { - t_coords = tex_coords.len() as i32 + t_coords; + t_coords += tex_coords.len() as i32; } else { t_coords -= 1; } let mut normal = it.next().unwrap().parse::().unwrap(); if normal < 0 { - normal = normals.len() as i32 + normal; + normal += normals.len() as i32; } else { normal -= 1; } @@ -395,17 +395,17 @@ pub fn load_obj( normal: *normals.get(normal as usize).unwrap(), tex_coords: *tex_coords.get(t_coords as usize).unwrap(), }); - } else if vert.matches("/").count() == 1 { - let mut it = vert.split("/"); + } else if vert.matches('/').count() == 1 { + let mut it = vert.split('/'); let mut vertex = it.next().unwrap().parse::().unwrap(); if vertex < 0 { - vertex = temp_vertices.len() as i32 + vertex; + vertex += temp_vertices.len() as i32; } else { vertex -= 1; } let mut t_coords = it.next().unwrap().parse::().unwrap(); if t_coords < 0 { - t_coords = tex_coords.len() as i32 + t_coords; + t_coords += tex_coords.len() as i32; } else { t_coords -= 1; } @@ -417,7 +417,7 @@ pub fn load_obj( } else { let mut vert = vert.parse::().unwrap(); if vert < 0 { - vert = temp_vertices.len() as i32 + vert; + vert += temp_vertices.len() as i32; } else { vert -= 1; } diff --git a/src/importer/stl.rs b/src/importer/stl.rs index 93e2a89..7f821f9 100644 --- a/src/importer/stl.rs +++ b/src/importer/stl.rs @@ -178,7 +178,7 @@ fn parse_binary_stl(mut file: std::fs::File) -> Result UnixListener { std::fs::remove_file(&pipe_path).expect("Failed to remove existing pipe"); } - let listener = UnixListener::bind(&pipe_path).expect("Failed to create named pipe"); - - listener + UnixListener::bind(&pipe_path).expect("Failed to create named pipe") } fn send_args_to_existing_instance(pipe_path: PathBuf, args_paths: Vec) { diff --git a/src/logger.rs b/src/logger.rs index 736ac38..078ce0e 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -43,7 +43,7 @@ impl LogMessage { pub fn new(level: LogLevel, message: &str) -> Self { Self { level, - message: format!("{}", message), + message: message.to_string(), } } } diff --git a/src/main.rs b/src/main.rs index c5e66fa..6b23f84 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,8 @@ +#![allow(clippy::no_effect)] use std::env; use std::fs::File; use std::path::PathBuf; -use anyhow; use glad_gl::gl; use glfw::{Action, Context, Key, Modifiers}; use simplelog::*; @@ -114,7 +114,7 @@ fn main() -> anyhow::Result<(), Box> { glm::vec3(0.0, 0.0, -3.0), ]; - let mut delta_time: f32 = 0.0; + let mut delta_time; let mut last_frame: f32 = 0.0; let mut last_cursor = None; @@ -131,8 +131,8 @@ fn main() -> anyhow::Result<(), Box> { mesh_shader.use_shader(); // set light uniforms - for i in 0..points_lights.len() { - mesh_shader.set_3fv(&format!("pointLights[{}].position", i), points_lights[i]); + for (i, point_light) in points_lights.iter().enumerate() { + mesh_shader.set_3fv(&format!("pointLights[{}].position", i), *point_light); mesh_shader.set_float(&format!("pointLights[{}].constant", i), 1.0); mesh_shader.set_float(&format!("pointLights[{}].linear", i), 0.09); @@ -229,42 +229,37 @@ fn main() -> anyhow::Result<(), Box> { glfw_platform.handle_event(imgui.io_mut(), &window, &event); } - match event { - glfw::WindowEvent::CursorPos(xpos, ypos) => { - if first_mouse { - last_x = xpos as f32; - last_y = ypos as f32; - first_mouse = false; - } - - let xoffset = xpos as f32 - last_x; - let yoffset = last_y - ypos as f32; + if let glfw::WindowEvent::CursorPos(xpos, ypos) = event { + if first_mouse { last_x = xpos as f32; last_y = ypos as f32; + first_mouse = false; + } - if state.can_capture_cursor - && window.get_mouse_button(glfw::MouseButtonLeft) == Action::Press - { - if window.get_key(glfw::Key::LeftShift) == Action::Press { - state.camera.move_camera(-xoffset, -yoffset); - } else { - if let Some(active_model) = state.active_model { - let x_rotation = - xoffset * state.camera.sensitivity * state.rotation_speed; - let y_rotation = - yoffset * state.camera.sensitivity * state.rotation_speed; - let model = state - .objects - .iter_mut() - .find(|m| m.id == active_model) - .unwrap(); - // let x_rotation = glm::quat_angle_axis(xoffset * state.camera.sensitivity, &state.camera.up); - model.rotate(x_rotation, y_rotation); - } - } + let xoffset = xpos as f32 - last_x; + let yoffset = last_y - ypos as f32; + last_x = xpos as f32; + last_y = ypos as f32; + + if state.can_capture_cursor + && window.get_mouse_button(glfw::MouseButtonLeft) == Action::Press + { + if window.get_key(glfw::Key::LeftShift) == Action::Press { + state.camera.move_camera(-xoffset, -yoffset); + } else if let Some(active_model) = state.active_model { + let x_rotation = + xoffset * state.camera.sensitivity * state.rotation_speed; + let y_rotation = + yoffset * state.camera.sensitivity * state.rotation_speed; + let model = state + .objects + .iter_mut() + .find(|m| m.id == active_model) + .unwrap(); + // let x_rotation = glm::quat_angle_axis(xoffset * state.camera.sensitivity, &state.camera.up); + model.rotate(x_rotation, y_rotation); } } - _ => {} } } @@ -344,8 +339,8 @@ fn main() -> anyhow::Result<(), Box> { fn draw_grid(shader: &threedobs::shader::Shader, view_mat: &glm::Mat4, projection_mat: &glm::Mat4) { shader.use_shader(); - shader.set_mat4fv("view", &view_mat); - shader.set_mat4fv("projection", &projection_mat); + shader.set_mat4fv("view", view_mat); + shader.set_mat4fv("projection", projection_mat); unsafe { gl::DrawArrays(gl::TRIANGLES, 0, 6); } @@ -408,7 +403,7 @@ fn create_scene_framebuffer() -> u32 { gl::BindFramebuffer(gl::FRAMEBUFFER, fb); } - return fb; + fb } fn create_scene_texture_and_renderbuffer(window: &glfw::Window, fbo: u32) -> (u32, u32) { @@ -461,5 +456,5 @@ fn create_scene_texture_and_renderbuffer(window: &glfw::Window, fbo: u32) -> (u3 } } - return (fb_texture, rbo); + (fb_texture, rbo) } diff --git a/src/mesh.rs b/src/mesh.rs index 761dd7b..580fdde 100644 --- a/src/mesh.rs +++ b/src/mesh.rs @@ -1,5 +1,4 @@ use glad_gl::gl; -use log::warn; use crate::{ importer::{Material, TextureType}, @@ -20,15 +19,13 @@ fn create_rotation_matrix(pitch: f32, yaw: f32, roll: f32, pivot: glm::Vec3) -> let trans_to_origin = glm::ext::translate(&mat, -glm::vec3(pivot.x, pivot.y, pivot.z)); let trans_back_to_center = glm::ext::translate(&mat, glm::vec3(pivot.x, pivot.y, pivot.z)); - let combined = trans_back_to_center * rot_z * rot_y * rot_x * trans_to_origin; - - combined + trans_back_to_center * rot_z * rot_y * rot_x * trans_to_origin } pub fn apply_rotation(matrix: &glm::Mat4, rot: glm::Vec3, pivot: glm::Vec3) -> glm::Mat4 { let rot = create_rotation_matrix(rot.x, rot.y, rot.z, pivot); - return rot * *matrix; + rot * *matrix } #[derive(Debug)] @@ -69,7 +66,7 @@ impl Mesh { gl::BufferData( gl::ARRAY_BUFFER, - (std::mem::size_of::() * vertices.len() as usize) as isize, + (std::mem::size_of::() * vertices.len()) as isize, vertices.as_ptr() as *const std::ffi::c_void, gl::STATIC_DRAW, ); @@ -77,7 +74,7 @@ impl Mesh { gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, - (std::mem::size_of::() * indices.len() as usize) as isize, + (std::mem::size_of::() * indices.len()) as isize, indices.as_ptr() as *const std::ffi::c_void, gl::STATIC_DRAW, ); @@ -183,7 +180,7 @@ impl Mesh { } if show_textures { - shader.set_bool("useTextures", self.material.textures.len() > 0); + shader.set_bool("useTextures", !self.material.textures.is_empty()); for (i, tex) in self.material.textures.iter().enumerate() { shader.set_bool("hasEmissionTexture", false); unsafe { diff --git a/src/model.rs b/src/model.rs index 61850b3..2142d13 100644 --- a/src/model.rs +++ b/src/model.rs @@ -49,7 +49,7 @@ impl Model { model.set_mem_usage(); - return model; + model } pub fn draw(&self, shader: &Shader, draw_aabb: bool, show_textures: bool) { @@ -109,7 +109,7 @@ impl Model { size += std::mem::size_of::(); for texture in &mesh.material.textures { - size += std::mem::size_of_val(&texture); + size += std::mem::size_of_val(texture); } for vertex in &mesh.vertices { size += std::mem::size_of_val(vertex); diff --git a/src/ui/ui.rs b/src/ui/ui.rs index 6c05b1b..d4331f0 100644 --- a/src/ui/ui.rs +++ b/src/ui/ui.rs @@ -52,7 +52,7 @@ impl Default for State { fov_zoom: true, rotation_speed: 1.0, wireframe: false, - camera: Camera::new(), + camera: Camera::default(), objects: vec![], viewport_size: [0.0, 0.0], logger: logger::WritableLog::default(), @@ -70,7 +70,7 @@ impl State { id = last_model.id + 1; } - return id; + id } } @@ -95,7 +95,7 @@ pub fn init_imgui( let mut glfw_platform = imgui_glfw_support::GlfwPlatform::init(&mut imgui); glfw_platform.attach_window( imgui.io_mut(), - &window, + window, imgui_glfw_support::HiDpiMode::Default, ); @@ -114,7 +114,7 @@ pub fn init_imgui( gl::load(|e| window.get_proc_address(e) as *const std::os::raw::c_void); let renderer = imgui_opengl_renderer::Renderer::new(&mut imgui); - glfw_platform.set_clipboard_backend(&mut imgui, &window); + glfw_platform.set_clipboard_backend(&mut imgui, window); (imgui, glfw_platform, renderer) } @@ -186,14 +186,14 @@ pub fn draw_main_menu_bar(ui: &imgui::Ui, state: &mut State, window: &mut glfw:: let mem = state .objects .iter() - .fold(0 as usize, |acc, m| acc + m.mem_usage) as f32; + .fold(0_usize, |acc, m| acc + m.mem_usage) as f32; let mem_fps = format!( "Mem: {:.1}MB | FPS: {:.1}", mem / (1024.0 * 1024.0), state.fps ); let avail_size = [ - *ui.content_region_avail().get(0).unwrap() - ui.calc_text_size(&mem_fps)[0], + *ui.content_region_avail().first().unwrap() - ui.calc_text_size(&mem_fps)[0], 0.0, ]; ui.dummy(avail_size); @@ -223,7 +223,7 @@ fn draw_about_window(ui: &imgui::Ui, state: &mut State) { env!("CARGO_PKG_VERSION"), env!("GIT_HASH") )); - ui.text(format!("{}", env!("CARGO_PKG_DESCRIPTION"))); + ui.text(env!("CARGO_PKG_DESCRIPTION")); ui.spacing(); ui.spacing(); ui.text(format!("Made by: {}", env!("CARGO_PKG_AUTHORS"))); @@ -379,7 +379,7 @@ fn draw_object_hierarchy(ui: &imgui::Ui, state: &mut State, idx: usize) -> bool return true; } - return false; + false } fn draw_objects_window(ui: &imgui::Ui, state: &mut State) { @@ -420,7 +420,7 @@ fn draw_objects_window(ui: &imgui::Ui, state: &mut State) { state.objects.remove(i); if state.active_model == Some(selected_obj_id) { let model = state.objects.last_mut().map(|m| m.reset_rotation()); - state.active_model = model.and_then(|o| Some(o.id)); + state.active_model = model.map(|o| o.id); state .camera .focus_on_selected_model(state.active_model, &state.objects); @@ -428,7 +428,7 @@ fn draw_objects_window(ui: &imgui::Ui, state: &mut State) { continue; } - i = i + 1; + i += 1; } } }); @@ -548,7 +548,7 @@ fn draw_viewport(ui: &imgui::Ui, state: &mut State, texture: u32) { 0, gl::RGBA, gl::UNSIGNED_BYTE, - (w * h * 4) as i32, + w * h * 4, pixels.as_mut_ptr() as *mut std::ffi::c_void, ); } @@ -648,7 +648,7 @@ pub fn draw_ui( let cursor = ui.mouse_cursor(); if *last_cursor != cursor { *last_cursor = cursor; - glfw_platform.prepare_render(&ui, window); + glfw_platform.prepare_render(ui, window); } } diff --git a/src/utils.rs b/src/utils.rs index 8591c1e..a86ac57 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,4 +1,5 @@ use std::path::PathBuf; +use std::str::FromStr; use ::log::{error, info}; use anyhow::{Context, Result}; @@ -12,12 +13,14 @@ pub enum SupportedFileExtensions { STL, } -impl SupportedFileExtensions { - pub fn from_str(s: &str) -> Option { +impl std::str::FromStr for SupportedFileExtensions { + type Err = String; + + fn from_str(s: &str) -> Result { match s.to_ascii_lowercase().as_str() { - "obj" => Some(Self::OBJ), - "stl" => Some(Self::STL), - _ => None, + "obj" => Ok(Self::OBJ), + "stl" => Ok(Self::STL), + _ => Err(format!("Unsupported file extension: {}", s)), } } } @@ -91,7 +94,7 @@ pub fn import_models_from_paths(paths: &Vec, state: &mut ui::ui::State) } match model_path.extension() { Some(ext) => { - if SupportedFileExtensions::from_str(ext.to_str().unwrap()).is_none() { + if SupportedFileExtensions::from_str(ext.to_str().unwrap()).is_err() { info!( "Skipping file \"{}\" because it is not an OBJ or STL file", filename.unwrap().to_str().unwrap()