From 87f9ac4b3f318bd8d860b7b89f79c121b28bef9f Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Sun, 10 Mar 2024 00:23:03 -0500 Subject: [PATCH] Repository Updates (#583) --- .rustfmt.toml | 1 + build.bash | 6 +- deny.toml | 5 +- examples/Cargo.toml | 4 +- examples/resources/index.html | 5 +- examples/src/animation/mod.rs | 14 +- examples/src/cube/mod.rs | 20 +- examples/src/cube_no_framework/Cargo.toml | 36 --- examples/src/cube_no_framework/mod.rs | 10 +- examples/src/egui/mod.rs | 28 +- examples/src/lib.rs | 65 ++-- examples/src/scene_viewer/mod.rs | 102 ++---- examples/src/skinning/mod.rs | 4 +- examples/src/static_gltf/mod.rs | 28 +- examples/src/tests.rs | 20 +- examples/src/textured_quad/Cargo.toml | 30 -- examples/src/textured_quad/mod.rs | 13 +- rend3-anim/src/lib.rs | 78 +---- rend3-egui/Cargo.toml | 2 +- rend3-egui/src/lib.rs | 35 +- rend3-framework/Cargo.toml | 4 +- rend3-framework/src/assets.rs | 27 +- rend3-framework/src/grab/wasm.rs | 13 +- rend3-framework/src/lib.rs | 55 +--- rend3-gltf/Cargo.toml | 2 +- rend3-gltf/src/lib.rs | 299 ++++-------------- rend3-routine/Cargo.toml | 4 +- rend3-routine/src/base.rs | 73 ++--- rend3-routine/src/common/interfaces.rs | 10 +- rend3-routine/src/common/samplers.rs | 28 +- rend3-routine/src/culling/batching.rs | 47 +-- rend3-routine/src/culling/culler.rs | 90 +----- rend3-routine/src/culling/suballoc.rs | 6 +- rend3-routine/src/forward.rs | 29 +- rend3-routine/src/hi_z.rs | 73 +---- rend3-routine/src/pbr/material.rs | 63 +--- rend3-routine/src/pbr/routine.rs | 24 +- rend3-routine/src/shaders.rs | 7 +- rend3-routine/src/skinning.rs | 15 +- rend3-routine/src/skybox.rs | 25 +- rend3-routine/src/tonemapping.rs | 39 +-- rend3-routine/src/uniforms.rs | 7 +- rend3-test/Cargo.toml | 4 +- rend3-test/src/runner.rs | 63 +--- rend3-test/src/threshold.rs | 13 +- rend3-test/tests/msaa.rs | 27 +- rend3-test/tests/object.rs | 22 +- rend3-test/tests/shadow.rs | 21 +- rend3-test/tests/simple.rs | 61 +--- rend3-types/Cargo.toml | 4 +- rend3-types/src/attribute.rs | 35 +- rend3-types/src/lib.rs | 69 +--- rend3/Cargo.toml | 6 +- rend3/src/graph/graph.rs | 80 ++--- rend3/src/graph/node.rs | 9 +- rend3/src/graph/store.rs | 7 +- rend3/src/graph/temp.rs | 9 +- rend3/src/graph/texture_store.rs | 10 +- rend3/src/instruction.rs | 5 +- rend3/src/managers/camera.rs | 10 +- rend3/src/managers/directional.rs | 15 +- .../src/managers/directional/shadow_alloc.rs | 129 ++------ .../src/managers/directional/shadow_camera.rs | 4 +- rend3/src/managers/graph_storage.rs | 8 +- rend3/src/managers/handle_alloc.rs | 9 +- rend3/src/managers/material.rs | 32 +- rend3/src/managers/material/texture_dedupe.rs | 11 +- rend3/src/managers/mesh.rs | 36 +-- rend3/src/managers/object.rs | 56 +--- rend3/src/managers/point.rs | 3 +- rend3/src/managers/skeleton.rs | 22 +- rend3/src/managers/texture.rs | 101 ++---- rend3/src/renderer/error.rs | 13 +- rend3/src/renderer/eval.rs | 58 +--- rend3/src/renderer/mod.rs | 104 ++---- rend3/src/renderer/setup.rs | 2 +- rend3/src/setup.rs | 36 +-- rend3/src/shader.rs | 100 ++---- rend3/src/util/bind_merge.rs | 43 +-- rend3/src/util/freelist/buffer.rs | 10 +- rend3/src/util/freelist/vec.rs | 5 +- rend3/src/util/frustum.rs | 27 +- rend3/src/util/mipmap.rs | 36 +-- rend3/src/util/output.rs | 10 +- rend3/src/util/scatter_copy.rs | 65 +--- rend3/src/util/sync.rs | 5 +- rend3/src/util/upload.rs | 12 +- 87 files changed, 647 insertions(+), 2206 deletions(-) delete mode 100644 examples/src/cube_no_framework/Cargo.toml delete mode 100644 examples/src/textured_quad/Cargo.toml diff --git a/.rustfmt.toml b/.rustfmt.toml index c641f101..cbcd4e91 100644 --- a/.rustfmt.toml +++ b/.rustfmt.toml @@ -1,4 +1,5 @@ max_width = 120 +use_small_heuristics = "Max" use_field_init_shorthand = true use_try_shorthand = true edition = "2021" diff --git a/build.bash b/build.bash index 06e441e0..5888eb7f 100755 --- a/build.bash +++ b/build.bash @@ -12,12 +12,12 @@ case $1 in else WASM_BUILD_DIR=debug fi - cargo build --target wasm32-unknown-unknown $BUILD_FLAGS --bin $@ + cargo build --target wasm32-unknown-unknown $BUILD_FLAGS --bin rend3-examples mkdir -p target/generated/ rm -rf target/generated/* - cp -r examples/$1/resources target/generated/ || true + cp -r examples/src/$1/resources target/generated/ || true sed "s/{{example}}/$1/g" > target/generated/index.html < examples/resources/index.html - wasm-bindgen --out-dir target/generated --target web target/wasm32-unknown-unknown/$WASM_BUILD_DIR/$1.wasm + wasm-bindgen --out-dir target/generated --target web target/wasm32-unknown-unknown/$WASM_BUILD_DIR/rend3-examples.wasm ;; serve) shift diff --git a/deny.toml b/deny.toml index b83173f0..f381f5ef 100644 --- a/deny.toml +++ b/deny.toml @@ -15,12 +15,13 @@ wildcards = "allow" skip = [ # gltf / reqwest { name = "base64", version = "0.13.1" }, + # ndk_glue + { name = "env_logger", version = "0.10.2" }, ] skip-tree = [ # winit brings in lots of duplicate deps that we can't fix { name = "winit", version = "0.29.4" }, - # loom is depended on by tracy-client but under a custom cfg that is never on. - { name = "loom", version = "0.5" }, + ] [advisories] diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 73acd448..3c4fbbce 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -24,9 +24,9 @@ egui = "0.26" # Winit integration with egui (turn off the clipboard feature) egui-winit = { version = "0.26", default-features = false, features = ["links", "wayland"] } # logging -env_logger = { version = "0.10", default-features = false, features = ["auto-color", "humantime"] } +env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] } # Linear algebra library -glam = "0.24" +glam = "0.25" # gltf model loading gltf = "1.4" # Channel diff --git a/examples/resources/index.html b/examples/resources/index.html index c9f866db..3c4c9640 100644 --- a/examples/resources/index.html +++ b/examples/resources/index.html @@ -13,8 +13,9 @@ diff --git a/examples/src/animation/mod.rs b/examples/src/animation/mod.rs index 15dc0226..03878665 100644 --- a/examples/src/animation/mod.rs +++ b/examples/src/animation/mod.rs @@ -53,10 +53,7 @@ impl rend3_framework::App for AnimationExample { // Load a gltf model with animation data // Needs to be stored somewhere, otherwise all the data gets freed. - let path = Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/animation/resources/scene.gltf" - )); + let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/animation/resources/scene.gltf")); let gltf_data = std::fs::read(path).unwrap(); let parent_directory = path.parent().unwrap(); let (loaded_scene, loaded_instance) = pollster::block_on(rend3_gltf::load_gltf( @@ -88,10 +85,7 @@ impl rend3_framework::App for AnimationExample { animation_time: 0.0, }; - let path = Path::new(concat!( - env!("CARGO_MANIFEST_DIR"), - "/src/animation/resources/cube_3.gltf" - )); + let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/src/animation/resources/cube_3.gltf")); let gltf_data = std::fs::read(path).unwrap(); let parent_directory = path.parent().unwrap(); let (loaded_scene, loaded_instance) = pollster::block_on(rend3_gltf::load_gltf( @@ -167,9 +161,7 @@ pub fn main() { let app = AnimationExample::default(); rend3_framework::start( app, - winit::window::WindowBuilder::new() - .with_title("animation-example") - .with_maximized(true), + winit::window::WindowBuilder::new().with_title("animation-example").with_maximized(true), ); } diff --git a/examples/src/cube/mod.rs b/examples/src/cube/mod.rs index 94bf9ff6..22b82b21 100644 --- a/examples/src/cube/mod.rs +++ b/examples/src/cube/mod.rs @@ -125,13 +125,12 @@ impl rend3_framework::App for CubeExample { ]; for (position, color) in lights { - self.point_lights - .push(context.renderer.add_point_light(rend3::types::PointLight { - position, - color, - radius: 2.0, - intensity: 4.0, - })); + self.point_lights.push(context.renderer.add_point_light(rend3::types::PointLight { + position, + color, + radius: 2.0, + intensity: 4.0, + })); } } @@ -184,12 +183,7 @@ impl rend3_framework::App for CubeExample { pub fn main() { let app = CubeExample::default(); - rend3_framework::start( - app, - winit::window::WindowBuilder::new() - .with_title("cube-example") - .with_maximized(true), - ); + rend3_framework::start(app, winit::window::WindowBuilder::new().with_title("cube-example").with_maximized(true)); } #[cfg(test)] diff --git a/examples/src/cube_no_framework/Cargo.toml b/examples/src/cube_no_framework/Cargo.toml deleted file mode 100644 index bdaef2da..00000000 --- a/examples/src/cube_no_framework/Cargo.toml +++ /dev/null @@ -1,36 +0,0 @@ -[package] -name = "rend3-cube-no-framework-example" -license = "MIT OR Apache-2.0 OR Zlib" -version = "0.3.0" -authors = ["The rend3 Developers"] -edition = "2021" -publish = false -rust-version = "1.71" - -[[bin]] -name = "cube-no-framework" -path = "src/main.rs" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -# logging -env_logger = { version = "0.10", default-features = false, features = ["auto-color", "humantime"] } -# Linear algebra library -glam = "0.24" -# Renderer core -rend3 = { version = "^0.3.0", path = "../../rend3" } -# Programmable render list that dictates how the scene renders -rend3-routine = { version = "^0.3.0", path = "../../rend3-routine" } -# Provides `block_on` to wait for futures from sync code -pollster = "0.3" -# windowing -winit = "0.29.4" - -[target.'cfg(target_arch = "wasm32")'.dependencies] -console_log = "1" -console_error_panic_hook = "0.1" -js-sys = "0.3" -web-sys = "0.3.67" -wasm-bindgen = "0.2.83" -wasm-bindgen-futures = "0.4" diff --git a/examples/src/cube_no_framework/mod.rs b/examples/src/cube_no_framework/mod.rs index 03f6d0fc..e764e898 100644 --- a/examples/src/cube_no_framework/mod.rs +++ b/examples/src/cube_no_framework/mod.rs @@ -179,10 +179,7 @@ pub fn main() { event_loop .run(move |event, _event_loop_window_target| match event { // Window was resized, need to resize renderer. - winit::event::Event::WindowEvent { - event: winit::event::WindowEvent::Resized(physical_size), - .. - } => { + winit::event::Event::WindowEvent { event: winit::event::WindowEvent::Resized(physical_size), .. } => { resolution = glam::UVec2::new(physical_size.width, physical_size.height); // Reconfigure the surface for the new size. rend3::configure_surface( @@ -196,10 +193,7 @@ pub fn main() { renderer.set_aspect_ratio(resolution.x as f32 / resolution.y as f32); } // Render! - winit::event::Event::WindowEvent { - event: winit::event::WindowEvent::RedrawRequested, - .. - } => { + winit::event::Event::WindowEvent { event: winit::event::WindowEvent::RedrawRequested, .. } => { // Get a frame let frame = surface.get_current_texture().unwrap(); diff --git a/examples/src/egui/mod.rs b/examples/src/egui/mod.rs index 8fb7cf11..cf3a4634 100644 --- a/examples/src/egui/mod.rs +++ b/examples/src/egui/mod.rs @@ -155,8 +155,7 @@ impl rend3_framework::App for EguiExample { #[allow(clippy::single_match)] match event { winit::event::WindowEvent::Resized(size) => { - data.egui_routine - .resize(size.width, size.height, window.scale_factor() as f32); + data.egui_routine.resize(size.width, size.height, window.scale_factor() as f32); } _ => {} } @@ -192,13 +191,7 @@ impl rend3_framework::App for EguiExample { ); } ui.label("Want to get rusty?"); - if ui - .add(egui::widgets::ImageButton::new(( - self.rust_logo, - egui::Vec2::splat(64.0), - ))) - .clicked() - { + if ui.add(egui::widgets::ImageButton::new((self.rust_logo, egui::Vec2::splat(64.0)))).clicked() { webbrowser::open("https://www.rust-lang.org").expect("failed to open URL"); } }); @@ -207,16 +200,10 @@ impl rend3_framework::App for EguiExample { // End the UI frame. Now let's draw the UI with our Backend, we could also // handle the output here - let egui::FullOutput { - shapes, textures_delta, .. - } = data.context.end_frame(); + let egui::FullOutput { shapes, textures_delta, .. } = data.context.end_frame(); let paint_jobs = data.context.tessellate(shapes, scale_factor); - let input = rend3_egui::Input { - clipped_meshes: &paint_jobs, - textures_delta, - context: data.context.clone(), - }; + let input = rend3_egui::Input { clipped_meshes: &paint_jobs, textures_delta, context: data.context.clone() }; // Swap the instruction buffers so that our frame's changes can be processed. context.renderer.swap_instruction_buffers(); @@ -269,12 +256,7 @@ impl rend3_framework::App for EguiExample { pub fn main() { let app = EguiExample::default(); - rend3_framework::start( - app, - winit::window::WindowBuilder::new() - .with_title("egui") - .with_maximized(true), - ) + rend3_framework::start(app, winit::window::WindowBuilder::new().with_title("egui").with_maximized(true)) } fn vertex(pos: [f32; 3]) -> glam::Vec3 { diff --git a/examples/src/lib.rs b/examples/src/lib.rs index 0b3ab4d0..cba9e27c 100644 --- a/examples/src/lib.rs +++ b/examples/src/lib.rs @@ -1,3 +1,8 @@ +#![allow(clippy::arc_with_non_send_sync)] + +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::prelude::*; + mod animation; mod cube; mod cube_no_framework; @@ -7,6 +12,9 @@ mod skinning; mod static_gltf; mod textured_quad; +#[cfg(target_arch = "wasm32")] +use log::info as println; + #[cfg(test)] mod tests; @@ -16,62 +24,41 @@ struct ExampleDesc { } const EXAMPLES: &[ExampleDesc] = &[ - ExampleDesc { - name: "animation", - run: animation::main, - }, - ExampleDesc { - name: "cube", - run: cube::main, - }, - ExampleDesc { - name: "cube-no-framework", - run: cube_no_framework::main, - }, - ExampleDesc { - name: "egui", - run: egui::main, - }, - ExampleDesc { - name: "scene-viewer", - run: scene_viewer::main, - }, - ExampleDesc { - name: "skinning", - run: skinning::main, - }, - ExampleDesc { - name: "static-gltf", - run: static_gltf::main, - }, - ExampleDesc { - name: "textured-quad", - run: textured_quad::main, - }, + ExampleDesc { name: "animation", run: animation::main }, + ExampleDesc { name: "cube", run: cube::main }, + ExampleDesc { name: "cube-no-framework", run: cube_no_framework::main }, + ExampleDesc { name: "egui", run: egui::main }, + ExampleDesc { name: "scene_viewer", run: scene_viewer::main }, + ExampleDesc { name: "skinning", run: skinning::main }, + ExampleDesc { name: "static_gltf", run: static_gltf::main }, + ExampleDesc { name: "textured_quad", run: textured_quad::main }, ]; fn print_examples() { - println!("Usage: cargo run "); - println!(); + println!("Usage: cargo run \n"); println!("Available examples:"); for example in EXAMPLES { println!(" {}", example.name); } } -#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on", logger(level = "debug")))] -pub fn main() { - let Some(example_name) = std::env::args().nth(1) else { +#[cfg_attr(target_arch = "wasm32", wasm_bindgen)] +pub fn main_with_name(example_name: Option) { + let Some(example_name) = example_name else { print_examples(); return; }; let Some(example) = EXAMPLES.iter().find(|example| example.name == example_name) else { - println!("Unknown example: {}", example_name); - println!(); + println!("Unknown example: {}\n", example_name); print_examples(); return; }; (example.run)(); } + +#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "on", logger(level = "debug")))] +pub fn main() { + main_with_name(std::env::args().nth(1)) +} diff --git a/examples/src/scene_viewer/mod.rs b/examples/src/scene_viewer/mod.rs index 630f5dc9..13267e86 100644 --- a/examples/src/scene_viewer/mod.rs +++ b/examples/src/scene_viewer/mod.rs @@ -24,14 +24,9 @@ use winit::{ }; async fn load_skybox_image(loader: &rend3_framework::AssetLoader, data: &mut Vec, path: &str) { - let decoded = image::load_from_memory( - &loader - .get_asset(AssetPath::Internal(path)) - .await - .unwrap_or_else(|e| panic!("Error {}: {}", path, e)), - ) - .unwrap() - .into_rgba8(); + let request_response = + loader.get_asset(AssetPath::Internal(path)).await.unwrap_or_else(|e| panic!("Error {}: {}", path, e)); + let decoded = image::load_from_memory(&request_response).unwrap().into_rgba8(); data.extend_from_slice(decoded.as_raw()); } @@ -118,11 +113,7 @@ async fn load_gltf( }) .await?; - log::info!( - "Loaded gltf in {:.3?}, resources loaded in {:.3?}", - gltf_elapsed, - resources_start.elapsed() - ); + log::info!("Loaded gltf in {:.3?}, resources loaded in {:.3?}", gltf_elapsed, resources_start.elapsed()); Ok((scene, instance)) } @@ -403,16 +394,10 @@ impl SceneViewer { app.run_speed = run_speed; } - let camera_default = [ - app.camera_location.x, - app.camera_location.y, - app.camera_location.z, - app.camera_pitch, - app.camera_yaw, - ]; - if let Ok(camera_info) = args - .value_from_str("--camera") - .map(|s: String| extract_array(&s, camera_default).unwrap()) + let camera_default = + [app.camera_location.x, app.camera_location.y, app.camera_location.z, app.camera_pitch, app.camera_yaw]; + if let Ok(camera_info) = + args.value_from_str("--camera").map(|s: String| extract_array(&s, camera_default).unwrap()) { app.camera_location = Vec3A::new(camera_info[0], camera_info[1], camera_info[2]); app.camera_pitch = camera_info[3]; @@ -458,13 +443,7 @@ impl rend3_framework::App for SceneViewer { >, > { Box::pin(async move { - rend3::create_iad( - self.desired_backend, - self.desired_device_name.clone(), - self.desired_profile, - None, - ) - .await + rend3::create_iad(self.desired_backend, self.desired_device_name.clone(), self.desired_profile, None).await }) } @@ -481,9 +460,7 @@ impl rend3_framework::App for SceneViewer { } fn setup(&mut self, context: rend3_framework::SetupContext<'_>) { - self.grabber = context - .windowing - .map(|windowing| rend3_framework::Grabber::new(windowing.window)); + self.grabber = context.windowing.map(|windowing| rend3_framework::Grabber::new(windowing.window)); if let Some(direction) = self.directional_light_direction { self.directional_light = Some(context.renderer.add_directional_light(DirectionalLight { @@ -536,26 +513,14 @@ impl rend3_framework::App for SceneViewer { fn handle_event(&mut self, context: rend3_framework::EventContext<'_>, event: winit::event::Event<()>) { match event { - Event::WindowEvent { - event: WindowEvent::Focused(focus), - .. - } => { + Event::WindowEvent { event: WindowEvent::Focused(focus), .. } => { if !focus { - self.grabber - .as_mut() - .unwrap() - .request_ungrab(context.window.as_ref().unwrap()); + self.grabber.as_mut().unwrap().request_ungrab(context.window.as_ref().unwrap()); } } Event::WindowEvent { - event: - WindowEvent::KeyboardInput { - event: KeyEvent { - physical_key, state, .. - }, - .. - }, + event: WindowEvent::KeyboardInput { event: KeyEvent { physical_key, state, .. }, .. }, .. } => { let PhysicalKey::Code(scancode) = physical_key else { @@ -573,12 +538,7 @@ impl rend3_framework::App for SceneViewer { } Event::WindowEvent { - event: - WindowEvent::MouseInput { - button: MouseButton::Left, - state: ElementState::Pressed, - .. - }, + event: WindowEvent::MouseInput { button: MouseButton::Left, state: ElementState::Pressed, .. }, .. } => { let grabber = self.grabber.as_mut().unwrap(); @@ -587,14 +547,7 @@ impl rend3_framework::App for SceneViewer { grabber.request_grab(context.window.as_ref().unwrap()); } } - Event::DeviceEvent { - event: - DeviceEvent::MouseMotion { - delta: (delta_x, delta_y), - .. - }, - .. - } => { + Event::DeviceEvent { event: DeviceEvent::MouseMotion { delta: (delta_x, delta_y), .. }, .. } => { if !self.grabber.as_ref().unwrap().grabbed() { return; } @@ -619,10 +572,8 @@ impl rend3_framework::App for SceneViewer { } else if self.camera_yaw >= TAU { self.camera_yaw -= TAU; } - self.camera_pitch = self.camera_pitch.clamp( - -std::f32::consts::FRAC_PI_2 + 0.0001, - std::f32::consts::FRAC_PI_2 - 0.0001, - ) + self.camera_pitch = + self.camera_pitch.clamp(-std::f32::consts::FRAC_PI_2 + 0.0001, std::f32::consts::FRAC_PI_2 - 0.0001) } _ => {} } @@ -644,11 +595,8 @@ impl rend3_framework::App for SceneViewer { let forward = -rotation.z_axis; let up = rotation.y_axis; let side = -rotation.x_axis; - let velocity = if button_pressed(&self.scancode_status, KeyCode::ShiftLeft) { - self.run_speed - } else { - self.walk_speed - }; + let velocity = + if button_pressed(&self.scancode_status, KeyCode::ShiftLeft) { self.run_speed } else { self.walk_speed }; if button_pressed(&self.scancode_status, KeyCode::KeyW) { self.camera_location += forward * velocity * context.delta_t_seconds; } @@ -676,10 +624,7 @@ impl rend3_framework::App for SceneViewer { } if button_pressed(&self.scancode_status, winit::keyboard::KeyCode::Escape) { - self.grabber - .as_mut() - .unwrap() - .request_ungrab(context.window.as_ref().unwrap()); + self.grabber.as_mut().unwrap().request_ungrab(context.window.as_ref().unwrap()); } if button_pressed(&self.scancode_status, KeyCode::KeyP) { @@ -695,10 +640,9 @@ impl rend3_framework::App for SceneViewer { let view = Mat4::from_euler(glam::EulerRot::XYZ, -self.camera_pitch, -self.camera_yaw, 0.0); let view = view * Mat4::from_translation((-self.camera_location).into()); - context.renderer.set_camera_data(Camera { - projection: CameraProjection::Perspective { vfov: 60.0, near: 0.1 }, - view, - }); + context + .renderer + .set_camera_data(Camera { projection: CameraProjection::Perspective { vfov: 60.0, near: 0.1 }, view }); // Lock all the routines let pbr_routine = lock(&context.routines.pbr); diff --git a/examples/src/skinning/mod.rs b/examples/src/skinning/mod.rs index 97d76972..c05b9b76 100644 --- a/examples/src/skinning/mod.rs +++ b/examples/src/skinning/mod.rs @@ -159,9 +159,7 @@ pub fn main() { let app = SkinningExample::default(); rend3_framework::start( app, - winit::window::WindowBuilder::new() - .with_title("skinning-example") - .with_maximized(true), + winit::window::WindowBuilder::new().with_title("skinning-example").with_maximized(true), ); } diff --git a/examples/src/static_gltf/mod.rs b/examples/src/static_gltf/mod.rs index dece75da..cfd3b172 100644 --- a/examples/src/static_gltf/mod.rs +++ b/examples/src/static_gltf/mod.rs @@ -12,18 +12,9 @@ fn load_gltf( let vertex_positions: Vec<_> = reader.read_positions().unwrap().map(glam::Vec3::from).collect(); let vertex_normals: Vec<_> = reader.read_normals().unwrap().map(glam::Vec3::from).collect(); - let vertex_tangents: Vec<_> = reader - .read_tangents() - .unwrap() - .map(glam::Vec4::from) - .map(glam::Vec4::truncate) - .collect(); - let vertex_uvs: Vec<_> = reader - .read_tex_coords(0) - .unwrap() - .into_f32() - .map(glam::Vec2::from) - .collect(); + let vertex_tangents: Vec<_> = + reader.read_tangents().unwrap().map(glam::Vec4::from).map(glam::Vec4::truncate).collect(); + let vertex_uvs: Vec<_> = reader.read_tex_coords(0).unwrap().into_f32().map(glam::Vec2::from).collect(); let indices = reader.read_indices().unwrap().into_u32().collect(); let mesh = rend3::types::MeshBuilder::new(vertex_positions.to_vec(), rend3::types::Handedness::Right) @@ -68,10 +59,8 @@ impl rend3_framework::App for StaticGltfExample { // Create mesh and calculate smooth normals based on vertices. // // We do not need to keep these handles alive once we make the object - let (mesh, material) = load_gltf( - context.renderer, - concat!(env!("CARGO_MANIFEST_DIR"), "/src/static_gltf/data.glb"), - ); + let (mesh, material) = + load_gltf(context.renderer, concat!(env!("CARGO_MANIFEST_DIR"), "/src/static_gltf/data.glb")); // Combine the mesh and the material with a location to give an object. let object = rend3::types::Object { @@ -153,12 +142,7 @@ impl rend3_framework::App for StaticGltfExample { pub fn main() { let app = StaticGltfExample::default(); - rend3_framework::start( - app, - winit::window::WindowBuilder::new() - .with_title("gltf-example") - .with_maximized(true), - ); + rend3_framework::start(app, winit::window::WindowBuilder::new().with_title("gltf-example").with_maximized(true)); } #[cfg(test)] diff --git a/examples/src/tests.rs b/examples/src/tests.rs index 6e0904a6..14ab8675 100644 --- a/examples/src/tests.rs +++ b/examples/src/tests.rs @@ -20,12 +20,8 @@ pub async fn test_app, T: 'static>(mut config: TestConfiguration) - let iad = rend3_test::no_gpu_return!(config.app.create_iad().await).context("InstanceAdapterDevice creation failed")?; - let renderer = rend3::Renderer::new( - iad.clone(), - A::HANDEDNESS, - Some(config.size.x as f32 / config.size.y as f32), - ) - .unwrap(); + let renderer = + rend3::Renderer::new(iad.clone(), A::HANDEDNESS, Some(config.size.x as f32 / config.size.y as f32)).unwrap(); let mut spp = rend3::ShaderPreProcessor::new(); rend3_routine::builtin_shaders(&mut spp); @@ -40,11 +36,7 @@ pub async fn test_app, T: 'static>(mut config: TestConfiguration) - &base_rendergraph.interfaces, &base_rendergraph.gpu_culler.culling_buffer_map_handle, )), - skybox: Mutex::new(rend3_routine::skybox::SkyboxRoutine::new( - &renderer, - &spp, - &base_rendergraph.interfaces, - )), + skybox: Mutex::new(rend3_routine::skybox::SkyboxRoutine::new(&renderer, &spp, &base_rendergraph.interfaces)), tonemapping: Mutex::new(rend3_routine::tonemapping::TonemappingRoutine::new( &renderer, &spp, @@ -66,11 +58,7 @@ pub async fn test_app, T: 'static>(mut config: TestConfiguration) - let texture = renderer.device.create_texture(&wgpu::TextureDescriptor { label: Some("Render Texture"), - size: wgpu::Extent3d { - width: config.size.x, - height: config.size.y, - depth_or_array_layers: 1, - }, + size: wgpu::Extent3d { width: config.size.x, height: config.size.y, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, diff --git a/examples/src/textured_quad/Cargo.toml b/examples/src/textured_quad/Cargo.toml deleted file mode 100644 index 0caac72f..00000000 --- a/examples/src/textured_quad/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "rend3-textured-quad-example" -license = "MIT OR Apache-2.0 OR Zlib" -version = "0.3.0" -authors = ["The rend3 Developers"] -edition = "2021" -publish = false -rust-version = "1.71" - -[[bin]] -name = "textured-quad" -path = "src/main.rs" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -# logging -env_logger = { version = "0.10", default-features = false, features = ["auto-color", "humantime"] } -# Linear algebra library -glam = "0.24" -# Renderer core -rend3 = { version = "^0.3.0", path = "../../rend3" } -# Framework that deals with the event loop, setting up the renderer, and platform differences. -rend3-framework = { version = "^0.3.0", path = "../../rend3-framework" } -# Programmable render list that dictates how the scene renders -rend3-routine = { version = "^0.3.0", path = "../../rend3-routine" } -# windowing -winit = "0.29.4" -# Load image -image = { version = "0.24", default-features = false, features = ["png"]} diff --git a/examples/src/textured_quad/mod.rs b/examples/src/textured_quad/mod.rs index 0d50e780..3435e6d3 100644 --- a/examples/src/textured_quad/mod.rs +++ b/examples/src/textured_quad/mod.rs @@ -111,11 +111,7 @@ impl rend3_framework::App for TexturedQuadExample { } fn handle_event(&mut self, context: rend3_framework::EventContext<'_>, event: winit::event::Event<()>) { - if let winit::event::Event::WindowEvent { - event: winit::event::WindowEvent::Resized(size), - .. - } = event - { + if let winit::event::Event::WindowEvent { event: winit::event::WindowEvent::Resized(size), .. } = event { let size = glam::UVec2::new(size.width, size.height); // Reset camera context.renderer.set_camera_data(rend3::types::Camera { @@ -176,12 +172,7 @@ impl rend3_framework::App for TexturedQuadExample { pub fn main() { let app = TexturedQuadExample::default(); - rend3_framework::start( - app, - winit::window::WindowBuilder::new() - .with_title("textured-quad") - .with_maximized(true), - ) + rend3_framework::start(app, winit::window::WindowBuilder::new().with_title("textured-quad").with_maximized(true)) } #[cfg(test)] diff --git a/rend3-anim/src/lib.rs b/rend3-anim/src/lib.rs index 4f201632..b6e38850 100644 --- a/rend3-anim/src/lib.rs +++ b/rend3-anim/src/lib.rs @@ -84,10 +84,7 @@ impl AnimationData { .iter() .enumerate() .flat_map(|(anim_idx, anim)| { - anim.inner - .channels - .keys() - .map(move |node_idx| (AnimationIndex(anim_idx), NodeIndex(*node_idx))) + anim.inner.channels.keys().map(move |node_idx| (AnimationIndex(anim_idx), NodeIndex(*node_idx))) }) .into_grouping_map() .collect::>(); @@ -99,15 +96,8 @@ impl AnimationData { let skin_index = SkinIndex(skin_index); let anim_affected_nodes = &animation_to_joint_nodes[&animation_idx]; - if skin - .inner - .joints - .iter() - .any(|j| anim_affected_nodes.contains(&NodeIndex(j.inner.node_idx))) - { - let entry = animation_skin_usage - .entry(animation_idx) - .or_insert_with(Default::default); + if skin.inner.joints.iter().any(|j| anim_affected_nodes.contains(&NodeIndex(j.inner.node_idx))) { + let entry = animation_skin_usage.entry(animation_idx).or_insert_with(Default::default); entry.push(skin_index); } } @@ -145,20 +135,10 @@ impl AnimationData { .cloned() .collect(); - skin_data.insert( - skin_index, - PerSkinData { - node_to_joint_idx, - joint_nodes_topological_order, - skeletons, - }, - ); + skin_data.insert(skin_index, PerSkinData { node_to_joint_idx, joint_nodes_topological_order, skeletons }); } - AnimationData { - skin_data, - animation_skin_usage, - } + AnimationData { skin_data, animation_skin_usage } } } @@ -183,11 +163,7 @@ impl Lerp for Quat { /// Samples the data value for an animation channel at a given time. Will /// interpolate between the two closest keyframes. fn sample_at_time(channel: &AnimationChannel, current_time: f32) -> T { - let next_idx = channel - .times - .iter() - .position(|time| *time > current_time) - .unwrap_or(channel.times.len() - 1); + let next_idx = channel.times.iter().position(|time| *time > current_time).unwrap_or(channel.times.len() - 1); let prev_idx = next_idx.saturating_sub(1); let interp_factor = f32::clamp( @@ -217,21 +193,10 @@ pub fn pose_animation_frame( let local_transform = instance.nodes[node_idx].inner.local_transform; let (bind_scale, bind_rotation, bind_translation) = local_transform.to_scale_rotation_translation(); - let translation = channels - .translation - .as_ref() - .map(|tra| sample_at_time(tra, time)) - .unwrap_or(bind_translation); - let rotation = channels - .rotation - .as_ref() - .map(|rot| sample_at_time(rot, time)) - .unwrap_or(bind_rotation); - let mut scale = channels - .scale - .as_ref() - .map(|sca| sample_at_time(sca, time)) - .unwrap_or(bind_scale); + let translation = + channels.translation.as_ref().map(|tra| sample_at_time(tra, time)).unwrap_or(bind_translation); + let rotation = channels.rotation.as_ref().map(|rot| sample_at_time(rot, time)).unwrap_or(bind_rotation); + let mut scale = channels.scale.as_ref().map(|sca| sample_at_time(sca, time)).unwrap_or(bind_scale); if renderer.handedness == Handedness::Left { scale.z = -scale.z @@ -262,21 +227,10 @@ pub fn pose_animation_frame( let local_transform = instance.nodes[node_idx].inner.local_transform; let (bind_scale, bind_rotation, bind_translation) = local_transform.to_scale_rotation_translation(); - let translation = channels - .translation - .as_ref() - .map(|tra| sample_at_time(tra, time)) - .unwrap_or(bind_translation); - let rotation = channels - .rotation - .as_ref() - .map(|rot| sample_at_time(rot, time)) - .unwrap_or(bind_rotation); - let scale = channels - .scale - .as_ref() - .map(|sca| sample_at_time(sca, time)) - .unwrap_or(bind_scale); + let translation = + channels.translation.as_ref().map(|tra| sample_at_time(tra, time)).unwrap_or(bind_translation); + let rotation = channels.rotation.as_ref().map(|rot| sample_at_time(rot, time)).unwrap_or(bind_rotation); + let scale = channels.scale.as_ref().map(|sca| sample_at_time(sca, time)).unwrap_or(bind_scale); let matrix = Mat4::from_scale_rotation_translation(scale, rotation, translation); let joint_idx = node_to_joint_idx[&NodeIndex(node_idx)]; @@ -292,9 +246,7 @@ pub fn pose_animation_frame( if let Some(parent_joint_idx) = node.parent.map(|pi| node_to_joint_idx.get(&NodeIndex(pi))) { // This is guaranteed to be computed because we're iterating // the hierarchy nodes in topological order - let parent_transform = parent_joint_idx - .map(|p| global_joint_transforms[p.0]) - .unwrap_or(Mat4::IDENTITY); + let parent_transform = parent_joint_idx.map(|p| global_joint_transforms[p.0]).unwrap_or(Mat4::IDENTITY); let current_transform = joint_local_matrices[joint_idx.0]; global_joint_transforms[joint_idx.0] = parent_transform * current_transform; diff --git a/rend3-egui/Cargo.toml b/rend3-egui/Cargo.toml index a03d5183..d4697a9f 100644 --- a/rend3-egui/Cargo.toml +++ b/rend3-egui/Cargo.toml @@ -14,7 +14,7 @@ rust-version = "1.71" [dependencies] egui = "0.26" egui-wgpu = "0.26" -glam = "0.24" +glam = "0.25" rend3 = { version = "^0.3.0", path = "../rend3" } wgpu = "0.19.0" wgpu-types = "0.19.0" diff --git a/rend3-egui/src/lib.rs b/rend3-egui/src/lib.rs index fc149a78..1333a803 100644 --- a/rend3-egui/src/lib.rs +++ b/rend3-egui/src/lib.rs @@ -45,10 +45,8 @@ impl EguiRenderRoutine { } pub fn resize(&mut self, new_width: u32, new_height: u32, new_scale_factor: f32) { - self.screen_descriptor = egui_wgpu::ScreenDescriptor { - size_in_pixels: [new_width, new_height], - pixels_per_point: new_scale_factor, - }; + self.screen_descriptor = + egui_wgpu::ScreenDescriptor { size_in_pixels: [new_width, new_height], pixels_per_point: new_scale_factor }; } pub fn add_to_graph<'node>( @@ -61,11 +59,7 @@ impl EguiRenderRoutine { let rpass_handle = builder.add_renderpass( RenderPassTargets { - targets: vec![RenderPassTarget { - color: output, - clear: Vec4::ZERO, - resolve: None, - }], + targets: vec![RenderPassTarget { color: output, clear: Vec4::ZERO, resolve: None }], depth_stencil: None, }, NodeResourceUsage::InputOutput, @@ -83,13 +77,9 @@ impl EguiRenderRoutine { self.internal.free_texture(&texture); } for (id, image_delta) in input.textures_delta.set { - self.internal - .update_texture(&ctx.renderer.device, &ctx.renderer.queue, id, &image_delta); + self.internal.update_texture(&ctx.renderer.device, &ctx.renderer.queue, id, &image_delta); } - let mut cmd_buffer = ctx - .renderer - .device - .create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); + let mut cmd_buffer = ctx.renderer.device.create_command_encoder(&wgpu::CommandEncoderDescriptor::default()); self.internal.update_buffers( &ctx.renderer.device, &ctx.renderer.queue, @@ -99,8 +89,7 @@ impl EguiRenderRoutine { ); drop(cmd_buffer); - self.internal - .render(rpass, input.clipped_meshes, &self.screen_descriptor); + self.internal.render(rpass, input.clipped_meshes, &self.screen_descriptor); }); } @@ -113,11 +102,7 @@ impl EguiRenderRoutine { dimensions: (u32, u32), label: Option<&str>, ) -> egui::TextureId { - let texture_size = wgpu::Extent3d { - width: dimensions.0, - height: dimensions.1, - depth_or_array_layers: 1, - }; + let texture_size = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth_or_array_layers: 1 }; let image_texture = renderer.device.create_texture(&wgpu::TextureDescriptor { size: texture_size, @@ -154,11 +139,7 @@ impl EguiRenderRoutine { let device = &renderer.device; let queue = &renderer.queue; - let texture_size = wgpu::Extent3d { - width: dimensions.0, - height: dimensions.1, - depth_or_array_layers: 1, - }; + let texture_size = wgpu::Extent3d { width: dimensions.0, height: dimensions.1, depth_or_array_layers: 1 }; queue.write_texture( wgpu::ImageCopyTexture { diff --git a/rend3-framework/Cargo.toml b/rend3-framework/Cargo.toml index a3b89678..438185fb 100644 --- a/rend3-framework/Cargo.toml +++ b/rend3-framework/Cargo.toml @@ -14,7 +14,7 @@ rust-version = "1.71" [dependencies] anyhow = "1" cfg-if = "1" -glam = "0.24" +glam = "0.25" log = "0.4" parking_lot = "0.12" profiling = { version = "1", default-features = false } @@ -27,7 +27,7 @@ wgpu = "0.19.0" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # logging -env_logger = { version = "0.10", default-features = false, features = ["auto-color", "humantime"] } +env_logger = { version = "0.11", default-features = false, features = ["auto-color", "humantime"] } pollster = "0.3" [target.'cfg(target_arch = "wasm32")'.dependencies] diff --git a/rend3-framework/src/assets.rs b/rend3-framework/src/assets.rs index 1fb2ee7c..52114efc 100644 --- a/rend3-framework/src/assets.rs +++ b/rend3-framework/src/assets.rs @@ -49,9 +49,7 @@ impl AssetLoader { } ); - Self { - base: SsoString::from(base), - } + Self { base: SsoString::from(base) } } pub fn get_asset_path<'a>(&self, path: AssetPath<'a>) -> Cow<'a, str> { @@ -61,10 +59,7 @@ impl AssetLoader { #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))] pub async fn get_asset(&self, path: AssetPath<'_>) -> Result, AssetError> { let full_path = path.get_path(&self.base); - std::fs::read(&*full_path).map_err(|error| AssetError::FileError { - path: SsoString::from(full_path), - error, - }) + std::fs::read(&*full_path).map_err(|error| AssetError::FileError { path: SsoString::from(full_path), error }) } #[cfg(target_os = "android")] @@ -83,10 +78,7 @@ impl AssetLoader { .and_then(|mut file| { file.get_buffer() .map(|b| b.to_vec()) - .map_err(|error| AssetError::FileError { - path: SsoString::from(full_path), - error, - }) + .map_err(|error| AssetError::FileError { path: SsoString::from(full_path), error }) }) } @@ -96,15 +88,12 @@ impl AssetLoader { gloo_net::http::Request::get(&full_path) .build() - .map_err(|error| AssetError::NetworkError { - path: SsoString::from(&*full_path), - error, - })? + .map_err(|error| AssetError::NetworkError { path: SsoString::from(&*full_path), error })? + .send() + .await + .map_err(|error| AssetError::NetworkError { path: SsoString::from(&*full_path), error })? .binary() .await - .map_err(|error| AssetError::NetworkError { - path: SsoString::from(&*full_path), - error, - }) + .map_err(|error| AssetError::NetworkError { path: SsoString::from(&*full_path), error }) } } diff --git a/rend3-framework/src/grab/wasm.rs b/rend3-framework/src/grab/wasm.rs index 85d2dafd..56cbd4e8 100644 --- a/rend3-framework/src/grab/wasm.rs +++ b/rend3-framework/src/grab/wasm.rs @@ -18,10 +18,7 @@ pub struct Grabber { } impl Grabber { pub fn new(window: &Window) -> Self { - let inner = Arc::new(GrabberInner { - grabbed: AtomicBool::new(false), - callback: OnceBox::new(), - }); + let inner = Arc::new(GrabberInner { grabbed: AtomicBool::new(false), callback: OnceBox::new() }); let inner_clone = Arc::clone(&inner); @@ -54,9 +51,7 @@ impl Grabber { let document = canvas.owner_document().unwrap(); canvas.request_pointer_lock(); - document - .add_event_listener_with_callback("pointerlockchange", self.inner.callback.get().unwrap()) - .unwrap(); + document.add_event_listener_with_callback("pointerlockchange", self.inner.callback.get().unwrap()).unwrap(); self.inner.grabbed.store(true, Ordering::Relaxed); } @@ -65,9 +60,7 @@ impl Grabber { let canvas = window.canvas().unwrap(); let document = canvas.owner_document().unwrap(); - document - .remove_event_listener_with_callback("pointerlockchange", self.inner.callback.get().unwrap()) - .unwrap(); + document.remove_event_listener_with_callback("pointerlockchange", self.inner.callback.get().unwrap()).unwrap(); document.exit_pointer_lock(); self.inner.grabbed.store(false, Ordering::Relaxed); diff --git a/rend3-framework/src/lib.rs b/rend3-framework/src/lib.rs index 188a4417..dcc12303 100644 --- a/rend3-framework/src/lib.rs +++ b/rend3-framework/src/lib.rs @@ -71,10 +71,8 @@ pub trait App { console_log::init().unwrap(); #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))] - if let Err(e) = env_logger::builder() - .filter_module("rend3", log::LevelFilter::Info) - .parse_default_env() - .try_init() + if let Err(e) = + env_logger::builder().filter_module("rend3", log::LevelFilter::Info).parse_default_env().try_init() { eprintln!("Error registering logger from Rend3 framework: {:?}", e); // probably ran two runs in sequence and initialized twice @@ -199,12 +197,9 @@ pub async fn async_start + 'static, T: 'static>(mut app: A, window_bui }; // Make us a renderer. - let renderer = rend3::Renderer::new( - iad.clone(), - A::HANDEDNESS, - Some(window_size.width as f32 / window_size.height as f32), - ) - .unwrap(); + let renderer = + rend3::Renderer::new(iad.clone(), A::HANDEDNESS, Some(window_size.width as f32 / window_size.height as f32)) + .unwrap(); // Get the preferred format for the surface. // @@ -238,11 +233,7 @@ pub async fn async_start + 'static, T: 'static>(mut app: A, window_bui &base_rendergraph.interfaces, &base_rendergraph.gpu_culler.culling_buffer_map_handle, )), - skybox: Mutex::new(rend3_routine::skybox::SkyboxRoutine::new( - &renderer, - &spp, - &base_rendergraph.interfaces, - )), + skybox: Mutex::new(rend3_routine::skybox::SkyboxRoutine::new(&renderer, &spp, &base_rendergraph.interfaces)), tonemapping: Mutex::new(rend3_routine::tonemapping::TonemappingRoutine::new( &renderer, &spp, @@ -253,10 +244,7 @@ pub async fn async_start + 'static, T: 'static>(mut app: A, window_bui drop(data_core); app.setup(SetupContext { - windowing: Some(WindowingSetup { - event_loop: &event_loop, - window: &window, - }), + windowing: Some(WindowingSetup { event_loop: &event_loop, window: &window }), renderer: &renderer, routines: &routines, surface_format: format, @@ -294,15 +282,9 @@ pub async fn async_start + 'static, T: 'static>(mut app: A, window_bui event_loop, move |event: Event, event_loop_window_target: &EventLoopWindowTarget| { let mut control_flow = event_loop_window_target.control_flow(); - if let Some(suspend) = handle_surface( - &app, - &window, - &event, - &iad.instance, - &mut surface, - &renderer, - &mut stored_surface_info, - ) { + if let Some(suspend) = + handle_surface(&app, &window, &event, &iad.instance, &mut surface, &renderer, &mut stored_surface_info) + { suspended = suspend; } @@ -318,21 +300,13 @@ pub async fn async_start + 'static, T: 'static>(mut app: A, window_bui } // Close button was clicked, we should close. - if let winit::event::Event::WindowEvent { - event: winit::event::WindowEvent::CloseRequested, - .. - } = event - { + if let winit::event::Event::WindowEvent { event: winit::event::WindowEvent::CloseRequested, .. } = event { event_loop_window_target.exit(); return; } // We need to block all updates - if let Event::WindowEvent { - window_id: _, - event: winit::event::WindowEvent::RedrawRequested, - } = event - { + if let Event::WindowEvent { window_id: _, event: winit::event::WindowEvent::RedrawRequested } = event { if suspended { return; } @@ -436,10 +410,7 @@ fn handle_surface, T: 'static>( *surface = None; Some(true) } - Event::WindowEvent { - event: winit::event::WindowEvent::Resized(size), - .. - } => { + Event::WindowEvent { event: winit::event::WindowEvent::Resized(size), .. } => { log::debug!("resize {:?}", size); let size = UVec2::new(size.width, size.height); diff --git a/rend3-gltf/Cargo.toml b/rend3-gltf/Cargo.toml index e85a1c3c..a3ca254f 100644 --- a/rend3-gltf/Cargo.toml +++ b/rend3-gltf/Cargo.toml @@ -20,7 +20,7 @@ base64 = "0.22" bytemuck = "1" ddsfile = { version = "0.5", optional = true } float-ord = "0.3.2" -glam = "0.24" +glam = "0.25" gltf = { version = "1.0", default-features = false, features = ["KHR_lights_punctual", "KHR_texture_transform", "KHR_materials_unlit", "extras", "names", "utils"] } image = { version = "0.24", default-features = false } ktx2 = { version = "0.3", optional = true } diff --git a/rend3-gltf/src/lib.rs b/rend3-gltf/src/lib.rs index 21606a82..43789893 100644 --- a/rend3-gltf/src/lib.rs +++ b/rend3-gltf/src/lib.rs @@ -50,10 +50,7 @@ pub struct Labeled { impl Labeled { /// Create a new pub fn new(inner: T, label: Option<&str>) -> Self { - Self { - inner, - label: label.map(SsoString::from), - } + Self { inner, label: label.map(SsoString::from) } } } @@ -157,12 +154,7 @@ pub struct PosRotScale { impl PosRotScale { pub fn new(node_idx: u32) -> Self { - Self { - node_idx, - translation: None, - rotation: None, - scale: None, - } + Self { node_idx, translation: None, rotation: None, scale: None } } } @@ -372,11 +364,7 @@ where Mat4::from_scale(Vec3::new( settings.scale, settings.scale, - if renderer.handedness == Handedness::Left { - -settings.scale - } else { - settings.scale - }, + if renderer.handedness == Handedness::Left { -settings.scale } else { settings.scale }, )), )?; @@ -413,14 +401,7 @@ where let skins = load_skins(file.skins(), &buffers)?; let animations = load_animations(file.animations(), &buffers)?; - let loaded = LoadedGltfScene { - meshes, - materials, - default_material, - images, - skins, - animations, - }; + let loaded = LoadedGltfScene { meshes, materials, default_material, images, skins, animations }; Ok(loaded) } @@ -435,19 +416,13 @@ pub fn add_mesh_by_index( skin_index: Option, transform: Mat4, ) -> Result, GltfLoadError> { - let mesh_handle = loaded - .meshes - .get(mesh_index) - .ok_or(GltfLoadError::MissingMesh(mesh_index))?; + let mesh_handle = loaded.meshes.get(mesh_index).ok_or(GltfLoadError::MissingMesh(mesh_index))?; let mut primitives = Vec::new(); let mut skeletons = Vec::new(); let skin = if let Some(skin_index) = skin_index { - let skin = loaded - .skins - .get(skin_index) - .ok_or(GltfLoadError::MissingSkin(skin_index))?; + let skin = loaded.skins.get(skin_index).ok_or(GltfLoadError::MissingSkin(skin_index))?; Some(skin) } else { None @@ -456,10 +431,7 @@ pub fn add_mesh_by_index( for prim in &mesh_handle.inner.primitives { let mat_idx = prim.material; let mat = mat_idx - .map_or_else( - || Some(&loaded.default_material), - |mat_idx| loaded.materials.get(mat_idx).map(|m| &m.inner), - ) + .map_or_else(|| Some(&loaded.default_material), |mat_idx| loaded.materials.get(mat_idx).map(|m| &m.inner)) .ok_or_else(|| GltfLoadError::MissingMaterial(mat_idx.expect("Could not find default material")))?; let mesh_kind = if let Some(skin) = skin { @@ -475,18 +447,11 @@ pub fn add_mesh_by_index( ObjectMeshKind::Static(prim.handle.clone()) }; - primitives.push(renderer.add_object(types::Object { - mesh_kind, - material: mat.clone(), - transform, - })); + primitives.push(renderer.add_object(types::Object { mesh_kind, material: mat.clone(), transform })); } Ok(Labeled::new( - Object { - primitives, - armature: skin_index.map(|skin_index| Armature { skeletons, skin_index }), - }, + Object { primitives, armature: skin_index.map(|skin_index| Armature { skeletons, skin_index }) }, name, )) } @@ -502,10 +467,8 @@ fn node_indices_topological_sort(nodes: &[gltf::Node]) -> (Vec, BTreeMap< } // Maps child to parent - let parents: BTreeMap = children - .iter() - .flat_map(|(parent, children)| children.iter().map(|ch| (*ch, *parent))) - .collect(); + let parents: BTreeMap = + children.iter().flat_map(|(parent, children)| children.iter().map(|ch| (*ch, *parent))).collect(); // Initialize the BFS queue with nodes that don't have any parent (i.e. roots) let mut queue: VecDeque = children.keys().filter(|n| parents.get(n).is_none()).cloned().collect(); @@ -547,10 +510,7 @@ pub fn instance_loaded_scene( let node = &nodes[*node_idx]; let local_transform = Mat4::from_cols_array_2d(&node.transform().matrix()); - let parent_transform = parents - .get(&node.index()) - .map(|p| node_transforms[*p]) - .unwrap_or(parent_transform); + let parent_transform = parents.get(&node.index()).map(|p| node_transforms[*p]).unwrap_or(parent_transform); let transform = parent_transform * local_transform; node_transforms[*node_idx] = transform; @@ -598,10 +558,7 @@ pub fn instance_loaded_scene( node.name(), ) } - Ok(GltfSceneInstance { - nodes: final_nodes, - topological_order, - }) + Ok(GltfSceneInstance { nodes: final_nodes, topological_order }) } /// Loads buffers from a [`gltf::Buffer`] iterator, calling io_func to resolve @@ -631,9 +588,9 @@ where blob_index = Some(b.index()); Vec::new() } - Source::Uri(uri) => io_func(SsoString::from(uri)) - .await - .map_err(|e| GltfLoadError::BufferIo(SsoString::from(uri), e))?, + Source::Uri(uri) => { + io_func(SsoString::from(uri)).await.map_err(|e| GltfLoadError::BufferIo(SsoString::from(uri), e))? + } }; buffers.push(data); } @@ -659,11 +616,7 @@ pub fn load_meshes<'a, E: std::error::Error + 'static>( let mut res_prims = Vec::new(); for prim in mesh.primitives() { if prim.mode() != gltf::mesh::Mode::Triangles { - return Err(GltfLoadError::UnsupportedPrimitiveMode( - mesh.index(), - prim.index(), - prim.mode(), - )); + return Err(GltfLoadError::UnsupportedPrimitiveMode(mesh.index(), prim.index(), prim.mode())); } let reader = prim.reader(|b| Some(&buffers[b.index()][..b.length()])); @@ -713,16 +666,11 @@ pub fn load_meshes<'a, E: std::error::Error + 'static>( builder = builder.with_vertex_joint_weights(joint_weights.into_f32().map(Vec4::from).collect()) } - let mesh = builder - .build() - .map_err(|valid| GltfLoadError::MeshValidationError(mesh.index(), valid))?; + let mesh = builder.build().map_err(|valid| GltfLoadError::MeshValidationError(mesh.index(), valid))?; let handle = renderer.add_mesh(mesh)?; - res_prims.push(MeshPrimitive { - handle, - material: prim.material().index(), - }) + res_prims.push(MeshPrimitive { handle, material: prim.material().index() }) } Ok(Labeled::new(Mesh { primitives: res_prims }, mesh.name())) }) @@ -747,18 +695,9 @@ fn load_skins( vec![Mat4::IDENTITY; num_joints] }; - let joints = skin - .joints() - .map(|node| Labeled::new(Joint { node_idx: node.index() }, node.name())) - .collect(); + let joints = skin.joints().map(|node| Labeled::new(Joint { node_idx: node.index() }, node.name())).collect(); - res_skins.push(Labeled::new( - Skin { - inverse_bind_matrices: inv_b_mats, - joints, - }, - skin.name(), - )) + res_skins.push(Labeled::new(Skin { inverse_bind_matrices: inv_b_mats, joints }, skin.name())) } Ok(res_skins) @@ -766,14 +705,7 @@ fn load_skins( fn compute_animation_duration(channels: &HashMap) -> f32 { fn channel_duration(channel: &AnimationChannel) -> f32 { - channel - .times - .iter() - .copied() - .map(float_ord::FloatOrd) - .max() - .map(|f_ord| f_ord.0) - .unwrap_or(0.0) + channel.times.iter().copied().map(float_ord::FloatOrd).max().map(|f_ord| f_ord.0).unwrap_or(0.0) } channels .values() @@ -803,9 +735,7 @@ fn load_animations( // Get the PosRotScale for the current target node or create a new // one if it doesn't exist. - let chs = result_channels - .entry(node_idx) - .or_insert_with(|| PosRotScale::new(node_idx as u32)); + let chs = result_channels.entry(node_idx).or_insert_with(|| PosRotScale::new(node_idx as u32)); let reader = ch.reader(|b| Some(&buffers[b.index()][..b.length()])); @@ -817,27 +747,16 @@ fn load_animations( // And 'outputs' means the keyframe values, which varies depending on the type // of keyframe - match reader - .read_outputs() - .ok_or_else(|| GltfLoadError::MissingKeyframeValues(anim.index(), ch_idx))? - { + match reader.read_outputs().ok_or_else(|| GltfLoadError::MissingKeyframeValues(anim.index(), ch_idx))? { gltf::animation::util::ReadOutputs::Translations(trs) => { - chs.translation = Some(AnimationChannel { - values: trs.map(Vec3::from).collect(), - times, - }) + chs.translation = Some(AnimationChannel { values: trs.map(Vec3::from).collect(), times }) } gltf::animation::util::ReadOutputs::Rotations(rots) => { - chs.rotation = Some(AnimationChannel { - values: rots.into_f32().map(Quat::from_array).collect(), - times, - }); + chs.rotation = + Some(AnimationChannel { values: rots.into_f32().map(Quat::from_array).collect(), times }); } gltf::animation::util::ReadOutputs::Scales(scls) => { - chs.scale = Some(AnimationChannel { - values: scls.map(Vec3::from).collect(), - times, - }); + chs.scale = Some(AnimationChannel { values: scls.map(Vec3::from).collect(), times }); } gltf::animation::util::ReadOutputs::MorphTargetWeights(_) => { // TODO @@ -846,10 +765,7 @@ fn load_animations( } result.push(Labeled::new( - Animation { - duration: compute_animation_duration(&result_channels), - channels: result_channels, - }, + Animation { duration: compute_animation_duration(&result_channels), channels: result_channels }, anim.name(), )) } @@ -967,16 +883,13 @@ where value: Vec4::from(albedo_factor), srgb: false, }, - None => pbr::AlbedoComponent::ValueVertex { - value: Vec4::from(albedo_factor), - srgb: false, - }, + None => pbr::AlbedoComponent::ValueVertex { value: Vec4::from(albedo_factor), srgb: false }, }, transparency: match material.alpha_mode() { gltf::material::AlphaMode::Opaque => pbr::Transparency::Opaque, - gltf::material::AlphaMode::Mask => pbr::Transparency::Cutout { - cutout: material.alpha_cutoff().unwrap_or(0.5), - }, + gltf::material::AlphaMode::Mask => { + pbr::Transparency::Cutout { cutout: material.alpha_cutoff().unwrap_or(0.5) } + } gltf::material::AlphaMode::Blend => pbr::Transparency::Blend, }, normal: match normals_tex { @@ -989,9 +902,7 @@ where _ => pbr::NormalTexture::None, }, aomr_textures: match (metallic_roughness_tex, occlusion_tex) { - (Some(mr), Some(ao)) if mr == ao => pbr::AoMRTextures::Combined { - texture: Some(mr.handle), - }, + (Some(mr), Some(ao)) if mr == ao => pbr::AoMRTextures::Combined { texture: Some(mr.handle) }, (mr, ao) if ao .as_ref() @@ -1011,10 +922,9 @@ where metallic_factor: Some(metallic_factor), roughness_factor: Some(roughness_factor), emissive: match emissive_tex { - Some(tex) => pbr::MaterialComponent::TextureValue { - texture: tex.handle, - value: Vec3::from(emissive_factor), - }, + Some(tex) => { + pbr::MaterialComponent::TextureValue { texture: tex.handle, value: Vec3::from(emissive_factor) } + } None => pbr::MaterialComponent::Value(Vec3::from(emissive_factor)), }, uv_transform0: uv_transform, @@ -1051,10 +961,7 @@ where Fut: Future, E>>, E: std::error::Error + 'static, { - let key = ImageKey { - index: image.index(), - srgb, - }; + let key = ImageKey { index: image.index(), srgb }; let entry = match images.entry(key) { Entry::Occupied(handle) => return Ok(handle.get().clone()), @@ -1089,18 +996,14 @@ where // profiling::scope!("load image", image.name().unwrap_or_default()); let (data, uri) = match image.source() { gltf::image::Source::Uri { uri, .. } => { - let data = io_func(SsoString::from(uri)) - .await - .map_err(|e| GltfLoadError::TextureIo(SsoString::from(uri), e))?; + let data = + io_func(SsoString::from(uri)).await.map_err(|e| GltfLoadError::TextureIo(SsoString::from(uri), e))?; (Cow::Owned(data), SsoString::from(uri)) } gltf::image::Source::View { view, .. } => { let start = view.offset(); let end = start + view.length(); - ( - Cow::Borrowed(&buffers[view.buffer().index()][start..end]), - SsoString::from(""), - ) + (Cow::Borrowed(&buffers[view.buffer().index()][start..end]), SsoString::from("")) } }; @@ -1126,9 +1029,7 @@ where let guaranteed_format = format.guaranteed_format_features(Default::default()); let generate = header.level_count == 1 - && guaranteed_format - .flags - .contains(rend3::types::TextureFormatFeatureFlags::FILTERABLE) + && guaranteed_format.flags.contains(rend3::types::TextureFormatFeatureFlags::FILTERABLE) && guaranteed_format.allowed_usages.contains( rend3::types::TextureUsages::TEXTURE_BINDING | rend3::types::TextureUsages::RENDER_ATTACHMENT, ); @@ -1150,11 +1051,7 @@ where } else { types::MipmapCount::Specific(std::num::NonZeroU32::new(header.level_count).unwrap()) }, - mip_source: if generate { - types::MipmapSource::Generated - } else { - types::MipmapSource::Uploaded - }, + mip_source: if generate { types::MipmapSource::Generated } else { types::MipmapSource::Uploaded }, }) } @@ -1184,16 +1081,12 @@ where let guaranteed_format = format.guaranteed_format_features(Default::default()); let generate = dds.get_num_mipmap_levels() == 1 - && guaranteed_format - .flags - .contains(rend3::types::TextureFormatFeatureFlags::FILTERABLE) + && guaranteed_format.flags.contains(rend3::types::TextureFormatFeatureFlags::FILTERABLE) && guaranteed_format.allowed_usages.contains( rend3::types::TextureUsages::TEXTURE_BINDING | rend3::types::TextureUsages::RENDER_ATTACHMENT, ); - let data = dds - .get_data(0) - .map_err(|_| GltfLoadError::TextureTooManyLayers(uri.take().unwrap()))?; + let data = dds.get_data(0).map_err(|_| GltfLoadError::TextureTooManyLayers(uri.take().unwrap()))?; texture = Some(types::Texture { label: image.name().map(str::to_owned), @@ -1205,11 +1098,7 @@ where } else { types::MipmapCount::Specific(std::num::NonZeroU32::new(dds.get_num_mipmap_levels()).unwrap()) }, - mip_source: if generate { - types::MipmapSource::Generated - } else { - types::MipmapSource::Uploaded - }, + mip_source: if generate { types::MipmapSource::Generated } else { types::MipmapSource::Uploaded }, }) } } @@ -1277,10 +1166,9 @@ pub mod util { // profiling::scope!("convert dynamic image"); match image { image::DynamicImage::ImageLuma8(i) => (i.into_raw(), r3F::R8Unorm), - image::DynamicImage::ImageLumaA8(i) => ( - ConvertBuffer::, Vec>>::convert(&i).into_raw(), - r3F::R8Unorm, - ), + image::DynamicImage::ImageLumaA8(i) => { + (ConvertBuffer::, Vec>>::convert(&i).into_raw(), r3F::R8Unorm) + } image::DynamicImage::ImageRgb8(i) => ( ConvertBuffer::, Vec>>::convert(&i).into_raw(), if srgb { r3F::Rgba8UnormSrgb } else { r3F::Rgba8Unorm }, @@ -1288,10 +1176,7 @@ pub mod util { image::DynamicImage::ImageRgba8(i) => { (i.into_raw(), if srgb { r3F::Rgba8UnormSrgb } else { r3F::Rgba8Unorm }) } - i => ( - i.into_rgba8().into_raw(), - if srgb { r3F::Rgba8UnormSrgb } else { r3F::Rgba8Unorm }, - ), + i => (i.into_rgba8().into_raw(), if srgb { r3F::Rgba8UnormSrgb } else { r3F::Rgba8Unorm }), } } @@ -1471,115 +1356,59 @@ pub mod util { k2F::EAC_R11G11_SNORM_BLOCK => r3F::EacRg11Snorm, k2F::ASTC_4x4_UNORM_BLOCK | k2F::ASTC_4x4_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B4x4, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_5x4_UNORM_BLOCK | k2F::ASTC_5x4_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B5x4, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_5x5_UNORM_BLOCK | k2F::ASTC_5x5_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B5x5, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_6x5_UNORM_BLOCK | k2F::ASTC_6x5_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B6x5, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_6x6_UNORM_BLOCK | k2F::ASTC_6x6_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B6x6, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_8x5_UNORM_BLOCK | k2F::ASTC_8x5_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B8x5, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_8x6_UNORM_BLOCK | k2F::ASTC_8x6_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B8x6, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_8x8_UNORM_BLOCK | k2F::ASTC_8x8_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B8x8, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_10x5_UNORM_BLOCK | k2F::ASTC_10x5_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B10x5, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_10x6_UNORM_BLOCK | k2F::ASTC_10x6_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B10x6, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_10x8_UNORM_BLOCK | k2F::ASTC_10x8_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B10x8, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_10x10_UNORM_BLOCK | k2F::ASTC_10x10_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B10x10, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_12x10_UNORM_BLOCK | k2F::ASTC_12x10_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B12x10, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, k2F::ASTC_12x12_UNORM_BLOCK | k2F::ASTC_12x12_SRGB_BLOCK => r3F::Astc { block: AstcBlock::B12x12, - channel: if srgb { - AstcChannel::UnormSrgb - } else { - AstcChannel::Unorm - }, + channel: if srgb { AstcChannel::UnormSrgb } else { AstcChannel::Unorm }, }, _ => return None, }) diff --git a/rend3-routine/Cargo.toml b/rend3-routine/Cargo.toml index a1c0a398..9d7c4554 100644 --- a/rend3-routine/Cargo.toml +++ b/rend3-routine/Cargo.toml @@ -16,9 +16,9 @@ arrayvec = "0.7" bitflags = "2" bytemuck = "1" codespan-reporting = "0.11" -encase = { version = "0.6", features = ["glam"] } +encase = { version = "0.7", features = ["glam"] } flume = "0.11" -glam = { version = "0.24.0", features = ["bytemuck"] } +glam = { version = "0.25.0", features = ["bytemuck"] } log = "0.4" naga = { version = "0.19.0", features = ["wgsl-in"] } ordered-float = "4" diff --git a/rend3-routine/src/base.rs b/rend3-routine/src/base.rs index 8b6dcc9b..304684f5 100644 --- a/rend3-routine/src/base.rs +++ b/rend3-routine/src/base.rs @@ -65,10 +65,7 @@ impl DepthTargets { }) }); - Self { - single_sample_mipped, - multi_sample, - } + Self { single_sample_mipped, multi_sample } } pub fn rendering_target(&self) -> RenderTargetHandle { @@ -123,12 +120,7 @@ impl BaseRenderGraph { let gpu_skinner = skinning::GpuSkinner::new(&renderer.device, spp); - Self { - interfaces, - samplers, - gpu_culler, - gpu_skinner, - } + Self { interfaces, samplers, gpu_culler, gpu_skinner } } /// Add this to the rendergraph. This is the function you should start @@ -263,11 +255,7 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { }); let depth = DepthTargets::new(graph, inputs.target.resolution, inputs.target.samples); let primary_renderpass = graph::RenderPassTargets { - targets: vec![graph::RenderPassTarget { - color, - resolve, - clear: settings.clear_color, - }], + targets: vec![graph::RenderPassTarget { color, resolve, clear: settings.clear_color }], depth_stencil: Some(graph::RenderPassDepthTarget { target: depth.rendering_target(), depth_clear: Some(0.0), @@ -378,9 +366,7 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { pub fn pbr_shadow_rendering(&mut self) { let iter = zip(&self.shadow_cull, &self.inputs.eval_output.shadows); for (shadow_index, (shadow_cull, desc)) in iter.enumerate() { - let target = self - .shadow - .set_viewport(ViewportRect::new(desc.map.offset, UVec2::splat(desc.map.size))); + let target = self.shadow.set_viewport(ViewportRect::new(desc.map.offset, UVec2::splat(desc.map.size))); let renderpass = graph::RenderPassTargets { targets: vec![], depth_stencil: Some(graph::RenderPassDepthTarget { @@ -390,10 +376,7 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { }), }; - let routines = [ - &self.inputs.routines.pbr.opaque_depth, - &self.inputs.routines.pbr.cutout_depth, - ]; + let routines = [&self.inputs.routines.pbr.opaque_depth, &self.inputs.routines.pbr.cutout_depth]; for routine in routines { routine.add_forward_to_graph(ForwardRoutineArgs { graph: self.graph, @@ -426,10 +409,7 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { /// Render the PBR materials. pub fn pbr_render_opaque_predicted_triangles(&mut self) { - let routines = [ - &self.inputs.routines.pbr.opaque_routine, - &self.inputs.routines.pbr.cutout_routine, - ]; + let routines = [&self.inputs.routines.pbr.opaque_routine, &self.inputs.routines.pbr.cutout_routine]; for routine in routines { routine.add_forward_to_graph(ForwardRoutineArgs { graph: self.graph, @@ -449,10 +429,7 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { /// Render the PBR materials. pub fn pbr_render_opaque_residual_triangles(&mut self) { - let routines = [ - &self.inputs.routines.pbr.opaque_routine, - &self.inputs.routines.pbr.cutout_routine, - ]; + let routines = [&self.inputs.routines.pbr.opaque_routine, &self.inputs.routines.pbr.cutout_routine]; for routine in routines { routine.add_forward_to_graph(ForwardRoutineArgs { graph: self.graph, @@ -472,31 +449,23 @@ impl<'a, 'node> BaseRenderGraphIntermediateState<'a, 'node> { /// Render the PBR materials. pub fn pbr_forward_rendering_transparent(&mut self) { - self.inputs - .routines - .pbr - .blend_routine - .add_forward_to_graph(ForwardRoutineArgs { - graph: self.graph, - label: "PBR Forward Transparent", - camera: CameraSpecifier::Viewport, - binding_data: forward::ForwardRoutineBindingData { - whole_frame_uniform_bg: self.forward_uniform_bg, - per_material_bgl: &self.inputs.routines.pbr.per_material, - extra_bgs: None, - }, - culling_source: forward::CullingSource::Residual(self.cull), - samples: self.inputs.target.samples, - renderpass: self.primary_renderpass.clone(), - }); + self.inputs.routines.pbr.blend_routine.add_forward_to_graph(ForwardRoutineArgs { + graph: self.graph, + label: "PBR Forward Transparent", + camera: CameraSpecifier::Viewport, + binding_data: forward::ForwardRoutineBindingData { + whole_frame_uniform_bg: self.forward_uniform_bg, + per_material_bgl: &self.inputs.routines.pbr.per_material, + extra_bgs: None, + }, + culling_source: forward::CullingSource::Residual(self.cull), + samples: self.inputs.target.samples, + renderpass: self.primary_renderpass.clone(), + }); } pub fn hi_z(&mut self) { - self.inputs - .routines - .pbr - .hi_z - .add_hi_z_to_graph(self.graph, self.depth, self.inputs.target.resolution); + self.inputs.routines.pbr.hi_z.add_hi_z_to_graph(self.graph, self.depth, self.inputs.target.resolution); } /// Tonemap onto the given render target. diff --git a/rend3-routine/src/common/interfaces.rs b/rend3-routine/src/common/interfaces.rs index 015f66d4..9361ce22 100644 --- a/rend3-routine/src/common/interfaces.rs +++ b/rend3-routine/src/common/interfaces.rs @@ -60,10 +60,7 @@ impl WholeFrameInterfaces { let forward_uniform_bgl = uniform_bglb.build(device, Some("forward uniform bgl")); - Self { - depth_uniform_bgl: shadow_uniform_bgl, - forward_uniform_bgl, - } + Self { depth_uniform_bgl: shadow_uniform_bgl, forward_uniform_bgl } } } @@ -144,9 +141,6 @@ impl PerMaterialArchetypeInterface { ) .build(device, Some("per material bgl")); - Self { - bgl, - _phantom: PhantomData, - } + Self { bgl, _phantom: PhantomData } } } diff --git a/rend3-routine/src/common/samplers.rs b/rend3-routine/src/common/samplers.rs index 1935b711..3fbf4ffa 100644 --- a/rend3-routine/src/common/samplers.rs +++ b/rend3-routine/src/common/samplers.rs @@ -23,37 +23,19 @@ impl Samplers { let nearest = create_sampler(device, FilterMode::Nearest, None); let shadow = create_sampler(device, FilterMode::Linear, Some(CompareFunction::GreaterEqual)); - Self { - linear, - nearest, - shadow, - } + Self { linear, nearest, shadow } } /// Add the samplers to the given bind group layout builder. pub fn add_to_bgl(bglb: &mut BindGroupLayoutBuilder) { - bglb.append( - ShaderStages::FRAGMENT, - BindingType::Sampler(SamplerBindingType::Filtering), - None, - ) - .append( - ShaderStages::FRAGMENT, - BindingType::Sampler(SamplerBindingType::NonFiltering), - None, - ) - .append( - ShaderStages::FRAGMENT, - BindingType::Sampler(SamplerBindingType::Comparison), - None, - ); + bglb.append(ShaderStages::FRAGMENT, BindingType::Sampler(SamplerBindingType::Filtering), None) + .append(ShaderStages::FRAGMENT, BindingType::Sampler(SamplerBindingType::NonFiltering), None) + .append(ShaderStages::FRAGMENT, BindingType::Sampler(SamplerBindingType::Comparison), None); } /// Add the samplers to the given bind group builder. pub fn add_to_bg<'a>(&'a self, bgb: &mut BindGroupBuilder<'a>) { - bgb.append_sampler(&self.linear) - .append_sampler(&self.nearest) - .append_sampler(&self.shadow); + bgb.append_sampler(&self.linear).append_sampler(&self.nearest).append_sampler(&self.shadow); } } diff --git a/rend3-routine/src/culling/batching.rs b/rend3-routine/src/culling/batching.rs index 5e5bcdb0..9858dee5 100644 --- a/rend3-routine/src/culling/batching.rs +++ b/rend3-routine/src/culling/batching.rs @@ -105,9 +105,7 @@ pub struct PerCameraPreviousInvocationsMap { } impl PerCameraPreviousInvocationsMap { pub fn new() -> Self { - Self { - inner: HashMap::default(), - } + Self { inner: HashMap::default() } } pub fn get_and_reset_camera(&mut self, camera: CameraSpecifier) -> FastHashMap { @@ -131,10 +129,7 @@ pub(super) fn batch_objects( let previous_invocation_map = per_camera_previous_invocation_map.get_and_reset_camera(camera_specifier); let mut current_invocation_map = FastHashMap::default(); - let mut jobs = ShaderBatchDatas { - jobs: Vec::new(), - regions: Vec::new(), - }; + let mut jobs = ShaderBatchDatas { jobs: Vec::new(), regions: Vec::new() }; let objects = match ctx.data_core.object_manager.enumerated_objects::() { Some(o) => o, @@ -153,28 +148,19 @@ pub(super) fn batch_objects( } let material = material_archetype.material(*object.material_handle); - let bind_group_index = material - .bind_group_index - .map_gpu(|_| TextureBindGroupIndex::DUMMY) - .into_common(); + let bind_group_index = material.bind_group_index.map_gpu(|_| TextureBindGroupIndex::DUMMY).into_common(); let material_key = material.inner.key(); let sorting = material.inner.sorting(); - let mut distance_sq = ctx - .data_core - .viewport_camera_state - .location() - .distance_squared(object.location.into()); + let mut distance_sq = + ctx.data_core.viewport_camera_state.location().distance_squared(object.location.into()); if sorting.order == SortingOrder::BackToFront { distance_sq = -distance_sq; } sorted_objects.push(( ShaderJobSortingKey { - job_key: ShaderJobKey { - material_key, - bind_group_index, - }, + job_key: ShaderJobKey { material_key, bind_group_index }, distance: OrderedFloat(distance_sq), sorting_reason: sorting.reason, }, @@ -202,16 +188,7 @@ pub(super) fn batch_objects( let max_dispatch_count = ctx.renderer.limits.max_compute_workgroups_per_dimension; - for ( - ShaderJobSortingKey { - job_key: key, - sorting_reason, - .. - }, - handle, - object, - ) in sorted_objects - { + for (ShaderJobSortingKey { job_key: key, sorting_reason, .. }, handle, object) in sorted_objects { let invocation_count = object.inner.index_count / 3; let key_difference = key != current_key; @@ -219,10 +196,7 @@ pub(super) fn batch_objects( let dispatch_limit = (current_invocation + invocation_count) >= max_dispatch_count * WORKGROUP_SIZE; if key_difference || object_limit || dispatch_limit { - jobs.regions.push(JobSubRegion { - job_index: jobs.jobs.len() as u32, - key: current_key, - }); + jobs.regions.push(JobSubRegion { job_index: jobs.jobs.len() as u32, key: current_key }); current_region_idx += 1; current_key = key; current_region_object_index = 0; @@ -261,10 +235,7 @@ pub(super) fn batch_objects( current_invocation += round_up(invocation_count, WORKGROUP_SIZE); } - jobs.regions.push(JobSubRegion { - job_index: jobs.jobs.len() as u32, - key: current_key, - }); + jobs.regions.push(JobSubRegion { job_index: jobs.jobs.len() as u32, key: current_key }); jobs.jobs.push(ShaderBatchData { object_culling_information: current_ranges, total_objects: current_object_index, diff --git a/rend3-routine/src/culling/culler.rs b/rend3-routine/src/culling/culler.rs index e0b4e32e..58fbce21 100644 --- a/rend3-routine/src/culling/culler.rs +++ b/rend3-routine/src/culling/culler.rs @@ -120,8 +120,7 @@ impl CullingBuffers { ) { self.index_buffer.swap(queue, device, encoder, sizes.invocations * 3); self.draw_call_buffer.swap(queue, device, encoder, sizes.draw_calls); - self.culling_results_buffer - .swap(queue, device, encoder, sizes.invocations.div_round_up(32)); + self.culling_results_buffer.swap(queue, device, encoder, sizes.invocations.div_round_up(32)); } } @@ -444,12 +443,7 @@ impl GpuCuller { let encoder = ctx.encoder_or_pass.take_encoder(); // TODO: Isolate all this into a struct - let max_object_count = ctx - .data_core - .object_manager - .buffer::() - .map(wgpu::Buffer::size) - .unwrap_or(0) + let max_object_count = ctx.data_core.object_manager.buffer::().map(wgpu::Buffer::size).unwrap_or(0) / ShaderObject::::SHADER_SIZE.get(); if max_object_count == 0 { @@ -506,11 +500,7 @@ impl GpuCuller { object_count: max_object_count as u32, objects: Vec::new(), }; - let mut buffer = ctx - .renderer - .queue - .write_buffer_with(buffer, 0, per_camera_data.size()) - .unwrap(); + let mut buffer = ctx.renderer.queue.write_buffer_with(buffer, 0, per_camera_data.size()).unwrap(); StorageBuffer::new(&mut *buffer).write(&per_camera_data).unwrap(); } @@ -521,14 +511,8 @@ impl GpuCuller { label: Some(&format_sso!("UniformPrep {type_name} BG")), layout: &self.prep_bgl, entries: &[ - BindGroupEntry { - binding: 0, - resource: object_manager_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 1, - resource: buffer.as_entire_binding(), - }, + BindGroupEntry { binding: 0, resource: object_manager_buffer.as_entire_binding() }, + BindGroupEntry { binding: 1, resource: buffer.as_entire_binding() }, ], }); @@ -577,10 +561,7 @@ impl GpuCuller { &ctx.renderer.device, encoder, camera_specifier, - CullingBufferSizes { - invocations: total_invocations as u64, - draw_calls: jobs.regions.len() as u64, - }, + CullingBufferSizes { invocations: total_invocations as u64, draw_calls: jobs.regions.len() as u64 }, ); let per_camera_uniform = Arc::clone( @@ -615,10 +596,7 @@ impl GpuCuller { label: Some(&format_sso!("GpuCuller {type_name} BG")), layout: &self.culling_bgl, entries: &[ - BindGroupEntry { - binding: 0, - resource: ctx.eval_output.mesh_buffer.as_entire_binding(), - }, + BindGroupEntry { binding: 0, resource: ctx.eval_output.mesh_buffer.as_entire_binding() }, BindGroupEntry { binding: 1, resource: ctx.data_core.object_manager.buffer::().unwrap().as_entire_binding(), @@ -631,30 +609,12 @@ impl GpuCuller { size: Some(ShaderBatchData::SHADER_SIZE), }), }, - BindGroupEntry { - binding: 3, - resource: buffers.draw_call_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 4, - resource: buffers.index_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 5, - resource: buffers.culling_results_buffer.as_entire_binding(), - }, - BindGroupEntry { - binding: 6, - resource: per_camera_uniform.as_entire_binding(), - }, - BindGroupEntry { - binding: 7, - resource: BindingResource::TextureView(hi_z_buffer), - }, - BindGroupEntry { - binding: 8, - resource: BindingResource::Sampler(&self.sampler), - }, + BindGroupEntry { binding: 3, resource: buffers.draw_call_buffer.as_entire_binding() }, + BindGroupEntry { binding: 4, resource: buffers.index_buffer.as_entire_binding() }, + BindGroupEntry { binding: 5, resource: buffers.culling_results_buffer.as_entire_binding() }, + BindGroupEntry { binding: 6, resource: per_camera_uniform.as_entire_binding() }, + BindGroupEntry { binding: 7, resource: BindingResource::TextureView(hi_z_buffer) }, + BindGroupEntry { binding: 8, resource: BindingResource::Sampler(&self.sampler) }, ], }); @@ -674,10 +634,7 @@ impl GpuCuller { current_material_key_range_start = range_end; } - draw_calls.push(DrawCall { - bind_group_index: region.key.bind_group_index, - batch_index: region.job_index, - }); + draw_calls.push(DrawCall { bind_group_index: region.key.bind_group_index, batch_index: region.job_index }); } material_key_ranges.insert(current_material_key, current_material_key_range_start..draw_calls.len()); @@ -693,21 +650,12 @@ impl GpuCuller { // RA can't infer this let job: &ShaderBatchData = job; - cpass.set_bind_group( - 0, - &culling_bg, - &[idx as u32 * ShaderBatchData::SHADER_SIZE.get() as u32], - ); + cpass.set_bind_group(0, &culling_bg, &[idx as u32 * ShaderBatchData::SHADER_SIZE.get() as u32]); cpass.dispatch_workgroups(job.total_invocations.div_round_up(WORKGROUP_SIZE), 1, 1); } drop(cpass); - DrawCallSet { - culling_data_buffer, - per_camera_uniform, - draw_calls, - material_key_ranges, - } + DrawCallSet { culling_data_buffer, per_camera_uniform, draw_calls, material_key_ranges } } pub fn add_object_uniform_upload_to_graph<'node, M: Material>( @@ -743,11 +691,7 @@ impl GpuCuller { let output = node.add_data(draw_calls_hdl, NodeResourceUsage::Output); let depth_handle = node.add_render_target( depth_handle, - if camera_specifier.is_shadow() { - NodeResourceUsage::Reference - } else { - NodeResourceUsage::Input - }, + if camera_specifier.is_shadow() { NodeResourceUsage::Reference } else { NodeResourceUsage::Input }, ); node.build(move |mut ctx| { diff --git a/rend3-routine/src/culling/suballoc.rs b/rend3-routine/src/culling/suballoc.rs index 467b2c2d..6079dcda 100644 --- a/rend3-routine/src/culling/suballoc.rs +++ b/rend3-routine/src/culling/suballoc.rs @@ -137,11 +137,7 @@ impl InputOutputBuffer { pub fn write_to_output(&self, queue: &wgpu::Queue, data: &T) { assert_eq!(data.size().get(), self.output_partition_elements * self.element_size); let mut mapping = queue - .write_buffer_with( - &self.buffer, - self.element_offset(InputOutputPartition::Output, 0), - data.size(), - ) + .write_buffer_with(&self.buffer, self.element_offset(InputOutputPartition::Output, 0), data.size()) .unwrap(); StorageBuffer::new(&mut *mapping).write(data).unwrap(); drop(mapping); diff --git a/rend3-routine/src/forward.rs b/rend3-routine/src/forward.rs index a54b2cd7..e45c9003 100644 --- a/rend3-routine/src/forward.rs +++ b/rend3-routine/src/forward.rs @@ -248,11 +248,7 @@ impl ForwardRoutine { // When we're rendering the residual data, we are post buffer flip. We want to be rendering using the // "input" partition, as this is the partition that all same-frame data is in. - let partition = if residual { - InputOutputPartition::Input - } else { - InputOutputPartition::Output - }; + let partition = if residual { InputOutputPartition::Input } else { InputOutputPartition::Output }; let per_material_bg = ctx.temps.add( BindGroupBuilder::new() @@ -264,11 +260,7 @@ impl ForwardRoutine { .append_buffer(&ctx.eval_output.mesh_buffer) .append_buffer(&draw_call_set.per_camera_uniform) .append_buffer(ctx.data_core.material_manager.archetype_view::().buffer()) - .build( - &ctx.renderer.device, - Some("Per-Material BG"), - &args.binding_data.per_material_bgl.bgl, - ), + .build(&ctx.renderer.device, Some("Per-Material BG"), &args.binding_data.per_material_bgl.bgl), ); let pipeline = match args.samples { @@ -339,11 +331,7 @@ fn build_forward_pipeline_inner( let mut desc = RenderPipelineDescriptor { label: Some(args.name), layout: Some(pll), - vertex: VertexState { - module: args.shaders.vs_module, - entry_point: args.shaders.vs_entry, - buffers: &[], - }, + vertex: VertexState { module: args.shaders.vs_module, entry_point: args.shaders.vs_entry, buffers: &[] }, primitive: PrimitiveState { topology: PrimitiveTopology::TriangleList, strip_index_format: None, @@ -363,18 +351,11 @@ fn build_forward_pipeline_inner( stencil: StencilState::default(), bias: match args.routine_type { // TODO: figure out what to put here - RoutineType::Depth => DepthBiasState { - constant: 0, - slope_scale: 0.0, - clamp: 0.0, - }, + RoutineType::Depth => DepthBiasState { constant: 0, slope_scale: 0.0, clamp: 0.0 }, RoutineType::Forward => DepthBiasState::default(), }, }), - multisample: MultisampleState { - count: samples as u32, - ..Default::default() - }, + multisample: MultisampleState { count: samples as u32, ..Default::default() }, fragment: Some(FragmentState { module: args.shaders.fs_module, entry_point: args.shaders.fs_entry, diff --git a/rend3-routine/src/hi_z.rs b/rend3-routine/src/hi_z.rs index 2fd75bc8..e75c5f8f 100644 --- a/rend3-routine/src/hi_z.rs +++ b/rend3-routine/src/hi_z.rs @@ -28,11 +28,7 @@ pub struct HiZRoutine { impl HiZRoutine { pub fn new(renderer: &Renderer, spp: &ShaderPreProcessor) -> Self { let resolve_source = spp - .render_shader( - "rend3-routine/resolve_depth_min.wgsl", - &serde_json::json!({"SAMPLES": 4}), - None, - ) + .render_shader("rend3-routine/resolve_depth_min.wgsl", &serde_json::json!({"SAMPLES": 4}), None) .unwrap(); let downscale_source = spp.render_shader("rend3-routine/hi_z.wgsl", &(), None).unwrap(); @@ -88,11 +84,7 @@ impl HiZRoutine { let resolve_pipeline = renderer.device.create_render_pipeline(&RenderPipelineDescriptor { label: Some("HiZ Resolve Pipeline"), layout: Some(&resolve_pipline_layout), - vertex: VertexState { - module: &resolve_sm, - entry_point: "vs_main", - buffers: &[], - }, + vertex: VertexState { module: &resolve_sm, entry_point: "vs_main", buffers: &[] }, primitive: PrimitiveState::default(), depth_stencil: Some(DepthStencilState { format: TextureFormat::Depth32Float, @@ -102,22 +94,14 @@ impl HiZRoutine { bias: DepthBiasState::default(), }), multisample: MultisampleState::default(), - fragment: Some(FragmentState { - module: &resolve_sm, - entry_point: "fs_main", - targets: &[], - }), + fragment: Some(FragmentState { module: &resolve_sm, entry_point: "fs_main", targets: &[] }), multiview: None, }); let downscale_pipeline = renderer.device.create_render_pipeline(&RenderPipelineDescriptor { label: Some("HiZ Downscale Pipeline"), layout: Some(&downscale_pipline_layout), - vertex: VertexState { - module: &downscale_sm, - entry_point: "vs_main", - buffers: &[], - }, + vertex: VertexState { module: &downscale_sm, entry_point: "vs_main", buffers: &[] }, primitive: PrimitiveState::default(), depth_stencil: Some(DepthStencilState { format: TextureFormat::Depth32Float, @@ -127,20 +111,11 @@ impl HiZRoutine { bias: DepthBiasState::default(), }), multisample: MultisampleState::default(), - fragment: Some(FragmentState { - module: &downscale_sm, - entry_point: "fs_main", - targets: &[], - }), + fragment: Some(FragmentState { module: &downscale_sm, entry_point: "fs_main", targets: &[] }), multiview: None, }); - Self { - single_sampled_bgl, - downscale_pipeline, - multisampled_bgl, - resolve_pipeline, - } + Self { single_sampled_bgl, downscale_pipeline, multisampled_bgl, resolve_pipeline } } pub fn resolve<'pass>( @@ -152,16 +127,11 @@ impl HiZRoutine { let rpass = ctx.encoder_or_pass.take_rpass(renderpass_handle); let source = ctx.graph_data.get_render_target(source_handle); - let bind_group = ctx - .temps - .add(ctx.renderer.device.create_bind_group(&BindGroupDescriptor { - label: Some("HiZ Resolve BG"), - layout: &self.multisampled_bgl, - entries: &[BindGroupEntry { - binding: 0, - resource: BindingResource::TextureView(source), - }], - })); + let bind_group = ctx.temps.add(ctx.renderer.device.create_bind_group(&BindGroupDescriptor { + label: Some("HiZ Resolve BG"), + layout: &self.multisampled_bgl, + entries: &[BindGroupEntry { binding: 0, resource: BindingResource::TextureView(source) }], + })); rpass.set_pipeline(&self.resolve_pipeline); rpass.set_bind_group(0, bind_group, &[]); @@ -177,16 +147,11 @@ impl HiZRoutine { let rpass = ctx.encoder_or_pass.take_rpass(renderpass_handle); let source = ctx.graph_data.get_render_target(source_handle); - let bind_group = ctx - .temps - .add(ctx.renderer.device.create_bind_group(&BindGroupDescriptor { - label: Some("HiZ Bind Group Layout"), - layout: &self.single_sampled_bgl, - entries: &[BindGroupEntry { - binding: 0, - resource: BindingResource::TextureView(source), - }], - })); + let bind_group = ctx.temps.add(ctx.renderer.device.create_bind_group(&BindGroupDescriptor { + label: Some("HiZ Bind Group Layout"), + layout: &self.single_sampled_bgl, + entries: &[BindGroupEntry { binding: 0, resource: BindingResource::TextureView(source) }], + })); rpass.set_pipeline(&self.downscale_pipeline); rpass.set_bind_group(0, bind_group, &[]); @@ -199,11 +164,7 @@ impl HiZRoutine { depth_targets: DepthTargets, resolution: UVec2, ) { - let extent = Extent3d { - width: resolution.x, - height: resolution.y, - depth_or_array_layers: 1, - }; + let extent = Extent3d { width: resolution.x, height: resolution.y, depth_or_array_layers: 1 }; let mips = extent.max_mips(TextureDimension::D2) as u8; // First we need to downscale the depth buffer to a single sample texture diff --git a/rend3-routine/src/pbr/material.rs b/rend3-routine/src/pbr/material.rs index efba8a1f..62f6dc33 100644 --- a/rend3-routine/src/pbr/material.rs +++ b/rend3-routine/src/pbr/material.rs @@ -265,21 +265,10 @@ pub enum AoMRTextures { impl AoMRTextures { pub fn to_roughness_texture(&self) -> Option<&Texture2DHandle> { match *self { - Self::Combined { - texture: Some(ref texture), - } => Some(texture), - Self::SwizzledSplit { - mr_texture: Some(ref texture), - .. - } => Some(texture), - Self::Split { - mr_texture: Some(ref texture), - .. - } => Some(texture), - Self::BWSplit { - r_texture: Some(ref texture), - .. - } => Some(texture), + Self::Combined { texture: Some(ref texture) } => Some(texture), + Self::SwizzledSplit { mr_texture: Some(ref texture), .. } => Some(texture), + Self::Split { mr_texture: Some(ref texture), .. } => Some(texture), + Self::BWSplit { r_texture: Some(ref texture), .. } => Some(texture), _ => None, } } @@ -289,10 +278,7 @@ impl AoMRTextures { Self::Combined { .. } => None, Self::SwizzledSplit { .. } => None, Self::Split { .. } => None, - Self::BWSplit { - m_texture: Some(ref texture), - .. - } => Some(texture), + Self::BWSplit { m_texture: Some(ref texture), .. } => Some(texture), _ => None, } } @@ -300,18 +286,9 @@ impl AoMRTextures { pub fn to_ao_texture(&self) -> Option<&Texture2DHandle> { match *self { Self::Combined { .. } => None, - Self::SwizzledSplit { - ao_texture: Some(ref texture), - .. - } => Some(texture), - Self::Split { - ao_texture: Some(ref texture), - .. - } => Some(texture), - Self::BWSplit { - ao_texture: Some(ref texture), - .. - } => Some(texture), + Self::SwizzledSplit { ao_texture: Some(ref texture), .. } => Some(texture), + Self::Split { ao_texture: Some(ref texture), .. } => Some(texture), + Self::BWSplit { ao_texture: Some(ref texture), .. } => Some(texture), _ => None, } } @@ -358,17 +335,9 @@ pub enum ClearcoatTextures { impl ClearcoatTextures { pub fn to_clearcoat_texture(&self) -> Option<&Texture2DHandle> { match *self { - Self::GltfCombined { - texture: Some(ref texture), - } => Some(texture), - Self::GltfSplit { - clearcoat_texture: Some(ref texture), - .. - } => Some(texture), - Self::BWSplit { - clearcoat_texture: Some(ref texture), - .. - } => Some(texture), + Self::GltfCombined { texture: Some(ref texture) } => Some(texture), + Self::GltfSplit { clearcoat_texture: Some(ref texture), .. } => Some(texture), + Self::BWSplit { clearcoat_texture: Some(ref texture), .. } => Some(texture), _ => None, } } @@ -376,14 +345,8 @@ impl ClearcoatTextures { pub fn to_clearcoat_roughness_texture(&self) -> Option<&Texture2DHandle> { match *self { Self::GltfCombined { .. } => None, - Self::GltfSplit { - clearcoat_roughness_texture: Some(ref texture), - .. - } => Some(texture), - Self::BWSplit { - clearcoat_roughness_texture: Some(ref texture), - .. - } => Some(texture), + Self::GltfSplit { clearcoat_roughness_texture: Some(ref texture), .. } => Some(texture), + Self::BWSplit { clearcoat_roughness_texture: Some(ref texture), .. } => Some(texture), _ => None, } } diff --git a/rend3-routine/src/pbr/routine.rs b/rend3-routine/src/pbr/routine.rs index 31ec5328..54b52f97 100644 --- a/rend3-routine/src/pbr/routine.rs +++ b/rend3-routine/src/pbr/routine.rs @@ -42,9 +42,7 @@ impl PbrRoutine { profiling::scope!("PbrRenderRoutine::new"); // This ensures the BGLs for the material are created - data_core - .material_manager - .ensure_archetype::(&renderer.device, renderer.profile); + data_core.material_manager.ensure_archetype::(&renderer.device, renderer.profile); let per_material = PerMaterialArchetypeInterface::::new(&renderer.device); @@ -53,10 +51,7 @@ impl PbrRoutine { source: ShaderSource::Wgsl(Cow::Owned( spp.render_shader( "rend3-routine/depth.wgsl", - &BlendModeWrapper { - profile: renderer.profile, - discard: true, - }, + &BlendModeWrapper { profile: renderer.profile, discard: true }, Some(&ShaderVertexBufferConfig::from_material::()), ) .unwrap(), @@ -68,10 +63,7 @@ impl PbrRoutine { source: ShaderSource::Wgsl(Cow::Owned( spp.render_shader( "rend3-routine/depth.wgsl", - &BlendModeWrapper { - profile: renderer.profile, - discard: false, - }, + &BlendModeWrapper { profile: renderer.profile, discard: false }, Some(&ShaderVertexBufferConfig::from_material::()), ) .unwrap(), @@ -83,10 +75,7 @@ impl PbrRoutine { source: ShaderSource::Wgsl(Cow::Owned( spp.render_shader( "rend3-routine/opaque.wgsl", - &BlendModeWrapper { - profile: renderer.profile, - discard: true, - }, + &BlendModeWrapper { profile: renderer.profile, discard: true }, Some(&ShaderVertexBufferConfig::from_material::()), ) .unwrap(), @@ -98,10 +87,7 @@ impl PbrRoutine { source: ShaderSource::Wgsl(Cow::Owned( spp.render_shader( "rend3-routine/opaque.wgsl", - &BlendModeWrapper { - profile: renderer.profile, - discard: false, - }, + &BlendModeWrapper { profile: renderer.profile, discard: false }, Some(&ShaderVertexBufferConfig::from_material::()), ) .unwrap(), diff --git a/rend3-routine/src/shaders.rs b/rend3-routine/src/shaders.rs index 89f1ac85..a10c8b80 100644 --- a/rend3-routine/src/shaders.rs +++ b/rend3-routine/src/shaders.rs @@ -98,11 +98,8 @@ mod tests { for config in configs { println!("Testing shader {shader} with config {config:?}"); - let output = pp.render_shader( - shader, - &config, - Some(&ShaderVertexBufferConfig::from_material::()), - ); + let output = + pp.render_shader(shader, &config, Some(&ShaderVertexBufferConfig::from_material::())); assert!(output.is_ok(), "Expected preprocessing success, got {output:?}"); let output = output.unwrap_or_else(|e| panic!("Expected preprocessing success, got {e:?}")); diff --git a/rend3-routine/src/skinning.rs b/rend3-routine/src/skinning.rs index e15d2513..a766244b 100644 --- a/rend3-routine/src/skinning.rs +++ b/rend3-routine/src/skinning.rs @@ -124,9 +124,7 @@ fn build_gpu_skinning_input_buffers(ctx: &NodeExecutionContext) -> PreSkinningBu // will get incremented once for every joint matrix, and the // length of the buffer is exactly the sum of all joint matrix // vector lengths. - joint_matrices_ptr - .add(joint_matrix_idx as usize) - .write_unaligned(joint_matrix.to_cols_array_2d()); + joint_matrices_ptr.add(joint_matrix_idx as usize).write_unaligned(joint_matrix.to_cols_array_2d()); joint_matrix_idx += 1; } } @@ -137,10 +135,7 @@ fn build_gpu_skinning_input_buffers(ctx: &NodeExecutionContext) -> PreSkinningBu gpu_skinning_inputs.unmap(); joint_matrices.unmap(); - PreSkinningBuffers { - gpu_skinning_inputs, - joint_matrices, - } + PreSkinningBuffers { gpu_skinning_inputs, joint_matrices } } /// Holds the necessary wgpu data structures for the GPU skinning compute pass @@ -190,10 +185,8 @@ impl GpuSkinner { .append_buffer(&buffers.joint_matrices) .build(&ctx.renderer.device, Some("GPU skinning inputs"), &self.bgl); - let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor { - label: Some("GPU Skinning"), - timestamp_writes: None, - }); + let mut cpass = + encoder.begin_compute_pass(&ComputePassDescriptor { label: Some("GPU Skinning"), timestamp_writes: None }); cpass.set_pipeline(&self.pipeline); for (i, skel) in ctx.data_core.skeleton_manager.skeletons().enumerate() { let offset = (i as u64 * GpuSkinningInput::SHADER_SIZE.get()) as u32; diff --git a/rend3-routine/src/skybox.rs b/rend3-routine/src/skybox.rs index e8ae5d8a..d2fd9dcf 100644 --- a/rend3-routine/src/skybox.rs +++ b/rend3-routine/src/skybox.rs @@ -48,11 +48,7 @@ impl SkyboxRoutine { let pipelines = SkyboxPipelines::new(renderer, spp, interfaces, &bgl); - Self { - current_skybox: StoredSkybox { bg: None, handle: None }, - bgl, - pipelines, - } + Self { current_skybox: StoredSkybox { bg: None, handle: None }, bgl, pipelines } } /// Set the current background texture. Bad things will happen if this isn't @@ -130,8 +126,7 @@ impl SkyboxPipelines { let skybox_sm = renderer.device.create_shader_module(ShaderModuleDescriptor { label: Some("skybox vert"), source: ShaderSource::Wgsl(Cow::Owned( - spp.render_shader("rend3-routine/skybox.wgsl", &ShaderConfig::default(), None) - .unwrap(), + spp.render_shader("rend3-routine/skybox.wgsl", &ShaderConfig::default(), None).unwrap(), )), }); @@ -145,11 +140,7 @@ impl SkyboxPipelines { renderer.device.create_render_pipeline(&RenderPipelineDescriptor { label: Some("skybox pass"), layout: Some(&pll), - vertex: VertexState { - module: &skybox_sm, - entry_point: "vs_main", - buffers: &[], - }, + vertex: VertexState { module: &skybox_sm, entry_point: "vs_main", buffers: &[] }, primitive: PrimitiveState { topology: PrimitiveTopology::TriangleList, strip_index_format: None, @@ -166,10 +157,7 @@ impl SkyboxPipelines { stencil: StencilState::default(), bias: DepthBiasState::default(), }), - multisample: MultisampleState { - count: samples as u32, - ..Default::default() - }, + multisample: MultisampleState { count: samples as u32, ..Default::default() }, fragment: Some(FragmentState { module: &skybox_sm, entry_point: "fs_main", @@ -183,9 +171,6 @@ impl SkyboxPipelines { }) }; - Self { - pipeline_s1: inner(SampleCount::One), - pipeline_s4: inner(SampleCount::Four), - } + Self { pipeline_s1: inner(SampleCount::One), pipeline_s4: inner(SampleCount::Four) } } } diff --git a/rend3-routine/src/tonemapping.rs b/rend3-routine/src/tonemapping.rs index ee4c1d41..4ac9c11d 100644 --- a/rend3-routine/src/tonemapping.rs +++ b/rend3-routine/src/tonemapping.rs @@ -37,16 +37,11 @@ fn create_pipeline( let module = device.create_shader_module(ShaderModuleDescriptor { label: Some("tonemapping"), source: ShaderSource::Wgsl(Cow::Owned( - spp.render_shader("rend3-routine/blit.wgsl", &ShaderConfig::default(), None) - .unwrap(), + spp.render_shader("rend3-routine/blit.wgsl", &ShaderConfig::default(), None).unwrap(), )), }); - let fs_entry_point = if output_format.is_srgb() { - "fs_main_scene" - } else { - "fs_main_monitor" - }; + let fs_entry_point = if output_format.is_srgb() { "fs_main_scene" } else { "fs_main_monitor" }; let pll = device.create_pipeline_layout(&PipelineLayoutDescriptor { label: Some("tonemapping pass"), @@ -57,11 +52,7 @@ fn create_pipeline( device.create_render_pipeline(&RenderPipelineDescriptor { label: Some("tonemapping pass"), layout: Some(&pll), - vertex: VertexState { - module: &module, - entry_point: "vs_main", - buffers: &[], - }, + vertex: VertexState { module: &module, entry_point: "vs_main", buffers: &[] }, primitive: PrimitiveState { topology: PrimitiveTopology::TriangleList, strip_index_format: None, @@ -76,11 +67,7 @@ fn create_pipeline( fragment: Some(FragmentState { module: &module, entry_point: fs_entry_point, - targets: &[Some(ColorTargetState { - format: output_format, - blend: None, - write_mask: ColorWrites::all(), - })], + targets: &[Some(ColorTargetState { format: output_format, blend: None, write_mask: ColorWrites::all() })], }), multiview: None, }) @@ -131,11 +118,7 @@ impl TonemappingRoutine { let rpass_handle = builder.add_renderpass( RenderPassTargets { - targets: vec![RenderPassTarget { - color: dst, - clear: Vec4::ZERO, - resolve: None, - }], + targets: vec![RenderPassTarget { color: dst, clear: Vec4::ZERO, resolve: None }], depth_stencil: None, }, NodeResourceUsage::InputOutput, @@ -150,13 +133,11 @@ impl TonemappingRoutine { profiling::scope!("tonemapping"); - let blit_src_bg = ctx - .temps - .add(BindGroupBuilder::new().append_texture_view(hdr_color).build( - &ctx.renderer.device, - Some("blit src bg"), - &self.bgl, - )); + let blit_src_bg = ctx.temps.add(BindGroupBuilder::new().append_texture_view(hdr_color).build( + &ctx.renderer.device, + Some("blit src bg"), + &self.bgl, + )); rpass.set_pipeline(&self.pipeline); rpass.set_bind_group(0, forward_uniform_bg, &[]); diff --git a/rend3-routine/src/uniforms.rs b/rend3-routine/src/uniforms.rs index 9249c247..b21f9d95 100644 --- a/rend3-routine/src/uniforms.rs +++ b/rend3-routine/src/uniforms.rs @@ -108,11 +108,8 @@ pub fn add_to_graph<'node>( ctx.data_core.directional_light_manager.add_to_bg(&mut bgb); ctx.data_core.point_light_manager.add_to_bg(&mut bgb); - let shadow_uniform_bg = bgb.build( - &ctx.renderer.device, - Some("shadow uniform bg"), - &binding_handles.interfaces.depth_uniform_bgl, - ); + let shadow_uniform_bg = + bgb.build(&ctx.renderer.device, Some("shadow uniform bg"), &binding_handles.interfaces.depth_uniform_bgl); bgb.append_texture_view(shadow_target); diff --git a/rend3-test/Cargo.toml b/rend3-test/Cargo.toml index 0a0cb232..031e0fd3 100644 --- a/rend3-test/Cargo.toml +++ b/rend3-test/Cargo.toml @@ -15,9 +15,9 @@ name = "rend3-tests" [dependencies] anyhow = "1" -env_logger = "0.10" +env_logger = "0.11" flume = { version = "0.11", features = ["spin"] } -glam = "0.24" +glam = "0.25" image = { version = "0.24", default-features = false, features = ["png"] } rend3 = { path = "../rend3" } rend3-routine = { path = "../rend3-routine" } diff --git a/rend3-test/src/runner.rs b/rend3-test/src/runner.rs index 5074effb..ad915976 100644 --- a/rend3-test/src/runner.rs +++ b/rend3-test/src/runner.rs @@ -24,10 +24,7 @@ pub struct FrameRenderSettings { impl FrameRenderSettings { pub fn new() -> Self { - Self { - size: 64, - samples: SampleCount::One, - } + Self { size: 64, samples: SampleCount::One } } pub fn size(mut self, size: u32) -> Result { @@ -74,9 +71,7 @@ impl TestRunnerBuilder { let iad = match self.iad { Some(iad) => iad, - None => rend3::create_iad(None, None, None, None) - .await - .context("InstanceAdapterDevice creation failed")?, + None => rend3::create_iad(None, None, None, None).await.context("InstanceAdapterDevice creation failed")?, }; let capture_guard = CaptureDropGuard::start_capture(Arc::clone(&iad.device)); @@ -95,20 +90,10 @@ impl TestRunnerBuilder { &base_rendergraph.interfaces, &base_rendergraph.gpu_culler.culling_buffer_map_handle, ); - let tonemapping = TonemappingRoutine::new( - &renderer, - &spp, - &base_rendergraph.interfaces, - TextureFormat::Rgba8UnormSrgb, - ); + let tonemapping = + TonemappingRoutine::new(&renderer, &spp, &base_rendergraph.interfaces, TextureFormat::Rgba8UnormSrgb); - Ok(TestRunner { - renderer, - pbr, - tonemapping, - base_rendergraph, - capture_guard, - }) + Ok(TestRunner { renderer, pbr, tonemapping, base_rendergraph, capture_guard }) } } @@ -136,11 +121,7 @@ impl TestRunner { pub fn process_events(&self, settings: FrameRenderSettings) -> wgpu::Texture { let texture = self.renderer.device.create_texture(&TextureDescriptor { label: Some("Test output image"), - size: Extent3d { - width: settings.size, - height: settings.size, - depth_or_array_layers: 1, - }, + size: Extent3d { width: settings.size, height: settings.size, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, @@ -219,40 +200,24 @@ pub async fn download_image( mapped_at_creation: false, }); - let mut encoder = renderer.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Test output encoder"), - }); + let mut encoder = + renderer.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Test output encoder") }); encoder.copy_texture_to_buffer( texture.as_image_copy(), ImageCopyBuffer { buffer: &buffer, - layout: ImageDataLayout { - offset: 0, - bytes_per_row: Some(size.x * 4), - rows_per_image: None, - }, - }, - Extent3d { - width: size.x, - height: size.y, - depth_or_array_layers: 1, + layout: ImageDataLayout { offset: 0, bytes_per_row: Some(size.x * 4), rows_per_image: None }, }, + Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 }, ); let submit_index = renderer.queue.submit(Some(encoder.finish())); let (sender, receiver) = flume::bounded(1); - buffer - .slice(..) - .map_async(wgpu::MapMode::Read, move |_| sender.send(()).unwrap()); - renderer - .device - .poll(wgpu::Maintain::WaitForSubmissionIndex(submit_index)); - - receiver - .recv_async() - .await - .context("Failed to recieve message from map_async")?; + buffer.slice(..).map_async(wgpu::MapMode::Read, move |_| sender.send(()).unwrap()); + renderer.device.poll(wgpu::Maintain::WaitForSubmissionIndex(submit_index)); + + receiver.recv_async().await.context("Failed to recieve message from map_async")?; let mapping = buffer.slice(..).get_mapped_range(); diff --git a/rend3-test/src/threshold.rs b/rend3-test/src/threshold.rs index e987faaf..3c4d7b6f 100644 --- a/rend3-test/src/threshold.rs +++ b/rend3-test/src/threshold.rs @@ -37,10 +37,7 @@ impl Threshold { ); within } - Self::Percentile { - percentile: p, - threshold: v, - } => { + Self::Percentile { percentile: p, threshold: v } => { let percentile = pool.get_percentile(p, true); let within = percentile <= v; println!( @@ -58,16 +55,12 @@ impl Threshold { impl From for ThresholdSet { fn from(threshold: Threshold) -> Self { - Self { - thresholds: vec![threshold], - } + Self { thresholds: vec![threshold] } } } impl From<&[Threshold]> for ThresholdSet { fn from(thresholds: &[Threshold]) -> Self { - Self { - thresholds: thresholds.into(), - } + Self { thresholds: thresholds.into() } } } diff --git a/rend3-test/tests/msaa.rs b/rend3-test/tests/msaa.rs index c984601c..a512247b 100644 --- a/rend3-test/tests/msaa.rs +++ b/rend3-test/tests/msaa.rs @@ -8,22 +8,13 @@ pub async fn triangle() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; // Clockwise triangle let mesh = MeshBuilder::new( - vec![ - Vec3::new(0.5, -0.5, 0.0), - Vec3::new(-0.5, -0.5, 0.0), - Vec3::new(0.0, 0.5, 0.0), - ], + vec![Vec3::new(0.5, -0.5, 0.0), Vec3::new(-0.5, -0.5, 0.0), Vec3::new(0.0, 0.5, 0.0)], Handedness::Left, ) .build() @@ -31,11 +22,8 @@ pub async fn triangle() -> anyhow::Result<()> { let mesh_hdl = runner.add_mesh(mesh).unwrap(); let material_hdl = runner.add_unlit_material(Vec4::new(0.25, 0.5, 0.75, 1.0)); - let object = Object { - mesh_kind: ObjectMeshKind::Static(mesh_hdl), - material: material_hdl, - transform: Mat4::IDENTITY, - }; + let object = + Object { mesh_kind: ObjectMeshKind::Static(mesh_hdl), material: material_hdl, transform: Mat4::IDENTITY }; let _object_hdl = runner.add_object(object); runner.set_camera_data(Camera { @@ -59,12 +47,7 @@ pub async fn sample_coverage() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; diff --git a/rend3-test/tests/object.rs b/rend3-test/tests/object.rs index cea3b1de..124e63d5 100644 --- a/rend3-test/tests/object.rs +++ b/rend3-test/tests/object.rs @@ -12,12 +12,7 @@ pub async fn deuplicate_object_retain() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; @@ -74,12 +69,7 @@ pub async fn multi_frame_add() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; @@ -101,10 +91,10 @@ pub async fn multi_frame_add() -> anyhow::Result<()> { let mut planes = Vec::with_capacity(2); for x in 0..2 { for y in 0..count { - planes.push(runner.plane( - material.clone(), - Mat4::from_translation(Vec3::new(x as f32, y as f32, 0.0)) * base_matrix, - )); + planes.push( + runner + .plane(material.clone(), Mat4::from_translation(Vec3::new(x as f32, y as f32, 0.0)) * base_matrix), + ); } runner .render_and_compare( diff --git a/rend3-test/tests/shadow.rs b/rend3-test/tests/shadow.rs index 36ab0943..486ea7ae 100644 --- a/rend3-test/tests/shadow.rs +++ b/rend3-test/tests/shadow.rs @@ -10,12 +10,7 @@ pub async fn shadows() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; @@ -26,9 +21,7 @@ pub async fn shadows() -> anyhow::Result<()> { let _plane = runner.plane(material1, Mat4::from_rotation_x(-FRAC_PI_2)); runner.set_camera_data(Camera { - projection: rend3::types::CameraProjection::Orthographic { - size: Vec3A::new(2.5, 2.5, 5.0), - }, + projection: rend3::types::CameraProjection::Orthographic { size: Vec3A::new(2.5, 2.5, 5.0) }, view: Mat4::look_at_lh(Vec3::new(0.0, 1.0, -1.0), Vec3::ZERO, Vec3::Y), }); @@ -37,10 +30,7 @@ pub async fn shadows() -> anyhow::Result<()> { .render_and_compare( FrameRenderSettings::new().size(256)?, file_name, - Threshold::Percentile { - percentile: 0.5, - threshold: 0.04, - }, + Threshold::Percentile { percentile: 0.5, threshold: 0.04 }, ) .await?; @@ -56,10 +46,7 @@ pub async fn shadows() -> anyhow::Result<()> { .render_and_compare( FrameRenderSettings::new().size(256)?, file_name, - Threshold::Percentile { - percentile: 0.5, - threshold: 0.04, - }, + Threshold::Percentile { percentile: 0.5, threshold: 0.04 }, ) .await?; diff --git a/rend3-test/tests/simple.rs b/rend3-test/tests/simple.rs index c2cd561d..ea3397de 100644 --- a/rend3-test/tests/simple.rs +++ b/rend3-test/tests/simple.rs @@ -19,11 +19,7 @@ pub async fn empty() -> anyhow::Result<()> { }); runner - .render_and_compare( - FrameRenderSettings::new(), - "tests/results/simple/empty.png", - Threshold::Mean(0.0), - ) + .render_and_compare(FrameRenderSettings::new(), "tests/results/simple/empty.png", Threshold::Mean(0.0)) .await .context("Image Comparison Failed")?; @@ -43,28 +39,15 @@ pub async fn triangle() -> anyhow::Result<()> { .context("InstanceAdapterDevice creation failed")?; for (handedness, winding, visible) in tests { - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(handedness) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(handedness).build().await else { return Ok(()); }; // Clockwise triangle let mesh = MeshBuilder::new( match winding { - FrontFace::Ccw => vec![ - Vec3::new(0.5, -0.5, 0.0), - Vec3::new(0.0, 0.5, 0.0), - Vec3::new(-0.5, -0.5, 0.0), - ], - FrontFace::Cw => vec![ - Vec3::new(0.5, -0.5, 0.0), - Vec3::new(-0.5, -0.5, 0.0), - Vec3::new(0.0, 0.5, 0.0), - ], + FrontFace::Ccw => vec![Vec3::new(0.5, -0.5, 0.0), Vec3::new(0.0, 0.5, 0.0), Vec3::new(-0.5, -0.5, 0.0)], + FrontFace::Cw => vec![Vec3::new(0.5, -0.5, 0.0), Vec3::new(-0.5, -0.5, 0.0), Vec3::new(0.0, 0.5, 0.0)], }, match winding { FrontFace::Cw => Handedness::Left, @@ -76,11 +59,8 @@ pub async fn triangle() -> anyhow::Result<()> { let mesh_hdl = runner.add_mesh(mesh).unwrap(); let material_hdl = runner.add_unlit_material(Vec4::new(0.25, 0.5, 0.75, 1.0)); - let object = Object { - mesh_kind: ObjectMeshKind::Static(mesh_hdl), - material: material_hdl, - transform: Mat4::IDENTITY, - }; + let object = + Object { mesh_kind: ObjectMeshKind::Static(mesh_hdl), material: material_hdl, transform: Mat4::IDENTITY }; let _object_hdl = runner.add_object(object); runner.set_camera_data(Camera { @@ -92,14 +72,13 @@ pub async fn triangle() -> anyhow::Result<()> { true => "tests/results/simple/triangle.png", false => "tests/results/simple/triangle-backface.png", }; - runner - .render_and_compare(FrameRenderSettings::new(), file_name, Threshold::Mean(0.0)) - .await - .with_context(|| { + runner.render_and_compare(FrameRenderSettings::new(), file_name, Threshold::Mean(0.0)).await.with_context( + || { format!( "Comparison failed on test (Handedness::{handedness:?}, FrontFace::{winding:?}, Visible: {visible})" ) - })?; + }, + )?; } Ok(()) @@ -120,12 +99,7 @@ pub async fn coordinate_space() -> anyhow::Result<()> { let iad = no_gpu_return!(rend3::create_iad(None, None, None, None).await) .context("InstanceAdapterDevice creation failed")?; - let Ok(runner) = TestRunner::builder() - .iad(iad.clone()) - .handedness(Handedness::Left) - .build() - .await - else { + let Ok(runner) = TestRunner::builder().iad(iad.clone()).handedness(Handedness::Left).build().await else { return Ok(()); }; @@ -142,19 +116,12 @@ pub async fn coordinate_space() -> anyhow::Result<()> { .build() .expect("Failed to create mesh"); - let color = if camera_vector.is_negative_bitmask() != 0 { - camera_vector * -0.25 - } else { - camera_vector - }; + let color = if camera_vector.is_negative_bitmask() != 0 { camera_vector * -0.25 } else { camera_vector }; let mesh_hdl = runner.add_mesh(mesh).unwrap(); let material_hdl = runner.add_unlit_material(color.extend(1.0)); - let object = Object { - mesh_kind: ObjectMeshKind::Static(mesh_hdl), - material: material_hdl, - transform: Mat4::IDENTITY, - }; + let object = + Object { mesh_kind: ObjectMeshKind::Static(mesh_hdl), material: material_hdl, transform: Mat4::IDENTITY }; runner.add_object(object) }); diff --git a/rend3-types/Cargo.toml b/rend3-types/Cargo.toml index d9668e44..692b2c6f 100644 --- a/rend3-types/Cargo.toml +++ b/rend3-types/Cargo.toml @@ -15,8 +15,8 @@ rust-version = "1.71" bitflags = "2" bytemuck = { version = "1", features = ["min_const_generics"] } cfg-if = "1" -encase = { version = "0.6", features = ["glam"] } -glam = { version = "0.24", features = ["bytemuck"] } +encase = { version = "0.7", features = ["glam"] } +glam = { version = "0.25", features = ["bytemuck"] } list-any = "0.2" once_cell = "1" thiserror = "1" diff --git a/rend3-types/src/attribute.rs b/rend3-types/src/attribute.rs index 977664ef..c9ad8ed9 100644 --- a/rend3-types/src/attribute.rs +++ b/rend3-types/src/attribute.rs @@ -53,12 +53,7 @@ where T: VertexFormat, { pub const fn new(name: &'static str, default_value: Option<&'static str>) -> Self { - Self { - name, - default_value, - id: OnceCell::new(), - _phantom: PhantomData, - } + Self { name, default_value, id: OnceCell::new(), _phantom: PhantomData } } pub fn name(&self) -> &'static str { @@ -100,35 +95,23 @@ pub trait VertexFormat: Pod + Send + Sync + 'static { // TODO: More formats impl VertexFormat for glam::Vec2 { - const METADATA: VertexFormatMetadata = VertexFormatMetadata { - size: 8, - shader_extract_fn: "extract_attribute_vec2_f32", - shader_type: "vec2", - }; + const METADATA: VertexFormatMetadata = + VertexFormatMetadata { size: 8, shader_extract_fn: "extract_attribute_vec2_f32", shader_type: "vec2" }; } impl VertexFormat for glam::Vec3 { - const METADATA: VertexFormatMetadata = VertexFormatMetadata { - size: 12, - shader_extract_fn: "extract_attribute_vec3_f32", - shader_type: "vec3", - }; + const METADATA: VertexFormatMetadata = + VertexFormatMetadata { size: 12, shader_extract_fn: "extract_attribute_vec3_f32", shader_type: "vec3" }; } impl VertexFormat for glam::Vec4 { - const METADATA: VertexFormatMetadata = VertexFormatMetadata { - size: 16, - shader_extract_fn: "extract_attribute_vec4_f32", - shader_type: "vec4", - }; + const METADATA: VertexFormatMetadata = + VertexFormatMetadata { size: 16, shader_extract_fn: "extract_attribute_vec4_f32", shader_type: "vec4" }; } impl VertexFormat for [u16; 4] { - const METADATA: VertexFormatMetadata = VertexFormatMetadata { - size: 8, - shader_extract_fn: "extract_attribute_vec4_u16", - shader_type: "vec4", - }; + const METADATA: VertexFormatMetadata = + VertexFormatMetadata { size: 8, shader_extract_fn: "extract_attribute_vec4_u16", shader_type: "vec4" }; } impl VertexFormat for [u8; 4] { diff --git a/rend3-types/src/lib.rs b/rend3-types/src/lib.rs index 8444ec16..1511684e 100644 --- a/rend3-types/src/lib.rs +++ b/rend3-types/src/lib.rs @@ -39,10 +39,7 @@ pub struct RawResourceHandle { impl RawResourceHandle { /// Creates a new handle with the given value pub const fn new(idx: usize) -> Self { - Self { - idx, - _phantom: PhantomData, - } + Self { idx, _phantom: PhantomData } } } @@ -109,11 +106,7 @@ impl Debug for ResourceHandle { impl Clone for ResourceHandle { fn clone(&self) -> Self { - Self { - refcount: self.refcount.clone(), - raw: self.raw, - _phantom: self._phantom, - } + Self { refcount: self.refcount.clone(), raw: self.raw, _phantom: self._phantom } } } @@ -138,10 +131,7 @@ impl ResourceHandle { pub fn new(destroy_fn: impl Fn(RawResourceHandle) + WasmNotSend + WasmNotSync + 'static, idx: usize) -> Self { Self { refcount: Arc::new(destroy_fn), - raw: RawResourceHandle { - idx, - _phantom: PhantomData, - }, + raw: RawResourceHandle { idx, _phantom: PhantomData }, _phantom: PhantomData, } } @@ -278,11 +268,7 @@ pub const MAX_INDEX_COUNT: u32 = u32::MAX; #[derive(Debug, Error)] pub enum MeshValidationError { #[error("Mesh's {:?} buffer has {actual} vertices but the position buffer has {expected}", .attribute_id.name())] - MismatchedVertexCount { - attribute_id: &'static VertexAttributeId, - expected: usize, - actual: usize, - }, + MismatchedVertexCount { attribute_id: &'static VertexAttributeId, expected: usize, actual: usize }, #[error("Mesh has {count} vertices when the vertex limit is {MAX_VERTEX_COUNT}")] ExceededMaxVertexCount { count: usize }, #[error("Mesh has {count} indicies when maximum index count is {MAX_INDEX_COUNT}")] @@ -309,12 +295,7 @@ impl StoredVertexAttributeData { { let bytes = (data.len() * size_of::()) as u64; let ptr = data.as_ptr() as *const u8; - Self { - id: attribute.id(), - data: WasmVecAny::from(data), - ptr, - bytes, - } + Self { id: attribute.id(), data: WasmVecAny::from(data), ptr, bytes } } pub fn id(&self) -> &'static VertexAttributeId { @@ -371,18 +352,14 @@ impl MeshBuilder { pub fn new(vertex_positions: Vec, handedness: Handedness) -> Self { Self { vertex_count: vertex_positions.len(), - vertex_attributes: vec![StoredVertexAttributeData::new( - &VERTEX_ATTRIBUTE_POSITION, - vertex_positions, - )], + vertex_attributes: vec![StoredVertexAttributeData::new(&VERTEX_ATTRIBUTE_POSITION, vertex_positions)], handedness, ..Self::default() } } pub fn with_attribute(mut self, attribute: &'static VertexAttribute, values: Vec) -> Self { - self.vertex_attributes - .push(StoredVertexAttributeData::new(attribute, values)); + self.vertex_attributes.push(StoredVertexAttributeData::new(attribute, values)); self } @@ -582,11 +559,7 @@ impl Mesh { for (index, &value) in self.indices.iter().enumerate() { if value as usize >= position_length { - return Err(MeshValidationError::IndexOutOfBounds { - index, - value, - max: position_length as u32, - }); + return Err(MeshValidationError::IndexOutOfBounds { index, value, max: position_length as u32 }); } } @@ -615,10 +588,8 @@ impl Mesh { index.map_or_else( || { let idx = self.attributes.len(); - self.attributes.push(StoredVertexAttributeData::new( - desired_attribute, - vec![T::zeroed(); self.vertex_count], - )); + self.attributes + .push(StoredVertexAttributeData::new(desired_attribute, vec![T::zeroed(); self.vertex_count])); // There were no normals, and our created normals are already zeroed. (idx, true) }, @@ -648,9 +619,7 @@ impl Mesh { let (position_attribute, remaining_attributes) = self.attributes.split_first_mut().unwrap(); let positions = position_attribute.typed_data(&VERTEX_ATTRIBUTE_POSITION).unwrap(); - let normals = remaining_attributes[normals_index - 1] - .typed_data_mut(&VERTEX_ATTRIBUTE_NORMAL) - .unwrap(); + let normals = remaining_attributes[normals_index - 1].typed_data_mut(&VERTEX_ATTRIBUTE_NORMAL).unwrap(); if handedness == Handedness::Left { unsafe { @@ -719,11 +688,7 @@ impl Mesh { let edge1 = pos2 - pos1; let edge2 = pos3 - pos1; - let normal = if LEFT_HANDED { - edge1.cross(edge2) - } else { - edge2.cross(edge1) - }; + let normal = if LEFT_HANDED { edge1.cross(edge2) } else { edge2.cross(edge1) }; // SAFETY: The conditions of this function assert all thes indices are in-bounds unsafe { *normals.get_unchecked_mut(idx0 as usize) += normal }; @@ -976,16 +941,10 @@ pub struct Sorting { impl Sorting { /// Default sorting for opaque and cutout objects - pub const OPAQUE: Self = Self { - reason: SortingReason::Optimization, - order: SortingOrder::FrontToBack, - }; + pub const OPAQUE: Self = Self { reason: SortingReason::Optimization, order: SortingOrder::FrontToBack }; /// Default sorting for any objects using blending - pub const BLENDING: Self = Self { - reason: SortingReason::Requirement, - order: SortingOrder::BackToFront, - }; + pub const BLENDING: Self = Self { reason: SortingReason::Requirement, order: SortingOrder::BackToFront }; } /// Reason why object need sorting diff --git a/rend3/Cargo.toml b/rend3/Cargo.toml index 7ab5bad0..02d58155 100644 --- a/rend3/Cargo.toml +++ b/rend3/Cargo.toml @@ -38,10 +38,10 @@ bimap = "0.6" bitflags = "2" bumpalo = "3" bytemuck = "1" -encase = { version = "0.6" } +encase = { version = "0.7" } flume = "0.11" -glam = { version = "0.24.0", features = ["bytemuck"] } -handlebars = "4" +glam = { version = "0.25.0", features = ["bytemuck"] } +handlebars = "5" indexmap = "2" list-any = "0.2" log = "0.4" diff --git a/rend3/src/graph/graph.rs b/rend3/src/graph/graph.rs index 2949bf7a..056e793c 100644 --- a/rend3/src/graph/graph.rs +++ b/rend3/src/graph/graph.rs @@ -60,10 +60,7 @@ pub(super) struct DataContents { impl DataContents { pub(super) fn new() -> Self { - Self { - inner: Box::new(RefCell::new(None::)), - dependencies: Vec::new(), - } + Self { inner: Box::new(RefCell::new(None::)), dependencies: Vec::new() } } } @@ -114,10 +111,7 @@ impl<'node> RenderGraph<'node> { layer_end: desc.depth, mip_start: 0, mip_end: desc.to_core().mip_count(), - viewport: ViewportRect { - offset: UVec2::ZERO, - size: desc.resolution, - }, + viewport: ViewportRect { offset: UVec2::ZERO, size: desc.resolution }, }), }; self.targets.push(desc); @@ -148,10 +142,7 @@ impl<'node> RenderGraph<'node> { pub fn add_data(&mut self) -> DataHandle { let idx = self.data.len(); self.data.push(DataContents::new::()); - DataHandle { - idx, - _phantom: PhantomData, - } + DataHandle { idx, _phantom: PhantomData } } fn flatten_dependencies(data: &[DataContents], resource_list: &mut Vec) { @@ -162,10 +153,7 @@ impl<'node> RenderGraph<'node> { resource_list.extend_from_slice(&data[idx].dependencies); // We can fall victim to cycles with this, so we assert on the length not being redonkulously large. - assert!( - resource_list.len() < (1 << 20), - "Rendergraph has dependencies of data that form a cycle" - ); + assert!(resource_list.len() < (1 << 20), "Rendergraph has dependencies of data that form a cycle"); } idx += 1; } @@ -226,11 +214,7 @@ impl<'node> RenderGraph<'node> { .and_modify(|span| { span.last_reference = Some(idx); }) - .or_insert(ResourceSpan { - first_reference: idx, - first_usage: None, - last_reference: Some(idx), - }); + .or_insert(ResourceSpan { first_reference: idx, first_usage: None, last_reference: Some(idx) }); } // Add or update the range for all inputs for &input in &node.inputs { @@ -260,11 +244,7 @@ impl<'node> RenderGraph<'node> { span.first_usage.get_or_insert(idx); span.last_reference = end }) - .or_insert(ResourceSpan { - first_reference: idx, - first_usage: Some(idx), - last_reference: end, - }); + .or_insert(ResourceSpan { first_reference: idx, first_usage: Some(idx), last_reference: end }); } } } @@ -358,15 +338,13 @@ impl<'node> RenderGraph<'node> { GraphSubResource::ImportedTexture(region) => { if let Entry::Vacant(vacant) = imported_views.entry(region) { let view = - self.imported_targets[region.idx] - .as_texture_ref() - .create_view(&TextureViewDescriptor { - base_array_layer: region.layer_start, - array_layer_count: Some(region.layer_end - region.layer_start), - base_mip_level: region.mip_start as u32, - mip_level_count: Some((region.mip_end - region.mip_start) as u32), - ..TextureViewDescriptor::default() - }); + self.imported_targets[region.idx].as_texture_ref().create_view(&TextureViewDescriptor { + base_array_layer: region.layer_start, + array_layer_count: Some(region.layer_end - region.layer_start), + base_mip_level: region.mip_start as u32, + mip_level_count: Some((region.mip_end - region.mip_start) as u32), + ..TextureViewDescriptor::default() + }); vacant.insert(view); } } @@ -410,11 +388,8 @@ impl<'node> RenderGraph<'node> { profiling::scope!("Run Nodes"); - let encoder_cell = UnsafeCell::new( - renderer - .device - .create_command_encoder(&CommandEncoderDescriptor::default()), - ); + let encoder_cell = + UnsafeCell::new(renderer.device.create_command_encoder(&CommandEncoderDescriptor::default())); let rpass_temps_cell = UnsafeCell::new(RpassTemporaryPool::new()); let mut next_rpass_idx = 0; @@ -509,11 +484,7 @@ impl<'node> RenderGraph<'node> { None => RenderGraphEncoderOrPassInner::Encoder(unsafe { &mut *encoder_cell.get() }), }; - data_core - .profiler - .try_lock() - .unwrap() - .end_query(&mut encoder_or_rpass, profiler_query); + data_core.profiler.try_lock().unwrap().end_query(&mut encoder_or_rpass, profiler_query); } } @@ -530,14 +501,10 @@ impl<'node> RenderGraph<'node> { // it eval_output.cmd_bufs.push(encoder_cell.into_inner().finish()); - let mut resolve_encoder = renderer.device.create_command_encoder(&CommandEncoderDescriptor { - label: Some("profile resolve encoder"), - }); - data_core - .profiler - .try_lock() - .unwrap() - .resolve_queries(&mut resolve_encoder); + let mut resolve_encoder = renderer + .device + .create_command_encoder(&CommandEncoderDescriptor { label: Some("profile resolve encoder") }); + data_core.profiler.try_lock().unwrap().resolve_queries(&mut resolve_encoder); eval_output.cmd_bufs.push(resolve_encoder.finish()); renderer.queue.submit(eval_output.cmd_bufs.drain(..)); @@ -545,11 +512,8 @@ impl<'node> RenderGraph<'node> { data_core.profiler.try_lock().unwrap().end_frame().unwrap(); // This variable seems superfluous, but solves borrow checker issues with the borrow of data_core. - let timers = data_core - .profiler - .try_lock() - .unwrap() - .process_finished_frame(renderer.queue.get_timestamp_period()); + let timers = + data_core.profiler.try_lock().unwrap().process_finished_frame(renderer.queue.get_timestamp_period()); timers } diff --git a/rend3/src/graph/node.rs b/rend3/src/graph/node.rs index 30ab9d3a..d38a732d 100644 --- a/rend3/src/graph/node.rs +++ b/rend3/src/graph/node.rs @@ -102,10 +102,7 @@ impl<'a, 'node> RenderGraphNodeBuilder<'a, 'node> { targets: RenderPassTargets, usage: NodeResourceUsage, ) -> DeclaredDependency { - assert!( - self.rpass.is_none(), - "Cannot have more than one graph-associated renderpass per node." - ); + assert!(self.rpass.is_none(), "Cannot have more than one graph-associated renderpass per node."); for targets in &targets.targets { self.add_render_target(targets.color, usage); self.add_optional_render_target(targets.resolve, usage); @@ -114,9 +111,7 @@ impl<'a, 'node> RenderGraphNodeBuilder<'a, 'node> { self.add_render_target(depth_stencil.target, usage); } self.rpass = Some(targets); - DeclaredDependency { - handle: RenderPassHandle, - } + DeclaredDependency { handle: RenderPassHandle } } /// Declares use of a data handle for reading. diff --git a/rend3/src/graph/store.rs b/rend3/src/graph/store.rs index 1950aecd..aa491fc1 100644 --- a/rend3/src/graph/store.rs +++ b/rend3/src/graph/store.rs @@ -48,10 +48,9 @@ impl<'a> RenderGraphDataStore<'a> { /// Get a rendertarget from the handle to one. pub fn get_render_target(&self, dep: DeclaredDependency) -> &'a TextureView { match dep.handle.resource { - GraphSubResource::Texture(name) => self - .texture_mapping - .get(&name) - .expect("internal rendergraph error: failed to get named texture"), + GraphSubResource::Texture(name) => { + self.texture_mapping.get(&name).expect("internal rendergraph error: failed to get named texture") + } GraphSubResource::ImportedTexture(name) => self .external_texture_mapping .get(&name) diff --git a/rend3/src/graph/temp.rs b/rend3/src/graph/temp.rs index f6af63f3..d4fce506 100644 --- a/rend3/src/graph/temp.rs +++ b/rend3/src/graph/temp.rs @@ -11,19 +11,14 @@ pub struct RpassTemporaryPool<'rpass> { } impl<'rpass> RpassTemporaryPool<'rpass> { pub(super) fn new() -> Self { - Self { - bump: Bump::new(), - dtors: RefCell::new(Vec::new()), - } + Self { bump: Bump::new(), dtors: RefCell::new(Vec::new()) } } #[allow(clippy::mut_from_ref)] pub fn add(&'rpass self, v: T) -> &'rpass mut T { let r = self.bump.alloc(v); let ptr = r as *mut T; - self.dtors - .borrow_mut() - .push(Box::new(move || unsafe { std::ptr::drop_in_place(ptr) })); + self.dtors.borrow_mut().push(Box::new(move || unsafe { std::ptr::drop_in_place(ptr) })); r } diff --git a/rend3/src/graph/texture_store.rs b/rend3/src/graph/texture_store.rs index 07981fca..c1566f97 100644 --- a/rend3/src/graph/texture_store.rs +++ b/rend3/src/graph/texture_store.rs @@ -19,9 +19,7 @@ pub(crate) struct GraphTextureStore { } impl GraphTextureStore { pub fn new() -> Self { - Self { - textures: FastHashMap::with_capacity_and_hasher(32, FastBuildHasher::default()), - } + Self { textures: FastHashMap::with_capacity_and_hasher(32, FastBuildHasher::default()) } } pub fn get_texture(&mut self, device: &Device, desc: RenderTargetCore) -> Arc { @@ -32,11 +30,7 @@ impl GraphTextureStore { Arc::new(device.create_texture(&TextureDescriptor { label: None, - size: Extent3d { - width: desc.resolution.x, - height: desc.resolution.y, - depth_or_array_layers: 1, - }, + size: Extent3d { width: desc.resolution.x, height: desc.resolution.y, depth_or_array_layers: 1 }, mip_level_count: desc.mip_count() as u32, sample_count: desc.samples as _, dimension: TextureDimension::D2, diff --git a/rend3/src/instruction.rs b/rend3/src/instruction.rs index 255a8ccf..6ee3a70f 100644 --- a/rend3/src/instruction.rs +++ b/rend3/src/instruction.rs @@ -131,10 +131,7 @@ pub struct InstructionStreamPair { } impl InstructionStreamPair { pub fn new() -> Self { - Self { - producer: Mutex::new(Vec::new()), - consumer: Mutex::new(Vec::new()), - } + Self { producer: Mutex::new(Vec::new()), consumer: Mutex::new(Vec::new()) } } pub fn swap(&self) { diff --git a/rend3/src/managers/camera.rs b/rend3/src/managers/camera.rs index 2fa6b6bb..deccd32d 100644 --- a/rend3/src/managers/camera.rs +++ b/rend3/src/managers/camera.rs @@ -29,15 +29,7 @@ impl CameraState { let frustum = Frustum::from_matrix(proj * data.view); - Self { - handedness, - orig_view, - proj, - inv_view: data.view.inverse(), - world_frustum: frustum, - data, - aspect_ratio, - } + Self { handedness, orig_view, proj, inv_view: data.view.inverse(), world_frustum: frustum, data, aspect_ratio } } /// Sets the camera data, rebuilding the using the given aspect ratio. If no diff --git a/rend3/src/managers/directional.rs b/rend3/src/managers/directional.rs index d90b9fad..b0563d37 100644 --- a/rend3/src/managers/directional.rs +++ b/rend3/src/managers/directional.rs @@ -89,11 +89,7 @@ impl DirectionalLightManager { } pub fn update(&mut self, handle: RawDirectionalLightHandle, change: DirectionalLightChange) { - self.data[handle.idx] - .as_mut() - .unwrap() - .inner - .update_from_changes(change); + self.data[handle.idx].as_mut().unwrap().inner.update_from_changes(change); } pub fn remove(&mut self, handle: RawDirectionalLightHandle) { @@ -155,8 +151,7 @@ impl DirectionalLightManager { .collect(), }; - self.data_buffer - .write_to_buffer(&renderer.device, &renderer.queue, &buffer); + self.data_buffer.write_to_buffer(&renderer.device, &renderer.queue, &buffer); (new_shadow_map_size, shadow_data) } @@ -183,11 +178,7 @@ fn create_shadow_texture(device: &Device, size: UVec2) -> TextureView { let texture = device.create_texture(&TextureDescriptor { label: Some("rend3 shadow texture"), - size: Extent3d { - width: size.x, - height: size.y, - depth_or_array_layers: 1, - }, + size: Extent3d { width: size.x, height: size.y, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: TextureDimension::D2, diff --git a/rend3/src/managers/directional/shadow_alloc.rs b/rend3/src/managers/directional/shadow_alloc.rs index bbcef236..11c830c7 100644 --- a/rend3/src/managers/directional/shadow_alloc.rs +++ b/rend3/src/managers/directional/shadow_alloc.rs @@ -38,9 +38,7 @@ impl ShadowNode { return false; } - children - .into_iter() - .any(|child| ShadowNode::try_alloc(nodes, child, relative_order - 1, handle)) + children.into_iter().any(|child| ShadowNode::try_alloc(nodes, child, relative_order - 1, handle)) } } } @@ -134,10 +132,7 @@ pub(super) fn allocate_shadow_atlas( } } - Some(ShadowAtlas { - texture_dimensions, - maps: output_maps, - }) + Some(ShadowAtlas { texture_dimensions, maps: output_maps }) } #[cfg(test)] @@ -234,14 +229,7 @@ mod tests { let res = allocate_shadow_atlas(maps, 16).unwrap(); assert_eq!(res.texture_dimensions, UVec2::splat(16)); - assert_eq!( - res.maps, - &[ShadowMap { - offset: UVec2::splat(0), - size: 16, - handle: RDLH::new(0) - }] - ); + assert_eq!(res.maps, &[ShadowMap { offset: UVec2::splat(0), size: 16, handle: RDLH::new(0) }]); } #[test] @@ -253,21 +241,9 @@ mod tests { assert_eq!( res.maps, &[ - ShadowMap { - offset: UVec2::splat(0), - size: 16, - handle: RDLH::new(0) - }, - ShadowMap { - offset: UVec2::new(16, 0), - size: 16, - handle: RDLH::new(1) - }, - ShadowMap { - offset: UVec2::new(32, 0), - size: 16, - handle: RDLH::new(2) - } + ShadowMap { offset: UVec2::splat(0), size: 16, handle: RDLH::new(0) }, + ShadowMap { offset: UVec2::new(16, 0), size: 16, handle: RDLH::new(1) }, + ShadowMap { offset: UVec2::new(32, 0), size: 16, handle: RDLH::new(2) } ] ); } @@ -281,65 +257,28 @@ mod tests { assert_eq!( res.maps, &[ - ShadowMap { - offset: UVec2::splat(0), - size: 16, - handle: RDLH::new(0) - }, - ShadowMap { - offset: UVec2::new(16, 0), - size: 16, - handle: RDLH::new(1) - }, - ShadowMap { - offset: UVec2::new(0, 16), - size: 16, - handle: RDLH::new(2) - } + ShadowMap { offset: UVec2::splat(0), size: 16, handle: RDLH::new(0) }, + ShadowMap { offset: UVec2::new(16, 0), size: 16, handle: RDLH::new(1) }, + ShadowMap { offset: UVec2::new(0, 16), size: 16, handle: RDLH::new(2) } ] ); } #[test] fn allocate_single_level_double_row_extra_space() { - let maps = vec![ - (RDLH::new(0), 16), - (RDLH::new(1), 16), - (RDLH::new(2), 16), - (RDLH::new(3), 16), - (RDLH::new(4), 16), - ]; + let maps = + vec![(RDLH::new(0), 16), (RDLH::new(1), 16), (RDLH::new(2), 16), (RDLH::new(3), 16), (RDLH::new(4), 16)]; let res = allocate_shadow_atlas(maps, 64).unwrap(); assert_eq!(res.texture_dimensions, UVec2::new(48, 32)); assert_eq!( res.maps, &[ - ShadowMap { - offset: UVec2::splat(0), - size: 16, - handle: RDLH::new(0) - }, - ShadowMap { - offset: UVec2::new(16, 0), - size: 16, - handle: RDLH::new(1) - }, - ShadowMap { - offset: UVec2::new(32, 0), - size: 16, - handle: RDLH::new(2) - }, - ShadowMap { - offset: UVec2::new(0, 16), - size: 16, - handle: RDLH::new(3) - }, - ShadowMap { - offset: UVec2::new(16, 16), - size: 16, - handle: RDLH::new(4) - } + ShadowMap { offset: UVec2::splat(0), size: 16, handle: RDLH::new(0) }, + ShadowMap { offset: UVec2::new(16, 0), size: 16, handle: RDLH::new(1) }, + ShadowMap { offset: UVec2::new(32, 0), size: 16, handle: RDLH::new(2) }, + ShadowMap { offset: UVec2::new(0, 16), size: 16, handle: RDLH::new(3) }, + ShadowMap { offset: UVec2::new(16, 16), size: 16, handle: RDLH::new(4) } ] ); } @@ -369,36 +308,12 @@ mod tests { assert_eq!( res.maps, &[ - ShadowMap { - offset: UVec2::splat(0), - size: 16, - handle: RDLH::new(0) - }, - ShadowMap { - offset: UVec2::new(16, 0), - size: 8, - handle: RDLH::new(1) - }, - ShadowMap { - offset: UVec2::new(24, 0), - size: 8, - handle: RDLH::new(2) - }, - ShadowMap { - offset: UVec2::new(16, 8), - size: 4, - handle: RDLH::new(3) - }, - ShadowMap { - offset: UVec2::new(20, 8), - size: 4, - handle: RDLH::new(4) - }, - ShadowMap { - offset: UVec2::new(16, 12), - size: 4, - handle: RDLH::new(5) - }, + ShadowMap { offset: UVec2::splat(0), size: 16, handle: RDLH::new(0) }, + ShadowMap { offset: UVec2::new(16, 0), size: 8, handle: RDLH::new(1) }, + ShadowMap { offset: UVec2::new(24, 0), size: 8, handle: RDLH::new(2) }, + ShadowMap { offset: UVec2::new(16, 8), size: 4, handle: RDLH::new(3) }, + ShadowMap { offset: UVec2::new(20, 8), size: 4, handle: RDLH::new(4) }, + ShadowMap { offset: UVec2::new(16, 12), size: 4, handle: RDLH::new(5) }, ] ); } diff --git a/rend3/src/managers/directional/shadow_camera.rs b/rend3/src/managers/directional/shadow_camera.rs index e3883b0a..a5538112 100644 --- a/rend3/src/managers/directional/shadow_camera.rs +++ b/rend3/src/managers/directional/shadow_camera.rs @@ -24,9 +24,7 @@ pub(super) fn shadow_camera(l: &InternalDirectionalLight, user_camera: &CameraSt CameraState::new( Camera { - projection: CameraProjection::Orthographic { - size: Vec3A::splat(l.inner.distance), - }, + projection: CameraProjection::Orthographic { size: Vec3A::splat(l.inner.distance) }, view: look_at(new_shadow_location, new_shadow_location + l.inner.direction, Vec3::Y), }, user_camera.handedness(), diff --git a/rend3/src/managers/graph_storage.rs b/rend3/src/managers/graph_storage.rs index c96d948b..63891b15 100644 --- a/rend3/src/managers/graph_storage.rs +++ b/rend3/src/managers/graph_storage.rs @@ -29,16 +29,12 @@ impl GraphStorage { pub fn get(&self, handle: &GraphDataHandle) -> impl Deref + '_ { let rw_lock: &RwLock = self.data[handle.0.idx].as_ref().unwrap().downcast_ref().unwrap(); - rw_lock - .try_read() - .expect("Called get on the same handle that was already borrowed mutably within a renderpass") + rw_lock.try_read().expect("Called get on the same handle that was already borrowed mutably within a renderpass") } pub fn get_mut(&self, handle: &GraphDataHandle) -> impl DerefMut + '_ { let rw_lock: &RwLock = self.data[handle.0.idx].as_ref().unwrap().downcast_ref().unwrap(); - rw_lock - .try_write() - .expect("Tried to call get_mut on the same handle twice within a renderpass") + rw_lock.try_write().expect("Tried to call get_mut on the same handle twice within a renderpass") } pub fn remove(&mut self, handle: &RawGraphDataHandleUntyped) { diff --git a/rend3/src/managers/handle_alloc.rs b/rend3/src/managers/handle_alloc.rs index 20dba352..dd32721b 100644 --- a/rend3/src/managers/handle_alloc.rs +++ b/rend3/src/managers/handle_alloc.rs @@ -49,9 +49,7 @@ where let renderer = Arc::clone(renderer); let destroy_fn = move |handle: RawResourceHandle| { - renderer - .instructions - .push(handle.into_delete_instruction_kind(), *Location::caller()) + renderer.instructions.push(handle.into_delete_instruction_kind(), *Location::caller()) }; ResourceHandle::new(destroy_fn, idx) @@ -71,10 +69,7 @@ where let mut locked_delay_list = delay_list.lock(); self.freelist.lock().extend_from_slice(&locked_delay_list); - locked_delay_list - .drain(..) - .map(|idx| RawResourceHandle::new(idx)) - .collect() + locked_delay_list.drain(..).map(|idx| RawResourceHandle::new(idx)).collect() } else { Vec::new() } diff --git a/rend3/src/managers/material.rs b/rend3/src/managers/material.rs index 2765b578..a5260c81 100644 --- a/rend3/src/managers/material.rs +++ b/rend3/src/managers/material.rs @@ -98,11 +98,7 @@ impl MaterialManager { let texture_deduplicator = texture_dedupe::TextureDeduplicator::new(device); - Self { - handle_to_typeid: FastHashMap::default(), - archetypes: FastHashMap::default(), - texture_deduplicator, - } + Self { handle_to_typeid: FastHashMap::default(), archetypes: FastHashMap::default(), texture_deduplicator } } pub fn ensure_archetype(&mut self, device: &Device, profile: RendererProfile) { @@ -144,8 +140,7 @@ impl MaterialManager { let textures = material.to_textures(); let texture_bg_index = - self.texture_deduplicator - .get_or_insert(device, texture_manager_2d, textures.as_ref()); + self.texture_deduplicator.get_or_insert(device, texture_manager_2d, textures.as_ref()); ProfileData::Cpu(texture_bg_index) } else { @@ -155,17 +150,11 @@ impl MaterialManager { let archetype = self.ensure_archetype_inner::(device, profile); archetype.buffer.use_index(handle.idx); - let mut data_vec = archetype - .data_vec - .downcast_mut::>>() - .unwrap(); + let mut data_vec = archetype.data_vec.downcast_mut::>>().unwrap(); if handle.idx >= data_vec.len() { data_vec.resize_with((handle.idx + 1).next_power_of_two(), || None); } - data_vec[handle.idx] = Some(InternalMaterial { - bind_group_index, - inner: material, - }); + data_vec[handle.idx] = Some(InternalMaterial { bind_group_index, inner: material }); drop(data_vec); self.handle_to_typeid.insert(handle, TypeId::of::()); @@ -184,18 +173,14 @@ impl MaterialManager { let archetype = self.archetypes.get_mut(&type_id).unwrap(); - let data_vec = archetype - .data_vec - .downcast_slice_mut::>>() - .unwrap(); + let data_vec = archetype.data_vec.downcast_slice_mut::>>().unwrap(); let internal = data_vec[handle.idx].as_mut().unwrap(); if let ProfileData::Cpu(ref mut index) = internal.bind_group_index { // Create the new bind group first. If the bind group didn't change, this will prevent // the bind group from dying on the call to remove. let bind_group_index = - self.texture_deduplicator - .get_or_insert(device, texture_manager_2d, material.to_textures().as_ref()); + self.texture_deduplicator.get_or_insert(device, texture_manager_2d, material.to_textures().as_ref()); self.texture_deduplicator.remove(*index); *index = bind_group_index; } @@ -244,10 +229,7 @@ impl MaterialManager { pub fn archetype_view(&self) -> MaterialArchetypeView<'_, M> { let archetype = &self.archetypes[&TypeId::of::()]; - MaterialArchetypeView { - buffer: &archetype.buffer, - data_vec: archetype.data_vec.downcast_slice().unwrap(), - } + MaterialArchetypeView { buffer: &archetype.buffer, data_vec: archetype.data_vec.downcast_slice().unwrap() } } pub fn texture_bind_group(&self, index: TextureBindGroupIndex) -> &BindGroup { diff --git a/rend3/src/managers/material/texture_dedupe.rs b/rend3/src/managers/material/texture_dedupe.rs index 090676ca..5ade6f9e 100644 --- a/rend3/src/managers/material/texture_dedupe.rs +++ b/rend3/src/managers/material/texture_dedupe.rs @@ -67,11 +67,7 @@ impl TextureDeduplicator { }) .collect(); - Self { - bgls, - deduplication_map: BiMap::default(), - storage: FreelistVec::new(), - } + Self { bgls, deduplication_map: BiMap::default(), storage: FreelistVec::new() } } pub fn get_or_insert( @@ -96,10 +92,7 @@ impl TextureDeduplicator { texture_manager_2d.get_null_view() }; - BindGroupEntry { - binding: idx as u32, - resource: BindingResource::TextureView(view), - } + BindGroupEntry { binding: idx as u32, resource: BindingResource::TextureView(view) } }) .collect(); diff --git a/rend3/src/managers/mesh.rs b/rend3/src/managers/mesh.rs index 5bd62d57..47910816 100644 --- a/rend3/src/managers/mesh.rs +++ b/rend3/src/managers/mesh.rs @@ -53,9 +53,7 @@ impl InternalMesh { } pub fn get_attribute(&self, attribute: &VertexAttributeId) -> Option> { - self.vertex_attribute_ranges - .iter() - .find_map(|(id, range)| (*id == *attribute).then_some(range.clone())) + self.vertex_attribute_ranges.iter().find_map(|(id, range)| (*id == *attribute).then_some(range.clone())) } } @@ -113,17 +111,11 @@ impl MeshManager { let data = Mutex::new(Vec::new()); - let encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("mesh manager init encoder"), - }); + let encoder = + device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("mesh manager init encoder") }); Self { - buffer_state: Mutex::new(BufferState { - buffer, - allocator, - encoder, - wait_group: WaitGroup::new(), - }), + buffer_state: Mutex::new(BufferState { buffer, allocator, encoder, wait_group: WaitGroup::new() }), data, } } @@ -141,10 +133,8 @@ impl MeshManager { // This value is used later when setting joints, to make sure all indices are // in-bounds with the specified amount of joints. let mut required_joint_count = None; - let joint_indices_attribute = mesh - .attributes - .iter() - .find_map(|attribute| attribute.typed_data(&VERTEX_ATTRIBUTE_JOINT_INDICES)); + let joint_indices_attribute = + mesh.attributes.iter().find_map(|attribute| attribute.typed_data(&VERTEX_ATTRIBUTE_JOINT_INDICES)); if let Some(joint_indices) = joint_indices_attribute { required_joint_count = Some(joint_indices.iter().flatten().max().map_or(0, |v| v + 1)); } @@ -164,9 +154,7 @@ impl MeshManager { let index_range = self.allocate_range_impl(device, buffer_state, index_count as u64 * 4)?; upload.add(index_range.start, bytemuck::cast_slice(&mesh.indices)); - upload - .create_staging_buffer(device) - .map_err(|e| MeshCreationError::BufferWriteFailed { inner: e })?; + upload.create_staging_buffer(device).map_err(|e| MeshCreationError::BufferWriteFailed { inner: e })?; upload.encode_upload(&mut buffer_state.encoder, &buffer_state.buffer); let staging_guard = buffer_state.wait_group.increment(); @@ -223,9 +211,8 @@ impl MeshManager { } pub fn evaluate(&self, device: &Device) -> (Arc, CommandBuffer) { - let new_encoder = device.create_command_encoder(&CommandEncoderDescriptor { - label: Some("mesh manager init encoder"), - }); + let new_encoder = + device.create_command_encoder(&CommandEncoderDescriptor { label: Some("mesh manager init encoder") }); let mut buffer_state = self.buffer_state.lock(); let buffer = buffer_state.buffer.clone(); @@ -304,10 +291,7 @@ impl MeshManager { usage: BufferUsages::COPY_SRC | BufferUsages::COPY_DST | BufferUsages::INDEX | BufferUsages::STORAGE, mapped_at_creation: false, })); - scope.end().map_err(|e| MeshCreationError::BufferAllocationFailed { - size: new_bytes, - inner: e, - })?; + scope.end().map_err(|e| MeshCreationError::BufferAllocationFailed { size: new_bytes, inner: e })?; buffer_state.encoder.copy_buffer_to_buffer( &buffer_state.buffer, diff --git a/rend3/src/managers/object.rs b/rend3/src/managers/object.rs index e4799f51..381a242e 100644 --- a/rend3/src/managers/object.rs +++ b/rend3/src/managers/object.rs @@ -103,10 +103,7 @@ impl ObjectManager { pub fn new() -> Self { profiling::scope!("ObjectManager::new"); - Self { - archetype: FastHashMap::default(), - handle_to_typeid: FastHashMap::default(), - } + Self { archetype: FastHashMap::default(), handle_to_typeid: FastHashMap::default() } } fn ensure_archetype(&mut self, device: &Device) -> &mut ObjectArchetype { @@ -146,14 +143,7 @@ impl ObjectManager { material_manager.call_object_add_callback( *object.material, - ObjectAddCallbackArgs { - device, - manager: self, - internal_mesh, - skeleton_ranges, - handle, - object, - }, + ObjectAddCallbackArgs { device, manager: self, internal_mesh, skeleton_ranges, handle, object }, ); } @@ -224,14 +214,7 @@ impl ObjectManager { let dst_obj = (archetype.duplicate_object)(&mut archetype.data_vec, src_handle.idx, change); - self.add( - device, - dst_handle, - dst_obj, - mesh_manager, - skeleton_manager, - material_manager, - ); + self.add(device, dst_handle, dst_obj, mesh_manager, skeleton_manager, material_manager); } } @@ -254,18 +237,11 @@ pub(super) fn object_add_callback(_material: &M, args: ObjectAddCal // Make sure all required attributes are in the mesh and the supported attribute list. for &required_attribute in M::required_attributes().into_iter() { // We can just directly use the internal mesh, as every attribute in the skeleton is also in the mesh. - let found_in_mesh = args - .internal_mesh - .vertex_attribute_ranges - .iter() - .any(|&(id, _)| id == required_attribute); + let found_in_mesh = args.internal_mesh.vertex_attribute_ranges.iter().any(|&(id, _)| id == required_attribute); // Check that our required attributes are in the supported one. - let found_in_supported = args - .internal_mesh - .vertex_attribute_ranges - .iter() - .any(|&(id, _)| id == required_attribute); + let found_in_supported = + args.internal_mesh.vertex_attribute_ranges.iter().any(|&(id, _)| id == required_attribute); assert!(found_in_mesh); assert!(found_in_supported); @@ -273,10 +249,8 @@ pub(super) fn object_add_callback(_material: &M, args: ObjectAddCal let vertex_attribute_start_offsets = M::supported_attributes().map_to_u32(|&supported_attribute| { // We first check the skeleton for the attribute's base offset. - let found_start_offset = args - .skeleton_ranges - .iter() - .find_map(|(id, range)| (*id == supported_attribute).then_some(range.start)); + let found_start_offset = + args.skeleton_ranges.iter().find_map(|(id, range)| (*id == supported_attribute).then_some(range.start)); if let Some(start_offset) = found_start_offset { return start_offset as u32; @@ -354,10 +328,7 @@ fn duplicate_object(data: &WasmVecAny, idx: usize, change: ObjectCh } fn remove(archetype: &mut ObjectArchetype, idx: usize) { - let data_vec = archetype - .data_vec - .downcast_slice_mut::>>() - .unwrap(); + let data_vec = archetype.data_vec.downcast_slice_mut::>>().unwrap(); // We don't actually remove the object at this point, // we just mark it as disabled. Next frame, this handle @@ -377,10 +348,7 @@ fn evaluate( scatter: &ScatterCopy, deferred_removals: &[RawObjectHandle], ) { - let data_vec = archetype - .data_vec - .downcast_slice_mut::>>() - .unwrap(); + let data_vec = archetype.data_vec.downcast_slice_mut::>>().unwrap(); for removal in deferred_removals { // Only one archetype will have each handle, @@ -392,7 +360,5 @@ fn evaluate( } } - archetype.buffer.apply(device, encoder, scatter, |idx| { - data_vec[idx].as_ref().map(|o| o.inner).unwrap_or_default() - }) + archetype.buffer.apply(device, encoder, scatter, |idx| data_vec[idx].as_ref().map(|o| o.inner).unwrap_or_default()) } diff --git a/rend3/src/managers/point.rs b/rend3/src/managers/point.rs index a2e6f339..142e93f9 100644 --- a/rend3/src/managers/point.rs +++ b/rend3/src/managers/point.rs @@ -70,8 +70,7 @@ impl PointLightManager { .collect(), }; - self.data_buffer - .write_to_buffer(&renderer.device, &renderer.queue, &buffer); + self.data_buffer.write_to_buffer(&renderer.device, &renderer.queue, &buffer); } pub fn add_to_bgl(bglb: &mut BindGroupLayoutBuilder) { diff --git a/rend3/src/managers/skeleton.rs b/rend3/src/managers/skeleton.rs index ebf590cc..9507ee92 100644 --- a/rend3/src/managers/skeleton.rs +++ b/rend3/src/managers/skeleton.rs @@ -44,10 +44,7 @@ pub enum SkeletonCreationError { "Not enough joints to create this skeleton. The mesh has {mesh_joint_count} joints, \ but only {joint_matrix_count} joint matrices were provided." )] - NotEnoughJoints { - mesh_joint_count: u16, - joint_matrix_count: usize, - }, + NotEnoughJoints { mesh_joint_count: u16, joint_matrix_count: usize }, } /// Manages skeletons. @@ -64,11 +61,7 @@ impl SkeletonManager { pub fn new() -> Self { profiling::scope!("SkeletonManager::new"); - Self { - data: Vec::new(), - skeleton_count: 0, - global_joint_count: 0, - } + Self { data: Vec::new(), skeleton_count: 0, global_joint_count: 0 } } pub fn validate_skeleton( @@ -77,9 +70,8 @@ impl SkeletonManager { skeleton: Skeleton, ) -> Result { let internal_mesh = &mesh_manager.lock_internal_data()[skeleton.mesh.get_raw()]; - let required_joint_count = internal_mesh - .required_joint_count - .ok_or(SkeletonCreationError::MissingAttributesJointIndices)?; + let required_joint_count = + internal_mesh.required_joint_count.ok_or(SkeletonCreationError::MissingAttributesJointIndices)?; let joint_weight_range = internal_mesh .get_attribute(&VERTEX_ATTRIBUTE_JOINT_WEIGHTS) @@ -96,11 +88,7 @@ impl SkeletonManager { }); } - let overridden_attributes = [ - &VERTEX_ATTRIBUTE_POSITION, - &VERTEX_ATTRIBUTE_NORMAL, - &VERTEX_ATTRIBUTE_TANGENT, - ]; + let overridden_attributes = [&VERTEX_ATTRIBUTE_POSITION, &VERTEX_ATTRIBUTE_NORMAL, &VERTEX_ATTRIBUTE_TANGENT]; let mut source_attribute_ranges: ArrayVec<_, 5> = ArrayVec::new(); source_attribute_ranges.push((*VERTEX_ATTRIBUTE_JOINT_WEIGHTS.id(), joint_weight_range)); diff --git a/rend3/src/managers/texture.rs b/rend3/src/managers/texture.rs index 872e4332..21863023 100644 --- a/rend3/src/managers/texture.rs +++ b/rend3/src/managers/texture.rs @@ -40,15 +40,9 @@ pub enum TextureCreationError { #[error("Failed to create texture view")] TextureViewCreationFailed(#[source] wgpu::Error), #[error("Textures formats must allow filtering with a linear filter. {format:?} has sample type {sample_type:?} which does not.")] - TextureFormatNotFilterable { - format: TextureFormat, - sample_type: TextureSampleType, - }, + TextureFormatNotFilterable { format: TextureFormat, sample_type: TextureSampleType }, #[error("Textures formats must be sample-able as floating point. {format:?} has sample type {sample_type:?}.")] - TextureFormatNotFloat { - format: TextureFormat, - sample_type: Option, - }, + TextureFormatNotFloat { format: TextureFormat, sample_type: Option }, #[error("Mipmap creation failed")] MipmapCreationFailed(#[from] MipmapGenerationError), } @@ -87,10 +81,8 @@ impl TextureManager { data.resize_with(TEXTURE_PREALLOCATION, || None); let layout = profile.into_data(|| (), || create_bind_group_layout(device, max_textures, dimension)); - let group = profile.into_data( - || (), - || create_bind_group(device, layout.as_gpu(), &null_view, &data, dimension), - ); + let group = + profile.into_data(|| (), || create_bind_group(device, layout.as_gpu(), &null_view, &data, dimension)); Self { layout, @@ -108,7 +100,7 @@ impl TextureManager { texture: crate::types::Texture, cube: bool, ) -> Result<(Option, InternalTexture), TextureCreationError> { - validate_texture_format(texture.format, renderer.device.features())?; + validate_texture_format(texture.format, renderer.features)?; let (block_x, block_y) = texture.format.block_dimensions(); let size = Extent3d { @@ -154,10 +146,7 @@ impl TextureManager { MipmapSource::Generated => { assert!(!cube, "Cannot generate mipmaps from cubemaps currently"); - let desc = TextureDescriptor { - usage: desc.usage | TextureUsages::RENDER_ATTACHMENT, - ..desc - }; + let desc = TextureDescriptor { usage: desc.usage | TextureUsages::RENDER_ATTACHMENT, ..desc }; let scope = AllocationErrorScope::new(&renderer.device); let tex = renderer.device.create_texture(&desc); scope.end().map_err(TextureCreationError::TextureAllocationFailed)?; @@ -184,14 +173,10 @@ impl TextureManager { ); scope.end().map_err(TextureCreationError::WriteTextureFailed)?; - let mut encoder = renderer - .device - .create_command_encoder(&CommandEncoderDescriptor::default()); + let mut encoder = renderer.device.create_command_encoder(&CommandEncoderDescriptor::default()); // generate mipmaps - renderer - .mipmap_generator - .generate_mipmaps(&renderer.device, &mut encoder, &tex, &desc)?; + renderer.mipmap_generator.generate_mipmaps(&renderer.device, &mut encoder, &tex, &desc)?; (Some(encoder.finish()), tex) } @@ -207,14 +192,7 @@ impl TextureManager { }); scope.end().map_err(TextureCreationError::TextureViewCreationFailed)?; - Ok(( - buffer, - InternalTexture { - texture: tex, - view, - desc, - }, - )) + Ok((buffer, InternalTexture { texture: tex, view, desc })) } pub fn fill_from_texture( @@ -224,23 +202,15 @@ impl TextureManager { dst_handle: RawResourceHandle, texture: TextureFromTexture, ) { - let InternalTexture { - texture: old_texture, - desc: old_texture_desc, - .. - } = self.data[texture.src.idx].as_ref().unwrap(); + let InternalTexture { texture: old_texture, desc: old_texture_desc, .. } = + self.data[texture.src.idx].as_ref().unwrap(); let new_size = old_texture_desc.mip_level_size(texture.start_mip).unwrap(); - let mip_level_count = texture - .mip_count - .map_or_else(|| old_texture_desc.mip_level_count - texture.start_mip, |c| c.get()); + let mip_level_count = + texture.mip_count.map_or_else(|| old_texture_desc.mip_level_count - texture.start_mip, |c| c.get()); - let desc = TextureDescriptor { - size: new_size, - mip_level_count, - ..old_texture_desc.clone() - }; + let desc = TextureDescriptor { size: new_size, mip_level_count, ..old_texture_desc.clone() }; let tex = device.create_texture(&desc); @@ -268,14 +238,7 @@ impl TextureManager { ); } - self.fill( - dst_handle, - InternalTexture { - texture: tex, - view, - desc, - }, - ) + self.fill(dst_handle, InternalTexture { texture: tex, view, desc }) } pub fn fill(&mut self, handle: RawResourceHandle, internal_texture: InternalTexture) { @@ -300,23 +263,14 @@ impl TextureManager { profiling::scope!("Update GPU Texture Arrays"); if group_dirty { - *self.group.as_gpu_mut() = create_bind_group( - device, - self.layout.as_gpu(), - &self.null_view, - &self.data, - self.dimension, - ); + *self.group.as_gpu_mut() = + create_bind_group(device, self.layout.as_gpu(), &self.null_view, &self.data, self.dimension); *self.group_dirty.as_gpu_mut() = false; } - TextureManagerEvaluateOutput { - bg: self.group.as_ref().map(|_| (), Arc::clone), - } + TextureManagerEvaluateOutput { bg: self.group.as_ref().map(|_| (), Arc::clone) } } else { - TextureManagerEvaluateOutput { - bg: ProfileData::Cpu(()), - } + TextureManagerEvaluateOutput { bg: ProfileData::Cpu(()) } } } @@ -379,10 +333,7 @@ fn create_bind_group( Arc::new(device.create_bind_group(&BindGroupDescriptor { label: Some(&*format!("{:?} texture bg count {}", dimension, count)), layout, - entries: &[BindGroupEntry { - binding: 0, - resource: BindingResource::TextureViewArray(&view_array), - }], + entries: &[BindGroupEntry { binding: 0, resource: BindingResource::TextureViewArray(&view_array) }], })) } @@ -412,20 +363,16 @@ fn create_null_tex_view(device: &Device, dimension: TextureViewDimension) -> Tex usage: TextureUsages::TEXTURE_BINDING, view_formats: &[], }) - .create_view(&TextureViewDescriptor { - dimension: Some(dimension), - ..TextureViewDescriptor::default() - }) + .create_view(&TextureViewDescriptor { dimension: Some(dimension), ..TextureViewDescriptor::default() }) } fn validate_texture_format(format: TextureFormat, features: Features) -> Result<(), TextureCreationError> { let sample_type = format.sample_type(None, Some(features)); match sample_type { Some(TextureSampleType::Float { filterable: true }) => Ok(()), - Some(TextureSampleType::Float { filterable: false }) => Err(TextureCreationError::TextureFormatNotFilterable { - format, - sample_type: sample_type.unwrap(), - }), + Some(TextureSampleType::Float { filterable: false }) => { + Err(TextureCreationError::TextureFormatNotFilterable { format, sample_type: sample_type.unwrap() }) + } _ => Err(TextureCreationError::TextureFormatNotFloat { format, sample_type }), } } diff --git a/rend3/src/renderer/error.rs b/rend3/src/renderer/error.rs index b3b98f6d..5b2b23aa 100644 --- a/rend3/src/renderer/error.rs +++ b/rend3/src/renderer/error.rs @@ -41,17 +41,8 @@ pub enum LimitType { pub enum RendererInitializationError { #[error("No supported adapter found")] MissingAdapter, - #[error( - "The device limit of {:?} is {} but renderer requires at least {}", - ty, - device_limit, - required_limit - )] - LowDeviceLimit { - ty: LimitType, - device_limit: u64, - required_limit: u64, - }, + #[error("The device limit of {:?} is {} but renderer requires at least {}", ty, device_limit, required_limit)] + LowDeviceLimit { ty: LimitType, device_limit: u64, required_limit: u64 }, #[error("Device is missing required features: {:?}", features)] MissingDeviceFeatures { features: Features }, #[error("Requesting a device failed")] diff --git a/rend3/src/renderer/eval.rs b/rend3/src/renderer/eval.rs index b8a5665d..8b003584 100644 --- a/rend3/src/renderer/eval.rs +++ b/rend3/src/renderer/eval.rs @@ -16,9 +16,8 @@ pub fn evaluate_instructions(renderer: &Renderer) -> InstructionEvaluationOutput // 16 encoders is a reasonable default let mut cmd_bufs = Vec::with_capacity(16); - let mut encoder = renderer.device.create_command_encoder(&CommandEncoderDescriptor { - label: Some("primary encoder"), - }); + let mut encoder = + renderer.device.create_command_encoder(&CommandEncoderDescriptor { label: Some("primary encoder") }); let mut data_core = renderer.data_core.lock(); let data_core = &mut *data_core; @@ -35,28 +34,16 @@ pub fn evaluate_instructions(renderer: &Renderer) -> InstructionEvaluationOutput &renderer.device, ); data_core.skeleton_manager.add(handle, *skeleton); - data_core - .profiler - .try_lock() - .unwrap() - .end_query(&mut encoder, profiler_query); - } - InstructionKind::AddTexture2D { - handle, - internal_texture, - cmd_buf, - } => { + data_core.profiler.try_lock().unwrap().end_query(&mut encoder, profiler_query); + } + InstructionKind::AddTexture2D { handle, internal_texture, cmd_buf } => { cmd_bufs.extend(cmd_buf); data_core.d2_texture_manager.fill(handle, internal_texture); } - InstructionKind::AddTexture2DFromTexture { handle, texture } => data_core - .d2_texture_manager - .fill_from_texture(&renderer.device, &mut encoder, handle, texture), - InstructionKind::AddTextureCube { - handle, - internal_texture, - cmd_buf, - } => { + InstructionKind::AddTexture2DFromTexture { handle, texture } => { + data_core.d2_texture_manager.fill_from_texture(&renderer.device, &mut encoder, handle, texture) + } + InstructionKind::AddTextureCube { handle, internal_texture, cmd_buf } => { cmd_bufs.extend(cmd_buf); data_core.d2c_texture_manager.fill(handle, internal_texture); } @@ -117,11 +104,7 @@ pub fn evaluate_instructions(renderer: &Renderer) -> InstructionEvaluationOutput InstructionKind::SetCameraData { data } => { data_core.viewport_camera_state.set_data(data); } - InstructionKind::DuplicateObject { - src_handle, - dst_handle, - change, - } => { + InstructionKind::DuplicateObject { src_handle, dst_handle, change } => { data_core.object_manager.duplicate_object( &renderer.device, src_handle, @@ -174,12 +157,7 @@ pub fn evaluate_instructions(renderer: &Renderer) -> InstructionEvaluationOutput // Do these in dependency order // Level 3 - data_core.object_manager.evaluate( - &renderer.device, - &mut encoder, - &renderer.scatter, - &delayed_object_handles, - ); + data_core.object_manager.evaluate(&renderer.device, &mut encoder, &renderer.scatter, &delayed_object_handles); // Level 2 let d2_texture = data_core.d2_texture_manager.evaluate(&renderer.device); @@ -197,21 +175,13 @@ pub fn evaluate_instructions(renderer: &Renderer) -> InstructionEvaluationOutput // Level 0 let d2c_texture = data_core.d2c_texture_manager.evaluate(&renderer.device); - let (shadow_target_size, shadows) = data_core - .directional_light_manager - .evaluate(renderer, &data_core.viewport_camera_state); + let (shadow_target_size, shadows) = + data_core.directional_light_manager.evaluate(renderer, &data_core.viewport_camera_state); data_core.point_light_manager.evaluate(renderer); let (mesh_buffer, mesh_cmd_buf) = renderer.mesh_manager.evaluate(&renderer.device); cmd_bufs.push(mesh_cmd_buf); cmd_bufs.push(encoder.finish()); - InstructionEvaluationOutput { - cmd_bufs, - d2_texture, - d2c_texture, - shadow_target_size, - shadows, - mesh_buffer, - } + InstructionEvaluationOutput { cmd_bufs, d2_texture, d2c_texture, shadow_target_size, shadows, mesh_buffer } } diff --git a/rend3/src/renderer/mod.rs b/rend3/src/renderer/mod.rs index 660280ef..5c5ed5f6 100644 --- a/rend3/src/renderer/mod.rs +++ b/rend3/src/renderer/mod.rs @@ -169,13 +169,8 @@ impl Renderer { // Handle allocation must be done _after_ any validation to prevent deletion of a handle that never gets fully added. let handle = self.resource_handle_allocators.skeleton.allocate(self); - self.instructions.push( - InstructionKind::AddSkeleton { - handle: *handle, - skeleton: Box::new(internal), - }, - *Location::caller(), - ); + self.instructions + .push(InstructionKind::AddSkeleton { handle: *handle, skeleton: Box::new(internal) }, *Location::caller()); Ok(handle) } @@ -193,14 +188,8 @@ impl Renderer { // Handle allocation must be done _after_ any validation to prevent deletion of a handle that never gets fully added. let handle = self.resource_handle_allocators.d2_texture.allocate(self); - self.instructions.push( - InstructionKind::AddTexture2D { - handle: *handle, - internal_texture, - cmd_buf, - }, - *Location::caller(), - ); + self.instructions + .push(InstructionKind::AddTexture2D { handle: *handle, internal_texture, cmd_buf }, *Location::caller()); Ok(handle) } @@ -216,13 +205,8 @@ impl Renderer { let handle = self.resource_handle_allocators.d2_texture.allocate(self); - self.instructions.push( - InstructionKind::AddTexture2DFromTexture { - handle: *handle, - texture, - }, - *Location::caller(), - ); + self.instructions + .push(InstructionKind::AddTexture2DFromTexture { handle: *handle, texture }, *Location::caller()); handle } @@ -240,14 +224,8 @@ impl Renderer { // Handle allocation must be done _after_ any validation to prevent deletion of a handle that never gets fully added. let handle = self.resource_handle_allocators.d2c_texture.allocate(self); - self.instructions.push( - InstructionKind::AddTextureCube { - handle: *handle, - internal_texture, - cmd_buf, - }, - *Location::caller(), - ); + self.instructions + .push(InstructionKind::AddTextureCube { handle: *handle, internal_texture, cmd_buf }, *Location::caller()); Ok(handle) } @@ -296,13 +274,7 @@ impl Renderer { #[track_caller] pub fn add_object(self: &Arc, object: Object) -> ObjectHandle { let handle = self.resource_handle_allocators.object.allocate(self); - self.instructions.push( - InstructionKind::AddObject { - handle: *handle, - object, - }, - *Location::caller(), - ); + self.instructions.push(InstructionKind::AddObject { handle: *handle, object }, *Location::caller()); handle } @@ -314,11 +286,7 @@ impl Renderer { pub fn duplicate_object(self: &Arc, object_handle: &ObjectHandle, change: ObjectChange) -> ObjectHandle { let dst_handle = self.resource_handle_allocators.object.allocate(self); self.instructions.push( - InstructionKind::DuplicateObject { - src_handle: **object_handle, - dst_handle: *dst_handle, - change, - }, + InstructionKind::DuplicateObject { src_handle: **object_handle, dst_handle: *dst_handle, change }, *Location::caller(), ); dst_handle @@ -327,13 +295,8 @@ impl Renderer { /// Move the given object to a new transform location. #[track_caller] pub fn set_object_transform(&self, handle: &ObjectHandle, transform: Mat4) { - self.instructions.push( - InstructionKind::SetObjectTransform { - handle: handle.get_raw(), - transform, - }, - *Location::caller(), - ); + self.instructions + .push(InstructionKind::SetObjectTransform { handle: handle.get_raw(), transform }, *Location::caller()); } /// Sets the joint positions for a skeleton. See @@ -368,10 +331,7 @@ impl Renderer { #[track_caller] pub fn set_skeleton_joint_matrices(&self, handle: &SkeletonHandle, joint_matrices: Vec) { self.instructions.push( - InstructionKind::SetSkeletonJointDeltas { - handle: handle.get_raw(), - joint_matrices, - }, + InstructionKind::SetSkeletonJointDeltas { handle: handle.get_raw(), joint_matrices }, *Location::caller(), ) } @@ -383,10 +343,7 @@ impl Renderer { pub fn add_directional_light(self: &Arc, light: DirectionalLight) -> DirectionalLightHandle { let handle = self.resource_handle_allocators.directional_light.allocate(self); - self.instructions.push( - InstructionKind::AddDirectionalLight { handle: *handle, light }, - *Location::caller(), - ); + self.instructions.push(InstructionKind::AddDirectionalLight { handle: *handle, light }, *Location::caller()); handle } @@ -402,10 +359,7 @@ impl Renderer { pub fn add_point_light(self: &Arc, light: PointLight) -> PointLightHandle { let handle = self.resource_handle_allocators.point_light.allocate(self); - self.instructions.push( - InstructionKind::AddPointLight { handle: *handle, light }, - *Location::caller(), - ); + self.instructions.push(InstructionKind::AddPointLight { handle: *handle, light }, *Location::caller()); handle } @@ -413,25 +367,15 @@ impl Renderer { /// Updates the settings for given directional light. #[track_caller] pub fn update_directional_light(&self, handle: &DirectionalLightHandle, change: DirectionalLightChange) { - self.instructions.push( - InstructionKind::ChangeDirectionalLight { - handle: handle.get_raw(), - change, - }, - *Location::caller(), - ) + self.instructions + .push(InstructionKind::ChangeDirectionalLight { handle: handle.get_raw(), change }, *Location::caller()) } /// Updates the settings for given point light. #[track_caller] pub fn update_point_light(&self, handle: &PointLightHandle, change: PointLightChange) { - self.instructions.push( - InstructionKind::ChangePointLight { - handle: handle.get_raw(), - change, - }, - *Location::caller(), - ) + self.instructions + .push(InstructionKind::ChangePointLight { handle: handle.get_raw(), change }, *Location::caller()) } /// Adds a piece of data for long term storage and convienient use in the RenderGraph @@ -442,9 +386,7 @@ impl Renderer { let handle = self.resource_handle_allocators.graph_storage.allocate(self); let handle2 = *handle; self.instructions.push( - InstructionKind::AddGraphData { - add_invoke: Box::new(move |storage| storage.add(&handle2, data)), - }, + InstructionKind::AddGraphData { add_invoke: Box::new(move |storage| storage.add(&handle2, data)) }, *Location::caller(), ); GraphDataHandle(handle, PhantomData) @@ -454,15 +396,13 @@ impl Renderer { /// aspect ratio of the user. #[track_caller] pub fn set_aspect_ratio(&self, ratio: f32) { - self.instructions - .push(InstructionKind::SetAspectRatio { ratio }, *Location::caller()) + self.instructions.push(InstructionKind::SetAspectRatio { ratio }, *Location::caller()) } /// Sets the position, pov, or projection mode of the camera. #[track_caller] pub fn set_camera_data(&self, data: Camera) { - self.instructions - .push(InstructionKind::SetCameraData { data }, *Location::caller()) + self.instructions.push(InstructionKind::SetCameraData { data }, *Location::caller()) } /// Swaps the front and back instruction buffer. Any world-modifiying functions diff --git a/rend3/src/renderer/setup.rs b/rend3/src/renderer/setup.rs index 07d19a9d..ec4c31e3 100644 --- a/rend3/src/renderer/setup.rs +++ b/rend3/src/renderer/setup.rs @@ -63,7 +63,7 @@ pub fn create_renderer( let profiler = Mutex::new( wgpu_profiler::GpuProfiler::new(GpuProfilerSettings { - enable_timer_queries: true, + enable_timer_queries: features.contains(wgpu::Features::TIMESTAMP_QUERY) && !cfg!(target_arch = "wasm32"), enable_debug_groups: true, max_num_pending_frames: 4, }) diff --git a/rend3/src/setup.rs b/rend3/src/setup.rs index cbf76557..074ec577 100644 --- a/rend3/src/setup.rs +++ b/rend3/src/setup.rs @@ -138,11 +138,7 @@ fn check_limit_unlimited + Ord>( ty: LimitType, ) -> Result { if d < r { - Err(RendererInitializationError::LowDeviceLimit { - ty, - device_limit: d.into(), - required_limit: r.into(), - }) + Err(RendererInitializationError::LowDeviceLimit { ty, device_limit: d.into(), required_limit: r.into() }) } else { Ok(d) } @@ -154,11 +150,7 @@ fn check_limit_low + Ord>( ty: LimitType, ) -> Result { if r < d { - Err(RendererInitializationError::LowDeviceLimit { - ty, - device_limit: d.into(), - required_limit: r.into(), - }) + Err(RendererInitializationError::LowDeviceLimit { ty, device_limit: d.into(), required_limit: r.into() }) } else { Ok(d) } @@ -352,13 +344,7 @@ impl PotentialAdapter { profile = RendererProfile::CpuDriven; } - Ok(PotentialAdapter { - inner, - info, - features: features?, - limits: limits?, - profile, - }) + Ok(PotentialAdapter { inner, info, features: features?, limits: limits?, profile }) } } @@ -479,18 +465,10 @@ pub async fn create_iad( let features = adapter.features(); let potential = PotentialAdapter::new(adapter, info, limits, features, desired_profile); - log::info!( - "{:?} Adapter {}: {:#?}", - backend, - idx, - potential.as_ref().map(|p| &p.info) - ); + log::info!("{:?} Adapter {}: {:#?}", backend, idx, potential.as_ref().map(|p| &p.info)); let desired = if let Some(ref desired_device) = desired_device { - potential - .as_ref() - .map(|i| i.info.name.to_lowercase().contains(desired_device)) - .unwrap_or(false) + potential.as_ref().map(|i| i.info.name.to_lowercase().contains(desired_device)).unwrap_or(false) } else { true }; @@ -538,9 +516,7 @@ pub async fn create_iad( .request_device( &DeviceDescriptor { label: None, - required_features: adapter - .features - .union(additional_features.unwrap_or_else(Features::empty)), + required_features: adapter.features.union(additional_features.unwrap_or_else(Features::empty)), required_limits: adapter.limits, }, None, diff --git a/rend3/src/shader.rs b/rend3/src/shader.rs index 829f5016..9c8d51d0 100644 --- a/rend3/src/shader.rs +++ b/rend3/src/shader.rs @@ -5,7 +5,7 @@ use std::{ fmt::Write, }; -use handlebars::{Context, Handlebars, Helper, HelperDef, Output, RenderContext, RenderError}; +use handlebars::{Context, Handlebars, Helper, HelperDef, Output, RenderContext, RenderError, RenderErrorReason}; use parking_lot::Mutex; use rend3_types::{Material, MaterialArray, VertexAttributeId}; use rust_embed::RustEmbed; @@ -33,10 +33,7 @@ impl ShaderVertexBufferConfig { let mut specs = Vec::with_capacity(supported.as_ref().len()); for attribute in supported.into_iter() { - specs.push(VertexBufferSpec { - attribute: *attribute, - optional: !required.as_ref().contains(&attribute), - }); + specs.push(VertexBufferSpec { attribute: *attribute, optional: !required.as_ref().contains(&attribute) }); } Self { specs } @@ -106,25 +103,15 @@ impl ShaderPreProcessor { registry.register_helper("vertex_fetch", Box::new(ShaderVertexBufferHelper::new(config))); } let contents = self.files.get(base).ok_or_else(|| { - RenderError::new(format!( + RenderErrorReason::Other(format!( "Base shader {base} is not registered. All registered shaders: {}", registered_shader_string(&self.files) )) })?; - let vertex_array_counts = if let Some(buffer_config) = buffer_config { - buffer_config.specs.len() - } else { - 0 - }; + let vertex_array_counts = if let Some(buffer_config) = buffer_config { buffer_config.specs.len() } else { 0 }; - registry.render_template( - contents, - &BufferConfigWrapper { - vertex_array_counts, - user_config, - }, - ) + registry.render_template(contents, &BufferConfigWrapper { vertex_array_counts, user_config }) } } @@ -159,7 +146,7 @@ impl<'a> ShaderIncluder<'a> { impl<'a> HelperDef for ShaderIncluder<'a> { fn call<'reg: 'rc, 'rc>( &self, - h: &Helper<'reg, 'rc>, + h: &Helper<'rc>, r: &'reg Handlebars<'reg>, ctx: &'rc Context, _rc: &mut RenderContext<'reg, 'rc>, @@ -167,11 +154,13 @@ impl<'a> HelperDef for ShaderIncluder<'a> { ) -> handlebars::HelperResult { let file_name_value = h .param(0) - .ok_or_else(|| RenderError::new("include helper must have a single argument for the include path"))? + .ok_or_else(|| { + RenderErrorReason::Other("include helper must have a single argument for the include path".to_string()) + })? .value(); let file_name = match file_name_value { handlebars::JsonValue::String(s) => s, - _ => return Err(RenderError::new("include helper's first argument must be a string")), + _ => Err(RenderErrorReason::Other("include helper's first argument must be a string".to_string()))?, }; let mut include_status = self.include_state.try_lock().unwrap(); @@ -182,7 +171,7 @@ impl<'a> HelperDef for ShaderIncluder<'a> { drop(include_status); let contents = self.files.get(file_name).ok_or_else(|| { - RenderError::new(format!( + RenderErrorReason::Other(format!( "Included file \"{file_name}\" is not registered. All registered files: {}", registered_shader_string(self.files) )) @@ -207,7 +196,7 @@ impl<'a> ShaderVertexBufferHelper<'a> { impl<'a> HelperDef for ShaderVertexBufferHelper<'a> { fn call<'reg: 'rc, 'rc>( &self, - h: &Helper<'reg, 'rc>, + h: &Helper<'rc>, r: &'reg Handlebars<'reg>, ctx: &'rc Context, _rc: &mut RenderContext<'reg, 'rc>, @@ -216,35 +205,31 @@ impl<'a> HelperDef for ShaderVertexBufferHelper<'a> { let object_buffer_value = h .param(0) .ok_or_else(|| { - RenderError::new("Vertex buffer helper must have an argument pointing to the buffer of objects") + RenderErrorReason::Other( + "Vertex buffer helper must have an argument pointing to the buffer of objects".to_string(), + ) })? .relative_path(); let object_buffer = match object_buffer_value { Some(s) => s, - _ => { - return Err(RenderError::new( - "Vertex buffer helper's first argument must be a string", - )) - } + _ => Err(RenderErrorReason::Other("Vertex buffer helper's first argument must be a string".to_string()))?, }; let batch_buffer_value = h .param(1) .ok_or_else(|| { - RenderError::new("Vertex buffer helper must have an argument pointing to the buffer of batch data") + RenderErrorReason::Other( + "Vertex buffer helper must have an argument pointing to the buffer of batch data".to_string(), + ) })? .relative_path(); let batch_buffer = match batch_buffer_value { Some(s) => s, - _ => { - return Err(RenderError::new( - "Vertex buffer helper's second argument must be a string", - )) - } + _ => Err(RenderErrorReason::Other("Vertex buffer helper's second argument must be a string".to_string()))?, }; let template = self .generate_template(h, object_buffer, batch_buffer) - .map_err(|_| RenderError::new("Failed to writeln vertex template string"))?; + .map_err(|_| RenderErrorReason::Other("Failed to writeln vertex template string".to_string()))?; out.write(&r.render_template(&template, ctx.data())?)?; @@ -282,20 +267,13 @@ impl<'a> ShaderVertexBufferHelper<'a> { .specs .iter() .enumerate() - .find_map( - |(idx, s)| match s.attribute.name() == requested_attribute.relative_path().unwrap() { - true => Some((idx, s)), - false => None, - }, - ) + .find_map(|(idx, s)| match s.attribute.name() == requested_attribute.relative_path().unwrap() { + true => Some((idx, s)), + false => None, + }) .unwrap(); - writeln!( - input_struct, - " {}: {},", - spec.attribute.name(), - spec.attribute.metadata().shader_type - )?; + writeln!(input_struct, " {}: {},", spec.attribute.name(), spec.attribute.metadata().shader_type)?; writeln!( input_function, @@ -304,11 +282,7 @@ impl<'a> ShaderVertexBufferHelper<'a> { )?; if spec.optional { - writeln!( - input_function, - " if ({}_offset != 0xFFFFFFFFu) {{", - spec.attribute.name() - )?; + writeln!(input_function, " if ({}_offset != 0xFFFFFFFFu) {{", spec.attribute.name())?; writeln!( input_function, @@ -354,10 +328,7 @@ mod tests { let mut pp = ShaderPreProcessor::new(); pp.add_shader("simple", "{{include \"other\"}} simple"); pp.add_shader("other", "other"); - let config = ShaderConfig { - profile: None, - position_attribute_offset: 0, - }; + let config = ShaderConfig { profile: None, position_attribute_offset: 0 }; let output = pp.render_shader("simple", &config, None).unwrap(); assert_eq!(output, "other simple"); @@ -368,10 +339,7 @@ mod tests { let mut pp = ShaderPreProcessor::new(); pp.add_shader("simple", "{{include \"other\"}} simple"); pp.add_shader("other", "{{include \"simple\"}} other"); - let config = ShaderConfig { - profile: None, - position_attribute_offset: 0, - }; + let config = ShaderConfig { profile: None, position_attribute_offset: 0 }; let output = pp.render_shader("simple", &config, None).unwrap(); assert_eq!(output, " other simple"); @@ -381,10 +349,7 @@ mod tests { fn error_include() { let mut pp = ShaderPreProcessor::new(); pp.add_shader("simple", "{{include \"other\"}} simple"); - let config = ShaderConfig { - profile: None, - position_attribute_offset: 0, - }; + let config = ShaderConfig { profile: None, position_attribute_offset: 0 }; let output = pp.render_shader("simple", &config, None); assert!(output.is_err(), "Expected error, got {output:?}"); @@ -394,10 +359,7 @@ mod tests { fn no_arg_include() { let mut pp = ShaderPreProcessor::new(); pp.add_shader("simple", "{{include}} simple"); - let config = ShaderConfig { - profile: None, - position_attribute_offset: 0, - }; + let config = ShaderConfig { profile: None, position_attribute_offset: 0 }; let output = pp.render_shader("simple", &config, None); assert!(output.is_err(), "Expected error, got {output:?}"); diff --git a/rend3/src/util/bind_merge.rs b/rend3/src/util/bind_merge.rs index 97f1fd7f..c23dd88b 100644 --- a/rend3/src/util/bind_merge.rs +++ b/rend3/src/util/bind_merge.rs @@ -14,19 +14,12 @@ pub struct BindGroupLayoutBuilder { } impl BindGroupLayoutBuilder { pub fn new() -> Self { - Self { - bgl_entries: Vec::with_capacity(16), - } + Self { bgl_entries: Vec::with_capacity(16) } } pub fn append(&mut self, visibility: ShaderStages, ty: BindingType, count: Option) -> &mut Self { let binding = self.bgl_entries.len() as u32; - self.bgl_entries.push(BindGroupLayoutEntry { - binding, - visibility, - ty, - count, - }); + self.bgl_entries.push(BindGroupLayoutEntry { binding, visibility, ty, count }); self } @@ -49,10 +42,7 @@ impl BindGroupLayoutBuilder { } pub fn build(&self, device: &Device, label: Option<&str>) -> BindGroupLayout { - device.create_bind_group_layout(&BindGroupLayoutDescriptor { - label, - entries: &self.bgl_entries, - }) + device.create_bind_group_layout(&BindGroupLayoutDescriptor { label, entries: &self.bgl_entries }) } } @@ -68,17 +58,12 @@ pub struct BindGroupBuilder<'a> { } impl<'a> BindGroupBuilder<'a> { pub fn new() -> Self { - Self { - bg_entries: Vec::with_capacity(16), - } + Self { bg_entries: Vec::with_capacity(16) } } pub fn append(&mut self, resource: BindingResource<'a>) -> &mut Self { let index = self.bg_entries.len(); - self.bg_entries.push(BindGroupEntry { - binding: index as u32, - resource, - }); + self.bg_entries.push(BindGroupEntry { binding: index as u32, resource }); self } @@ -88,20 +73,12 @@ impl<'a> BindGroupBuilder<'a> { } pub fn append_buffer_with_size(&mut self, buffer: &'a Buffer, size: u64) -> &mut Self { - self.append(BindingResource::Buffer(BufferBinding { - buffer, - offset: 0, - size: NonZeroU64::new(size), - })); + self.append(BindingResource::Buffer(BufferBinding { buffer, offset: 0, size: NonZeroU64::new(size) })); self } pub fn append_buffer_with_offset_and_size(&mut self, buffer: &'a Buffer, offset: u64, size: u64) -> &mut Self { - self.append(BindingResource::Buffer(BufferBinding { - buffer, - offset, - size: NonZeroU64::new(size), - })); + self.append(BindingResource::Buffer(BufferBinding { buffer, offset, size: NonZeroU64::new(size) })); self } @@ -121,11 +98,7 @@ impl<'a> BindGroupBuilder<'a> { } pub fn build(&self, device: &Device, label: Option<&str>, bgl: &BindGroupLayout) -> BindGroup { - device.create_bind_group(&BindGroupDescriptor { - label, - layout: bgl, - entries: &self.bg_entries, - }) + device.create_bind_group(&BindGroupDescriptor { label, layout: bgl, entries: &self.bg_entries }) } } diff --git a/rend3/src/util/freelist/buffer.rs b/rend3/src/util/freelist/buffer.rs index f9dd0b2e..80d17919 100644 --- a/rend3/src/util/freelist/buffer.rs +++ b/rend3/src/util/freelist/buffer.rs @@ -17,9 +17,8 @@ pub struct FreelistDerivedBuffer { } impl FreelistDerivedBuffer { pub const STARTING_SIZE: usize = 16; - pub const NEEDED_USAGES: BufferUsages = BufferUsages::STORAGE - .union(BufferUsages::COPY_DST) - .union(BufferUsages::COPY_SRC); + pub const NEEDED_USAGES: BufferUsages = + BufferUsages::STORAGE.union(BufferUsages::COPY_DST).union(BufferUsages::COPY_SRC); pub fn new(device: &Device) -> Self where @@ -92,10 +91,7 @@ impl FreelistDerivedBuffer { let data = self.stale.drain(..).map(|idx| { let data = get_value(idx); - ScatterData { - word_offset: u32::try_from((idx as u64 * self.rounded_size) / 4).unwrap(), - data, - } + ScatterData { word_offset: u32::try_from((idx as u64 * self.rounded_size) / 4).unwrap(), data } }); scatter.execute_copy(device, encoder, &self.inner, data); diff --git a/rend3/src/util/freelist/vec.rs b/rend3/src/util/freelist/vec.rs index bf9079a0..48abb88f 100644 --- a/rend3/src/util/freelist/vec.rs +++ b/rend3/src/util/freelist/vec.rs @@ -10,10 +10,7 @@ pub struct FreelistVec { impl FreelistVec { pub fn new() -> Self { - Self { - data: Vec::new(), - freelist: Vec::new(), - } + Self { data: Vec::new(), freelist: Vec::new() } } pub fn push(&mut self, value: T) -> FreelistIndex { diff --git a/rend3/src/util/frustum.rs b/rend3/src/util/frustum.rs index 16b89ecb..44f9ced0 100644 --- a/rend3/src/util/frustum.rs +++ b/rend3/src/util/frustum.rs @@ -16,10 +16,7 @@ impl BoundingSphere { let center = find_mesh_center(mesh); let radius = find_mesh_bounding_sphere_radius(center, mesh); - Self { - center: Vec3::from(center), - radius, - } + Self { center: Vec3::from(center), radius } } pub fn apply_transform(self, matrix: Mat4) -> Self { @@ -27,20 +24,11 @@ impl BoundingSphere { .x_axis .xyz() .length_squared() - .max( - matrix - .y_axis - .xyz() - .length_squared() - .max(matrix.z_axis.xyz().length_squared()), - ) + .max(matrix.y_axis.xyz().length_squared().max(matrix.z_axis.xyz().length_squared())) .sqrt(); let center = matrix * self.center.extend(1.0); - Self { - center: center.truncate(), - radius: max_scale * self.radius, - } + Self { center: center.truncate(), radius: max_scale * self.radius } } } @@ -64,9 +52,7 @@ fn find_mesh_center(mesh: &[Vec3]) -> Vec3A { } fn find_mesh_bounding_sphere_radius(mesh_center: Vec3A, mesh: &[Vec3]) -> f32 { - mesh.iter().fold(0.0, |distance, pos| { - distance.max((Vec3A::from(*pos) - mesh_center).length()) - }) + mesh.iter().fold(0.0, |distance, pos| distance.max((Vec3A::from(*pos) - mesh_center).length())) } /// Represents a plane as a vec4 (or vec3 + f32) @@ -78,10 +64,7 @@ pub struct Plane { impl Plane { pub fn new(a: f32, b: f32, c: f32, d: f32) -> Self { - Self { - abc: Vec3::new(a, b, c), - d, - } + Self { abc: Vec3::new(a, b, c), d } } pub fn normalize(mut self) -> Self { diff --git a/rend3/src/util/mipmap.rs b/rend3/src/util/mipmap.rs index 47fb4dec..78ea5cc0 100644 --- a/rend3/src/util/mipmap.rs +++ b/rend3/src/util/mipmap.rs @@ -101,13 +101,7 @@ impl MipmapGenerator { .map(|&format| (format, Self::build_blit_pipeline(device, format, &pll, &sm))) .collect(); - Self { - texture_bgl, - sampler_bg, - sm, - pll, - pipelines: RwLock::new(pipelines), - } + Self { texture_bgl, sampler_bg, sm, pll, pipelines: RwLock::new(pipelines) } } fn build_blit_pipeline( @@ -121,11 +115,7 @@ impl MipmapGenerator { device.create_render_pipeline(&RenderPipelineDescriptor { label: Some(&label), layout: Some(pll), - vertex: VertexState { - module: sm, - entry_point: "vs_main", - buffers: &[], - }, + vertex: VertexState { module: sm, entry_point: "vs_main", buffers: &[] }, primitive: PrimitiveState { topology: PrimitiveTopology::TriangleList, strip_index_format: None, @@ -140,11 +130,7 @@ impl MipmapGenerator { fragment: Some(FragmentState { module: sm, entry_point: "fs_main", - targets: &[Some(ColorTargetState { - format, - blend: None, - write_mask: ColorWrites::all(), - })], + targets: &[Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::all() })], }), multiview: None, }) @@ -167,9 +153,7 @@ impl MipmapGenerator { mip_level_count: Some(1), ..Default::default() }); - scope - .end() - .map_err(|source| MipmapGenerationError::TextureViewCreationFailed { mip_level, source })?; + scope.end().map_err(|source| MipmapGenerationError::TextureViewCreationFailed { mip_level, source })?; Ok(view) }) @@ -182,10 +166,9 @@ impl MipmapGenerator { None => { drop(read_pipelines); - self.pipelines.write().insert( - desc.format, - Self::build_blit_pipeline(device, desc.format, &self.pll, &self.sm), - ); + self.pipelines + .write() + .insert(desc.format, Self::build_blit_pipeline(device, desc.format, &self.pll, &self.sm)); read_pipelines = self.pipelines.read(); @@ -215,10 +198,7 @@ impl MipmapGenerator { color_attachments: &[Some(RenderPassColorAttachment { view: dst_view, resolve_target: None, - ops: Operations { - load: LoadOp::Clear(Color::BLACK), - store: StoreOp::Store, - }, + ops: Operations { load: LoadOp::Clear(Color::BLACK), store: StoreOp::Store }, })], depth_stencil_attachment: None, timestamp_writes: None, diff --git a/rend3/src/util/output.rs b/rend3/src/util/output.rs index aa317bf9..3a942c64 100644 --- a/rend3/src/util/output.rs +++ b/rend3/src/util/output.rs @@ -7,10 +7,7 @@ use wgpu::{SurfaceTexture, TextureView}; /// Anything that resembles a surface to render to. pub enum OutputFrame { // Pre-acquired surface. rend3 will present it. - SurfaceAcquired { - view: TextureView, - surface_tex: SurfaceTexture, - }, + SurfaceAcquired { view: TextureView, surface_tex: SurfaceTexture }, // Arbitrary texture view. View(Arc), } @@ -26,10 +23,7 @@ impl OutputFrame { /// Present the surface, if needed. pub fn present(self) { - if let Self::SurfaceAcquired { - surface_tex: surface, .. - } = self - { + if let Self::SurfaceAcquired { surface_tex: surface, .. } = self { surface.present(); } } diff --git a/rend3/src/util/scatter_copy.rs b/rend3/src/util/scatter_copy.rs index 26c0d693..60a10ebf 100644 --- a/rend3/src/util/scatter_copy.rs +++ b/rend3/src/util/scatter_copy.rs @@ -17,10 +17,7 @@ pub struct ScatterData { } impl ScatterData { pub fn new(byte_offset: u32, data: T) -> Self { - Self { - word_offset: byte_offset / 4, - data, - } + Self { word_offset: byte_offset / 4, data } } } @@ -123,15 +120,14 @@ impl ScatterCopy { drop(mapped_range); source_buffer.unmap(); - let bg = BindGroupBuilder::new() - .append_buffer(&source_buffer) - .append_buffer(destination_buffer) - .build(device, Some("ScatterCopy temporary bind group"), &self.bgl); + let bg = BindGroupBuilder::new().append_buffer(&source_buffer).append_buffer(destination_buffer).build( + device, + Some("ScatterCopy temporary bind group"), + &self.bgl, + ); - let mut cpass = encoder.begin_compute_pass(&ComputePassDescriptor { - label: Some("ScatterCopy cpass"), - timestamp_writes: None, - }); + let mut cpass = encoder + .begin_compute_pass(&ComputePassDescriptor { label: Some("ScatterCopy cpass"), timestamp_writes: None }); cpass.set_pipeline(&self.pipeline); cpass.set_bind_group(0, &bg, &[]); cpass.dispatch_workgroups(div_round_up(count_u32, 64), 1, 1); @@ -153,10 +149,8 @@ mod test { impl TestContext { fn new() -> Option { let backends = wgpu::util::backend_bits_from_env().unwrap_or(wgpu::Backends::all()); - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { - backends, - ..wgpu::InstanceDescriptor::default() - }); + let instance = + wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::default() }); let adapter = pollster::block_on(wgpu::util::initialize_adapter_from_env_or_default(&instance, None))?; let (device, queue) = pollster::block_on(adapter.request_device( &wgpu::DeviceDescriptor { @@ -180,8 +174,7 @@ mod test { } fn encoder(&self) -> wgpu::CommandEncoder { - self.device - .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }) + self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None }) } fn readback( @@ -222,15 +215,7 @@ mod test { let mut encoder = ctx.encoder(); - scatter.execute_copy( - &ctx.device, - &mut encoder, - &buffer, - [ScatterData { - word_offset: 0, - data: 1.0_f32, - }], - ); + scatter.execute_copy(&ctx.device, &mut encoder, &buffer, [ScatterData { word_offset: 0, data: 1.0_f32 }]); assert_eq!(&ctx.readback::(encoder, &buffer, 16), &[1.0, 5.0, 5.0, 5.0]); } @@ -251,16 +236,7 @@ mod test { &ctx.device, &mut encoder, &buffer, - [ - ScatterData { - word_offset: 0, - data: 1.0_f32, - }, - ScatterData { - word_offset: 2, - data: 3.0_f32, - }, - ], + [ScatterData { word_offset: 0, data: 1.0_f32 }, ScatterData { word_offset: 2, data: 3.0_f32 }], ); assert_eq!(&ctx.readback::(encoder, &buffer, 16), &[1.0, 5.0, 3.0, 5.0]); @@ -283,20 +259,11 @@ mod test { &mut encoder, &buffer, [ - ScatterData { - word_offset: 0, - data: [1.0_f32, 2.0_f32], - }, - ScatterData { - word_offset: 4, - data: [5.0_f32, 6.0_f32], - }, + ScatterData { word_offset: 0, data: [1.0_f32, 2.0_f32] }, + ScatterData { word_offset: 4, data: [5.0_f32, 6.0_f32] }, ], ); - assert_eq!( - &ctx.readback::<[f32; 2]>(encoder, &buffer, 32), - &[[1.0, 2.0], [9.0, 9.0], [5.0, 6.0], [9.0, 9.0]] - ); + assert_eq!(&ctx.readback::<[f32; 2]>(encoder, &buffer, 32), &[[1.0, 2.0], [9.0, 9.0], [5.0, 6.0], [9.0, 9.0]]); } } diff --git a/rend3/src/util/sync.rs b/rend3/src/util/sync.rs index c0fea0d0..d13ba595 100644 --- a/rend3/src/util/sync.rs +++ b/rend3/src/util/sync.rs @@ -10,10 +10,7 @@ pub struct WaitGroup { impl WaitGroup { pub fn new() -> Arc { - Arc::new(Self { - counter: Mutex::new(0), - condvar: Condvar::new(), - }) + Arc::new(Self { counter: Mutex::new(0), condvar: Condvar::new() }) } pub fn increment(self: &Arc) -> DecrementGuard { diff --git a/rend3/src/util/upload.rs b/rend3/src/util/upload.rs index 4fd413f1..ef3298c1 100644 --- a/rend3/src/util/upload.rs +++ b/rend3/src/util/upload.rs @@ -16,19 +16,11 @@ pub struct UploadChainer<'a> { impl<'a> UploadChainer<'a> { pub fn new() -> Self { - Self { - staging_buffer: None, - uploads: Vec::new(), - total_size: 0, - } + Self { staging_buffer: None, uploads: Vec::new(), total_size: 0 } } pub fn add(&mut self, offset: u64, data: &'a [u8]) { - self.uploads.push(Upload { - staging_offset: self.total_size, - offset, - data, - }); + self.uploads.push(Upload { staging_offset: self.total_size, offset, data }); self.total_size += data.len() as u64; }