1
0
Fork 0

[RENDERER] Begin refactor

This commit is contained in:
Florian RICHER 2022-07-25 14:00:36 +02:00
parent df92b1b884
commit dc063f74a1
9 changed files with 65 additions and 54 deletions

9
Cargo.lock generated
View file

@ -1688,6 +1688,14 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "render"
version = "0.1.0"
dependencies = [
"wgpu",
"winit",
]
[[package]] [[package]]
name = "renderdoc-sys" name = "renderdoc-sys"
version = "0.7.1" version = "0.7.1"
@ -2061,6 +2069,7 @@ dependencies = [
"log", "log",
"pollster", "pollster",
"rayon", "rayon",
"render",
"reqwest", "reqwest",
"tobj", "tobj",
"wasm-bindgen", "wasm-bindgen",

View file

@ -8,6 +8,8 @@ edition = "2021"
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
render = { path = "crates/render" }
cfg-if = "1" cfg-if = "1"
anyhow = "1.0" anyhow = "1.0"
bytemuck = { version = "1.9.1", features = [ "derive" ] } bytemuck = { version = "1.9.1", features = [ "derive" ] }

13
crates/render/Cargo.toml Normal file
View file

@ -0,0 +1,13 @@
[package]
name = "render"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
winit = "0.26"
wgpu = { version = "0.13"}

View file

@ -1,20 +1,18 @@
use std::iter; use std::iter;
use winit::{event::Event, window::Window}; use wgpu::{CommandEncoder, TextureView};
use winit::window::Window;
use super::State; pub struct GraphicsRenderer {
pub struct Renderer {
pub surface: wgpu::Surface, pub surface: wgpu::Surface,
pub device: wgpu::Device, pub device: wgpu::Device,
pub queue: wgpu::Queue, pub queue: wgpu::Queue,
pub size: winit::dpi::PhysicalSize<u32>, pub size: winit::dpi::PhysicalSize<u32>,
pub config: wgpu::SurfaceConfiguration, pub config: wgpu::SurfaceConfiguration,
state: Option<Box<dyn State>>,
} }
impl Renderer { impl GraphicsRenderer {
pub async fn new(window: &Window) -> Self { pub async fn initialize(window: &Window) -> Self {
let size = window.inner_size(); let size = window.inner_size();
// The instance is a handle to our GPU // The instance is a handle to our GPU
@ -63,7 +61,6 @@ impl Renderer {
queue, queue,
config, config,
size, size,
state: None,
} }
} }
@ -73,27 +70,13 @@ impl Renderer {
self.config.width = new_size.width; self.config.width = new_size.width;
self.config.height = new_size.height; self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config); self.surface.configure(&self.device, &self.config);
if let Some(state) = self.state.as_mut() {
state.resize(&self.device, &self.config, new_size);
}
} }
} }
pub fn input(&mut self, event: &Event<()>) -> bool { pub fn render_frame<T>(&mut self, render: T) -> Result<(), wgpu::SurfaceError>
if let Some(state) = self.state.as_mut() { where
return state.input(event); T: Fn(&TextureView, &mut CommandEncoder) -> Result<(), wgpu::SurfaceError>,
} {
false
}
pub fn update(&mut self, dt: instant::Duration) {
if let Some(state) = self.state.as_mut() {
state.update(&self.queue, dt);
}
}
pub fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
let output = self.surface.get_current_texture()?; let output = self.surface.get_current_texture()?;
let view = output let view = output
.texture .texture
@ -105,16 +88,10 @@ impl Renderer {
label: Some("Render Encoder"), label: Some("Render Encoder"),
}); });
if let Some(state) = self.state.as_mut() { render(&view, &mut encoder)?;
state.render(&view, &mut encoder)?; self.queue.submit(iter::once(encoder.finish()));
self.queue.submit(iter::once(encoder.finish())); output.present();
output.present();
}
Ok(()) Ok(())
} }
pub fn set_state(&mut self, state: Option<Box<dyn State>>) {
self.state = state;
}
} }

10
crates/render/src/lib.rs Normal file
View file

@ -0,0 +1,10 @@
pub mod graphics_renderer;
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
let result = 2 + 2;
assert_eq!(result, 4);
}
}

View file

@ -1,6 +1,7 @@
use std::{ops::Deref, sync::Arc}; use std::{ops::Deref, sync::Arc};
use cgmath::prelude::*; use cgmath::prelude::*;
use ::render::graphics_renderer::GraphicsRenderer;
use winit::{ use winit::{
event::*, event::*,
event_loop::{ControlFlow, EventLoop}, event_loop::{ControlFlow, EventLoop},
@ -9,7 +10,7 @@ use winit::{
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*; use wasm_bindgen::prelude::*;
use crate::render::{DefaultState, Renderer}; use crate::render::{DefaultState, State};
mod camera; mod camera;
mod model; mod model;
@ -156,22 +157,21 @@ pub async fn run() {
.expect("Couldn't append canvas to document body."); .expect("Couldn't append canvas to document body.");
} }
let mut renderer = Arc::from(Renderer::new(&window).await); let mut renderer = Arc::from(GraphicsRenderer::initialize(&window).await);
let default_state = Box::from(DefaultState::new(renderer.deref()).await); let mut default_state = Arc::from(DefaultState::new(renderer.deref()).await);
Arc::get_mut(&mut renderer)
.unwrap()
.set_state(Some(default_state));
let mut last_render_time = instant::Instant::now(); let mut last_render_time = instant::Instant::now();
event_loop.run(move |base_event, _, control_flow| { event_loop.run(move |base_event, _, control_flow| {
*control_flow = ControlFlow::Poll; *control_flow = ControlFlow::Poll;
let renderer = Arc::get_mut(&mut renderer).unwrap(); let renderer = Arc::get_mut(&mut renderer).unwrap();
let state = Arc::get_mut(&mut default_state).unwrap();
match base_event { match base_event {
Event::MainEventsCleared => window.request_redraw(), Event::MainEventsCleared => window.request_redraw(),
Event::WindowEvent { Event::WindowEvent {
ref event, ref event,
window_id, window_id,
} if window_id == window.id() && !renderer.input(&base_event) => match event { } if window_id == window.id() && !state.input(&base_event) => match event {
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
WindowEvent::CloseRequested WindowEvent::CloseRequested
| WindowEvent::KeyboardInput { | WindowEvent::KeyboardInput {
@ -190,15 +190,20 @@ pub async fn run() {
renderer.resize(**new_inner_size); renderer.resize(**new_inner_size);
} }
_ => { _ => {
renderer.input(&base_event); state.input(&base_event);
} }
}, },
Event::RedrawRequested(window_id) if window_id == window.id() => { Event::RedrawRequested(window_id) if window_id == window.id() => {
let now = instant::Instant::now(); let now = instant::Instant::now();
let dt = now - last_render_time; let dt = now - last_render_time;
last_render_time = now; last_render_time = now;
renderer.update(dt); state.update(&renderer.queue, dt);
match renderer.render() {
match renderer.render_frame(|view, command| {
let mut renderable = Arc::clone(&default_state);
let state = Arc::get_mut(&mut renderable).unwrap();
state.render(view, command)
}) {
Ok(_) => {} Ok(_) => {}
Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => { Err(wgpu::SurfaceError::Lost | wgpu::SurfaceError::Outdated) => {
renderer.resize(renderer.size) renderer.resize(renderer.size)
@ -208,7 +213,7 @@ pub async fn run() {
} }
} }
_ => { _ => {
renderer.input(&base_event); state.input(&base_event);
} }
} }
}); });

View file

@ -4,4 +4,4 @@ pub use pipelines::utils::create_render_pipeline;
pub use pipelines::{GlobalBindLayout, Pipelines}; pub use pipelines::{GlobalBindLayout, Pipelines};
mod renderer; mod renderer;
pub use renderer::{DefaultState, Renderer, State}; pub use renderer::{DefaultState, State};

View file

@ -2,6 +2,7 @@ use cgmath::prelude::*;
#[cfg(not(target_arch="wasm32"))] #[cfg(not(target_arch="wasm32"))]
use rayon::prelude::*; use rayon::prelude::*;
use ::render::graphics_renderer::GraphicsRenderer;
use wgpu::{util::DeviceExt, Queue}; use wgpu::{util::DeviceExt, Queue};
use winit::event::{DeviceEvent, ElementState, Event, KeyboardInput, MouseButton, WindowEvent}; use winit::event::{DeviceEvent, ElementState, Event, KeyboardInput, MouseButton, WindowEvent};
@ -11,8 +12,6 @@ use crate::{
render, resources, texture, CameraUniform, Instance, LightUniform, NUM_INSTANCES_PER_ROW, render, resources, texture, CameraUniform, Instance, LightUniform, NUM_INSTANCES_PER_ROW,
}; };
use super::Renderer;
pub struct DefaultState { pub struct DefaultState {
obj_model: model::Model, obj_model: model::Model,
camera: camera::Camera, camera: camera::Camera,
@ -35,7 +34,7 @@ pub struct DefaultState {
} }
impl DefaultState { impl DefaultState {
pub async fn new(renderer: &Renderer) -> Self pub async fn new(renderer: &GraphicsRenderer) -> Self
{ {
let global_bind_layout = render::GlobalBindLayout::new(&renderer.device); let global_bind_layout = render::GlobalBindLayout::new(&renderer.device);
let pipelines = let pipelines =

View file

@ -1,7 +1,3 @@
mod renderer;
pub use renderer::Renderer;
mod default_state; mod default_state;
pub use default_state::DefaultState; pub use default_state::DefaultState;