ECS'ing it up, lost rendering though, bummer
This commit is contained in:
@@ -68,7 +68,7 @@ pub fn import_mesh(mesh_path: &str) -> (Vec<Vertex>, Vec<u32>) {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println!("{:?}\n\n\n\n\n {:?}", vertex_data, index_data);
|
//println!("{:?}\n\n\n\n\n {:?}", vertex_data, index_data);
|
||||||
(vertex_data.to_vec(), index_data.to_vec())
|
(vertex_data.to_vec(), index_data.to_vec())
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
213
src/main.rs
213
src/main.rs
@@ -19,6 +19,7 @@ use std::rc::Rc;
|
|||||||
use wgpu::Buffer;
|
use wgpu::Buffer;
|
||||||
use winit::platform::unix::x11::ffi::Time;
|
use winit::platform::unix::x11::ffi::Time;
|
||||||
use legion::*;
|
use legion::*;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
mod framework;
|
mod framework;
|
||||||
mod geometry;
|
mod geometry;
|
||||||
@@ -118,8 +119,8 @@ struct DirectionalLight {
|
|||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
struct Mesh {
|
struct Mesh {
|
||||||
index_buffer: Rc<Buffer>,
|
index_buffer: Arc<Buffer>,
|
||||||
vertex_buffer: Rc<Buffer>,
|
vertex_buffer: Arc<Buffer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
@@ -138,31 +139,6 @@ fn main() {
|
|||||||
use legion::*;
|
use legion::*;
|
||||||
let mut world = World::default();
|
let mut world = World::default();
|
||||||
|
|
||||||
// This could be used for relationships between entities...???
|
|
||||||
let entity: Entity = world.push((
|
|
||||||
cgmath::Point3 {
|
|
||||||
x: -5.0,
|
|
||||||
y: 7.0,
|
|
||||||
z: 10.0,
|
|
||||||
},
|
|
||||||
DirectionalLight {
|
|
||||||
color: wgpu::Color {
|
|
||||||
r: 1.0,
|
|
||||||
g: 0.5,
|
|
||||||
b: 0.5,
|
|
||||||
a: 1.0,
|
|
||||||
},
|
|
||||||
fov: 45.0,
|
|
||||||
depth: RangeCopy { start: 1.0, end: 20.0 },
|
|
||||||
}
|
|
||||||
));
|
|
||||||
|
|
||||||
let entities: &[Entity] = world.extend(vec![
|
|
||||||
(Position { x: 0.0, y: 0.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
|
||||||
(Position { x: 1.0, y: 1.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
|
||||||
(Position { x: 2.0, y: 2.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
|
||||||
]);
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Querying entities by their handle
|
Querying entities by their handle
|
||||||
|
|
||||||
@@ -180,8 +156,14 @@ fn main() {
|
|||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// construct a schedule (you should do this on init)
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
let mut schedule = Schedule::builder()
|
let (mut pool, spawner) = {
|
||||||
|
let local_pool = futures::executor::LocalPool::new();
|
||||||
|
let spawner = local_pool.spawner();
|
||||||
|
(local_pool, spawner)
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut render_schedule = Schedule::builder()
|
||||||
.add_system(render::render_test_system())
|
.add_system(render::render_test_system())
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
@@ -193,7 +175,7 @@ fn main() {
|
|||||||
|
|
||||||
// you can then iterate through the components found in the world
|
// you can then iterate through the components found in the world
|
||||||
for position in query.iter(&world) {
|
for position in query.iter(&world) {
|
||||||
println!("{:?}", position);
|
//println!("{:?}", position);
|
||||||
}
|
}
|
||||||
|
|
||||||
let event_loop = EventLoop::new();
|
let event_loop = EventLoop::new();
|
||||||
@@ -207,109 +189,10 @@ fn main() {
|
|||||||
builder = builder.with_no_redirection_bitmap(true);
|
builder = builder.with_no_redirection_bitmap(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// I think right here is where I can start pulling everything into the renderer
|
||||||
|
|
||||||
let window = builder.build(&event_loop).unwrap();
|
let window = builder.build(&event_loop).unwrap();
|
||||||
|
|
||||||
log::info!("Initializing the surface...");
|
|
||||||
|
|
||||||
// Grab the GPU instance, and query its features
|
|
||||||
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
|
|
||||||
let (size, surface) = unsafe {
|
|
||||||
let size = window.inner_size();
|
|
||||||
let surface = instance.create_surface(&window);
|
|
||||||
(size, surface)
|
|
||||||
};
|
|
||||||
let adapter =
|
|
||||||
instance
|
|
||||||
.request_adapter(&wgpu::RequestAdapterOptions {
|
|
||||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
|
||||||
compatible_surface: Some(&surface),
|
|
||||||
});
|
|
||||||
|
|
||||||
let adapter = futures::executor::block_on(adapter).unwrap();
|
|
||||||
|
|
||||||
let optional_features = Renderer::optional_features();
|
|
||||||
let required_features = Renderer::required_features();
|
|
||||||
let adapter_features = adapter.features();
|
|
||||||
// assert!(
|
|
||||||
// adapter_features.contains(required_features),
|
|
||||||
// "Adapter does not support required features for this example: {:?}",
|
|
||||||
// required_features - adapter_features
|
|
||||||
// );
|
|
||||||
|
|
||||||
let needed_limits = wgpu::Limits::default();//Renderer::required_limits();
|
|
||||||
|
|
||||||
// Maybe for debug tracing???
|
|
||||||
let trace_dir = std::env::var("WGPU_TRACE");
|
|
||||||
|
|
||||||
// And then get the device we want
|
|
||||||
let device = adapter
|
|
||||||
.request_device(
|
|
||||||
&wgpu::DeviceDescriptor {
|
|
||||||
features: (optional_features & adapter_features) | required_features,
|
|
||||||
limits: needed_limits,
|
|
||||||
shader_validation: true,
|
|
||||||
},
|
|
||||||
trace_dir.ok().as_ref().map(std::path::Path::new),
|
|
||||||
);
|
|
||||||
|
|
||||||
let (device, queue) = futures::executor::block_on(device).unwrap();
|
|
||||||
|
|
||||||
let device = Rc::new(device);
|
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
|
||||||
let (mut pool, spawner) = {
|
|
||||||
let local_pool = futures::executor::LocalPool::new();
|
|
||||||
let spawner = local_pool.spawner();
|
|
||||||
(local_pool, spawner)
|
|
||||||
};
|
|
||||||
|
|
||||||
// This is some gross-ass web shit
|
|
||||||
/*#[cfg(target_arch = "wasm32")]
|
|
||||||
let spawner = {
|
|
||||||
use futures::{future::LocalFutureObj, task::SpawnError};
|
|
||||||
use winit::platform::web::WindowExtWebSys;
|
|
||||||
|
|
||||||
struct WebSpawner {}
|
|
||||||
impl LocalSpawn for WebSpawner {
|
|
||||||
fn spawn_local_obj(
|
|
||||||
&self,
|
|
||||||
future: LocalFutureObj<'static, ()>,
|
|
||||||
) -> Result<(), SpawnError> {
|
|
||||||
Ok(wasm_bindgen_futures::spawn_local(future))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
|
||||||
|
|
||||||
// On wasm, append the canvas to the document body
|
|
||||||
web_sys::window()
|
|
||||||
.and_then(|win| win.document())
|
|
||||||
.and_then(|doc| doc.body())
|
|
||||||
.and_then(|body| {
|
|
||||||
body.append_child(&web_sys::Element::from(window.canvas()))
|
|
||||||
.ok()
|
|
||||||
})
|
|
||||||
.expect("couldn't append canvas to document body");
|
|
||||||
|
|
||||||
WebSpawner {}
|
|
||||||
};*/
|
|
||||||
|
|
||||||
|
|
||||||
let mut sc_desc = wgpu::SwapChainDescriptor {
|
|
||||||
// Allows a texture to be a output attachment of a renderpass.
|
|
||||||
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
|
|
||||||
format: if cfg!(target_arch = "wasm32") {
|
|
||||||
wgpu::TextureFormat::Bgra8Unorm
|
|
||||||
} else {
|
|
||||||
wgpu::TextureFormat::Bgra8UnormSrgb
|
|
||||||
},
|
|
||||||
width: size.width,
|
|
||||||
height: size.height,
|
|
||||||
// The presentation engine waits for the next vertical blanking period to update
|
|
||||||
present_mode: wgpu::PresentMode::Mailbox,
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
|
|
||||||
log::info!("Done doing the loading part...");
|
|
||||||
|
|
||||||
// Not sure why this is guarded, maybe we don't handle the event loop timing?
|
// Not sure why this is guarded, maybe we don't handle the event loop timing?
|
||||||
#[cfg(not(target_arch = "wasm32"))]
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
@@ -318,12 +201,49 @@ fn main() {
|
|||||||
log::info!("Entering render loop...");
|
log::info!("Entering render loop...");
|
||||||
|
|
||||||
// Load up the renderer (and the resources)
|
// Load up the renderer (and the resources)
|
||||||
let mut renderer = render::Renderer::init(device.clone(), &sc_desc);
|
let mut renderer = render::Renderer::init(window);
|
||||||
|
|
||||||
let (plane_vertex_buffer, plane_index_buffer) = Renderer::load_mesh_to_buffer(device.clone(), "./resources/untitled.obj");
|
let (plane_vertex_buffer, plane_index_buffer) = renderer.load_mesh_to_buffer("./resources/untitled.obj");
|
||||||
|
|
||||||
|
// This could be used for relationships between entities...???
|
||||||
|
let light_entity: Entity = world.push((
|
||||||
|
cgmath::Point3 {
|
||||||
|
x: -5.0,
|
||||||
|
y: 7.0,
|
||||||
|
z: 10.0,
|
||||||
|
},
|
||||||
|
DirectionalLight {
|
||||||
|
color: wgpu::Color {
|
||||||
|
r: 1.0,
|
||||||
|
g: 0.5,
|
||||||
|
b: 0.5,
|
||||||
|
a: 1.0,
|
||||||
|
},
|
||||||
|
fov: 45.0,
|
||||||
|
depth: RangeCopy { start: 1.0, end: 20.0 },
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let mesh_entity: Entity = world.push((
|
||||||
|
cgmath::Point3 {
|
||||||
|
x: -5.0,
|
||||||
|
y: 7.0,
|
||||||
|
z: 10.0,
|
||||||
|
},
|
||||||
|
Mesh {
|
||||||
|
index_buffer: plane_index_buffer,
|
||||||
|
vertex_buffer: plane_vertex_buffer,
|
||||||
|
}
|
||||||
|
));
|
||||||
|
|
||||||
|
let entities: &[Entity] = world.extend(vec![
|
||||||
|
(Position { x: 0.0, y: 0.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
||||||
|
(Position { x: 1.0, y: 1.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
||||||
|
(Position { x: 2.0, y: 2.0 }, Velocity { dx: 0.0, dy: 0.0 }),
|
||||||
|
]);
|
||||||
|
|
||||||
// Init, this wants the references to the buffers...
|
// Init, this wants the references to the buffers...
|
||||||
let mut runtime = runtime::Runtime::init(&sc_desc, &device, &queue);
|
let mut runtime = runtime::Runtime::init();
|
||||||
|
|
||||||
let mut resources = Resources::default();
|
let mut resources = Resources::default();
|
||||||
resources.insert(runtime);
|
resources.insert(runtime);
|
||||||
@@ -331,7 +251,7 @@ fn main() {
|
|||||||
|
|
||||||
// This is just an winit event loop
|
// This is just an winit event loop
|
||||||
event_loop.run(move |event, _, control_flow| {
|
event_loop.run(move |event, _, control_flow| {
|
||||||
let _ = (&instance, &adapter); // force ownership by the closure (wtf??)
|
//let _ = (&instance, &adapter); // force ownership by the closure (wtf??)
|
||||||
|
|
||||||
// Override the control flow behaviour based on our system
|
// Override the control flow behaviour based on our system
|
||||||
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
*control_flow = if cfg!(feature = "metal-auto-capture") {
|
||||||
@@ -355,8 +275,8 @@ fn main() {
|
|||||||
{
|
{
|
||||||
// ask for a redraw every 20 millis
|
// ask for a redraw every 20 millis
|
||||||
if last_update_inst.elapsed() > Duration::from_millis(20) {
|
if last_update_inst.elapsed() > Duration::from_millis(20) {
|
||||||
schedule.execute(&mut world, &mut resources);
|
render_schedule.execute(&mut world, &mut resources);
|
||||||
window.request_redraw();
|
//window.request_redraw();
|
||||||
last_update_inst = Instant::now();
|
last_update_inst = Instant::now();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -373,12 +293,12 @@ fn main() {
|
|||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
log::info!("Resizing to {:?}", size);
|
log::info!("Resizing to {:?}", size);
|
||||||
sc_desc.width = size.width;
|
let width = size.width;
|
||||||
sc_desc.height = size.height;
|
let height = size.height;
|
||||||
|
|
||||||
resources.get_mut::<Renderer>().unwrap().resize(&sc_desc, &device, &queue);
|
resources.get_mut::<Renderer>().unwrap().resize(width, height);
|
||||||
|
|
||||||
swap_chain = device.create_swap_chain(&surface, &sc_desc);
|
//swap_chain = device.create_swap_chain(&surface, &sc_desc);
|
||||||
}
|
}
|
||||||
event::Event::WindowEvent { event, .. } => match event {
|
event::Event::WindowEvent { event, .. } => match event {
|
||||||
WindowEvent::KeyboardInput {
|
WindowEvent::KeyboardInput {
|
||||||
@@ -398,17 +318,8 @@ fn main() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
event::Event::RedrawRequested(_) => {
|
event::Event::RedrawRequested(_) => {
|
||||||
let frame = match swap_chain.get_current_frame() {
|
|
||||||
Ok(frame) => frame,
|
|
||||||
Err(_) => {
|
|
||||||
swap_chain = device.create_swap_chain(&surface, &sc_desc);
|
|
||||||
swap_chain
|
|
||||||
.get_current_frame()
|
|
||||||
.expect("Failed to acquire next swap chain texture!")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
resources.get_mut::<Renderer>().unwrap().render(&frame.output, &device, &queue, &spawner);
|
//resources.get_mut::<Renderer>().unwrap().render();
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
360
src/render.rs
360
src/render.rs
@@ -1,14 +1,19 @@
|
|||||||
use bytemuck::{Pod, Zeroable};
|
use std::sync::Arc;
|
||||||
use bytemuck::__core::mem;
|
|
||||||
use wgpu::util::DeviceExt;
|
|
||||||
use std::{iter, num::NonZeroU32, ops::Range, rc::Rc};
|
use std::{iter, num::NonZeroU32, ops::Range, rc::Rc};
|
||||||
use crate::{OPENGL_TO_WGPU_MATRIX, Velocity};
|
|
||||||
use crate::light::LightRaw;
|
use bytemuck::__core::mem;
|
||||||
use crate::geometry::{Vertex, import_mesh, create_plane};
|
use bytemuck::{Pod, Zeroable};
|
||||||
use wgpu::{Buffer, Device};
|
|
||||||
use winit::dpi::Position;
|
|
||||||
use winit::platform::unix::x11::ffi::Time;
|
|
||||||
use legion::*;
|
use legion::*;
|
||||||
|
use wgpu::util::DeviceExt;
|
||||||
|
use wgpu::{Buffer, Device, SwapChain, Queue, SwapChainFrame, Surface, SwapChainDescriptor, Instance};
|
||||||
|
use winit::dpi::{Position, PhysicalSize};
|
||||||
|
use winit::platform::unix::x11::ffi::Time;
|
||||||
|
use winit::window::Window;
|
||||||
|
|
||||||
|
use crate::geometry::{create_plane, import_mesh, Vertex};
|
||||||
|
use crate::light::LightRaw;
|
||||||
|
use crate::{Velocity, OPENGL_TO_WGPU_MATRIX};
|
||||||
|
use futures::executor::LocalPool;
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
@@ -44,7 +49,16 @@ pub struct Pass {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub struct Renderer {
|
pub struct Renderer {
|
||||||
device: Rc<Device>,
|
window: Window,
|
||||||
|
swapchain: SwapChain,
|
||||||
|
swapchain_description: Arc<SwapChainDescriptor>,
|
||||||
|
instance: Arc<Instance>,
|
||||||
|
device: Arc<Device>,
|
||||||
|
queue: Arc<Queue>,
|
||||||
|
|
||||||
|
size: PhysicalSize<u32>,
|
||||||
|
surface: Arc<Surface>,
|
||||||
|
|
||||||
lights_are_dirty: bool,
|
lights_are_dirty: bool,
|
||||||
shadow_pass: Pass,
|
shadow_pass: Pass,
|
||||||
forward_pass: Pass,
|
forward_pass: Pass,
|
||||||
@@ -79,38 +93,178 @@ impl Renderer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[system(for_each)]
|
#[system(for_each)]
|
||||||
pub fn render_test(pos: &mut Position, vel: &Velocity) {
|
pub fn render_test(pos: &mut Position, vel: &Velocity, #[resource] renderer: &mut Renderer) {
|
||||||
|
|
||||||
|
let frame = renderer.get_current_frame();
|
||||||
//pos.x += vel.dx * time.elapsed_seconds;
|
//pos.x += vel.dx * time.elapsed_seconds;
|
||||||
//pos.y += vel.dy * time.elapsed_seconds;
|
//pos.y += vel.dy * time.elapsed_seconds;
|
||||||
|
|
||||||
|
// frame: &wgpu::SwapChainTexture,
|
||||||
|
// device: &wgpu::Device,
|
||||||
|
// queue: &wgpu::Queue,
|
||||||
|
// _spawner: &impl futures::task::LocalSpawn,
|
||||||
|
// )
|
||||||
|
// {
|
||||||
|
// update uniforms
|
||||||
|
// for entity in self.entities.iter_mut() {
|
||||||
|
//
|
||||||
|
// // Revolve the entity by the rotation speed, only if it is non-zero
|
||||||
|
// if entity.rotation_speed != 0.0 {
|
||||||
|
// let rotation = cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed));
|
||||||
|
// entity.mx_world = entity.mx_world * rotation;
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// let data = EntityUniforms {
|
||||||
|
// model: entity.mx_world.into(),
|
||||||
|
// color: [
|
||||||
|
// entity.color.r as f32,
|
||||||
|
// entity.color.g as f32,
|
||||||
|
// entity.color.b as f32,
|
||||||
|
// entity.color.a as f32,
|
||||||
|
// ],
|
||||||
|
// };
|
||||||
|
// queue.write_buffer(&entity.uniform_buf, 0, bytemuck::bytes_of(&data));
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if self.lights_are_dirty {
|
||||||
|
// self.lights_are_dirty = false;
|
||||||
|
// for (i, light) in self.lights.iter().enumerate() {
|
||||||
|
// queue.write_buffer(
|
||||||
|
// &self.light_uniform_buf,
|
||||||
|
// (i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
|
||||||
|
// bytemuck::bytes_of(&light.to_raw()),
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
let mut encoder = renderer
|
||||||
|
.device
|
||||||
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None });
|
||||||
|
|
||||||
|
encoder.push_debug_group("shadow passes");
|
||||||
|
/*for (i, light) in self.lights.iter().enumerate() {
|
||||||
|
encoder.push_debug_group(&format!(
|
||||||
|
"shadow pass {} (light at position {:?})",
|
||||||
|
i, light.pos
|
||||||
|
));
|
||||||
|
|
||||||
|
// The light uniform buffer already has the projection,
|
||||||
|
// let's just copy it over to the shadow uniform buffer.
|
||||||
|
encoder.copy_buffer_to_buffer(
|
||||||
|
&self.light_uniform_buf,
|
||||||
|
(i * mem::size_of::<LightRaw>()) as wgpu::BufferAddress,
|
||||||
|
&self.shadow_pass.uniform_buf,
|
||||||
|
0,
|
||||||
|
64,
|
||||||
|
);
|
||||||
|
|
||||||
|
encoder.insert_debug_marker("render entities");
|
||||||
|
{
|
||||||
|
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
|
color_attachments: &[],
|
||||||
|
depth_stencil_attachment: Some(
|
||||||
|
wgpu::RenderPassDepthStencilAttachmentDescriptor {
|
||||||
|
attachment: &light.target_view,
|
||||||
|
depth_ops: Some(wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(1.0),
|
||||||
|
store: true,
|
||||||
|
}),
|
||||||
|
stencil_ops: None,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
});
|
||||||
|
pass.set_pipeline(&self.shadow_pass.pipeline);
|
||||||
|
pass.set_bind_group(0, &self.shadow_pass.bind_group, &[]);
|
||||||
|
|
||||||
|
for entity in &self.entities {
|
||||||
|
pass.set_bind_group(1, &entity.bind_group, &[]);
|
||||||
|
pass.set_index_buffer(entity.index_buf.slice(..));
|
||||||
|
pass.set_vertex_buffer(0, entity.vertex_buf.slice(..));
|
||||||
|
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
encoder.pop_debug_group();
|
||||||
|
}*/
|
||||||
|
encoder.pop_debug_group();
|
||||||
|
|
||||||
|
// forward pass
|
||||||
|
encoder.push_debug_group("forward rendering pass");
|
||||||
|
{
|
||||||
|
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||||
|
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
|
||||||
|
attachment: &frame.output.view,
|
||||||
|
resolve_target: None,
|
||||||
|
ops: wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 }),
|
||||||
|
store: true,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
|
||||||
|
attachment: &renderer.forward_depth,
|
||||||
|
depth_ops: Some(wgpu::Operations {
|
||||||
|
load: wgpu::LoadOp::Clear(1.0),
|
||||||
|
store: false,
|
||||||
|
}),
|
||||||
|
stencil_ops: None,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
pass.set_pipeline(&renderer.forward_pass.pipeline);
|
||||||
|
pass.set_bind_group(0, &renderer.forward_pass.bind_group, &[]);
|
||||||
|
|
||||||
|
// for entity in &self.entities {
|
||||||
|
// pass.set_bind_group(1, &entity.bind_group, &[]);
|
||||||
|
// pass.set_index_buffer(entity.index_buf.slice(..));
|
||||||
|
// pass.set_vertex_buffer(0, entity.vertex_buf.slice(..));
|
||||||
|
// pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
encoder.pop_debug_group();
|
||||||
|
|
||||||
|
renderer.queue.submit(iter::once(encoder.finish()));
|
||||||
|
|
||||||
|
renderer.window.request_redraw();
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Renderer {
|
impl Renderer {
|
||||||
|
|
||||||
|
pub fn get_current_frame(&mut self) -> SwapChainFrame {
|
||||||
|
// Update the renderers swapchain state
|
||||||
|
match self.swapchain.get_current_frame() {
|
||||||
|
Ok(frame) => frame,
|
||||||
|
Err(_) => {
|
||||||
|
self.swapchain = self.device.create_swap_chain(&self.surface, &self.swapchain_description);
|
||||||
|
self.swapchain
|
||||||
|
.get_current_frame()
|
||||||
|
.expect("Failed to acquire next swap chain texture!")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn create_buffer(
|
||||||
pub fn create_buffer(device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
indices: Vec<u32>,
|
indices: Vec<u32>,
|
||||||
vertices: Vec<Vertex>) -> (Rc<Buffer>, Rc<Buffer>) {
|
vertices: Vec<Vertex>,
|
||||||
|
) -> (Arc<Buffer>, Arc<Buffer>) {
|
||||||
// Creates the vertex and index buffers for the cube
|
// Creates the vertex and index buffers for the cube
|
||||||
let vertex_size = mem::size_of::<Vertex>();
|
let vertex_size = mem::size_of::<Vertex>();
|
||||||
//import_mesh("/home/mrh/source/3d-min-viable-eng/resources/my_tree.obj");
|
//import_mesh("/home/mrh/source/3d-min-viable-eng/resources/my_tree.obj");
|
||||||
|
|
||||||
let vertex_buf = Rc::new(device.create_buffer_init(
|
let vertex_buf = Arc::new(
|
||||||
&wgpu::util::BufferInitDescriptor {
|
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some("vertex-buffer"),
|
label: Some("vertex-buffer"),
|
||||||
contents: bytemuck::cast_slice(&vertices),
|
contents: bytemuck::cast_slice(&vertices),
|
||||||
usage: wgpu::BufferUsage::VERTEX,
|
usage: wgpu::BufferUsage::VERTEX,
|
||||||
},
|
}),
|
||||||
));
|
);
|
||||||
|
|
||||||
let index_buf = Rc::new(device.create_buffer_init(
|
let index_buf = Arc::new(
|
||||||
&wgpu::util::BufferInitDescriptor {
|
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some("index-buffer"),
|
label: Some("index-buffer"),
|
||||||
contents: bytemuck::cast_slice(&indices),
|
contents: bytemuck::cast_slice(&indices),
|
||||||
usage: wgpu::BufferUsage::INDEX,
|
usage: wgpu::BufferUsage::INDEX,
|
||||||
},
|
}),
|
||||||
));
|
);
|
||||||
|
|
||||||
// // Creates the vertex and index buffers for the plane
|
// // Creates the vertex and index buffers for the plane
|
||||||
// let (plane_vertex_data, plane_index_data) = create_plane(7.0);
|
// let (plane_vertex_data, plane_index_data) = create_plane(7.0);
|
||||||
@@ -131,15 +285,109 @@ impl Renderer {
|
|||||||
(vertex_buf, index_buf)
|
(vertex_buf, index_buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn load_mesh_to_buffer(&self, filepath: &str) -> (Arc<Buffer>, Arc<Buffer>) {
|
||||||
pub fn load_mesh_to_buffer(device: Rc<wgpu::Device>, filepath: &str) -> (Rc<Buffer>, Rc<Buffer>) {
|
|
||||||
let (vertices, indices) = import_mesh(filepath);
|
let (vertices, indices) = import_mesh(filepath);
|
||||||
Renderer::create_buffer(&device, indices, vertices)
|
Renderer::create_buffer(&self.device, indices, vertices)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn init(window: Window) -> Renderer {
|
||||||
|
log::info!("Initializing the surface...");
|
||||||
|
|
||||||
pub fn init(device: Rc<wgpu::Device>, sc_desc: &wgpu::SwapChainDescriptor) -> Renderer {
|
// Grab the GPU instance, and query its features
|
||||||
|
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
|
||||||
|
let (size, surface) = unsafe {
|
||||||
|
let size = window.inner_size();
|
||||||
|
let surface = instance.create_surface(&window);
|
||||||
|
(size, surface)
|
||||||
|
};
|
||||||
|
let surface = Arc::new(surface);
|
||||||
|
|
||||||
|
let adapter = instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||||
|
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||||
|
compatible_surface: Some(&surface),
|
||||||
|
});
|
||||||
|
|
||||||
|
let adapter = futures::executor::block_on(adapter).unwrap();
|
||||||
|
|
||||||
|
let optional_features = Renderer::optional_features();
|
||||||
|
let required_features = Renderer::required_features();
|
||||||
|
let adapter_features = adapter.features();
|
||||||
|
// assert!(
|
||||||
|
// adapter_features.contains(required_features),
|
||||||
|
// "Adapter does not support required features for this example: {:?}",
|
||||||
|
// required_features - adapter_features
|
||||||
|
// );
|
||||||
|
|
||||||
|
let needed_limits = wgpu::Limits::default(); //Renderer::required_limits();
|
||||||
|
|
||||||
|
// Maybe for debug tracing???
|
||||||
|
let trace_dir = std::env::var("WGPU_TRACE");
|
||||||
|
|
||||||
|
// And then get the device we want
|
||||||
|
let device = adapter.request_device(
|
||||||
|
&wgpu::DeviceDescriptor {
|
||||||
|
features: (optional_features & adapter_features) | required_features,
|
||||||
|
limits: needed_limits,
|
||||||
|
shader_validation: true,
|
||||||
|
},
|
||||||
|
trace_dir.ok().as_ref().map(std::path::Path::new),
|
||||||
|
);
|
||||||
|
|
||||||
|
let (device, queue) = futures::executor::block_on(device).unwrap();
|
||||||
|
|
||||||
|
let queue = Arc::new(queue);
|
||||||
|
let device = Arc::new(device);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// This is some gross-ass web shit
|
||||||
|
/*#[cfg(target_arch = "wasm32")]
|
||||||
|
let spawner = {
|
||||||
|
use futures::{future::LocalFutureObj, task::SpawnError};
|
||||||
|
use winit::platform::web::WindowExtWebSys;
|
||||||
|
|
||||||
|
struct WebSpawner {}
|
||||||
|
impl LocalSpawn for WebSpawner {
|
||||||
|
fn spawn_local_obj(
|
||||||
|
&self,
|
||||||
|
future: LocalFutureObj<'static, ()>,
|
||||||
|
) -> Result<(), SpawnError> {
|
||||||
|
Ok(wasm_bindgen_futures::spawn_local(future))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
|
||||||
|
|
||||||
|
// On wasm, append the canvas to the document body
|
||||||
|
web_sys::window()
|
||||||
|
.and_then(|win| win.document())
|
||||||
|
.and_then(|doc| doc.body())
|
||||||
|
.and_then(|body| {
|
||||||
|
body.append_child(&web_sys::Element::from(window.canvas()))
|
||||||
|
.ok()
|
||||||
|
})
|
||||||
|
.expect("couldn't append canvas to document body");
|
||||||
|
|
||||||
|
WebSpawner {}
|
||||||
|
};*/
|
||||||
|
|
||||||
|
log::info!("Done doing the loading part...");
|
||||||
|
|
||||||
|
let mut sc_desc = Arc::new(wgpu::SwapChainDescriptor {
|
||||||
|
// Allows a texture to be a output attachment of a renderpass.
|
||||||
|
usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT,
|
||||||
|
format: if cfg!(target_arch = "wasm32") {
|
||||||
|
wgpu::TextureFormat::Bgra8Unorm
|
||||||
|
} else {
|
||||||
|
wgpu::TextureFormat::Bgra8UnormSrgb
|
||||||
|
},
|
||||||
|
width: size.width,
|
||||||
|
height: size.height,
|
||||||
|
// The presentation engine waits for the next vertical blanking period to update
|
||||||
|
present_mode: wgpu::PresentMode::Mailbox,
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut swap_chain = device.create_swap_chain(&surface, &sc_desc);
|
||||||
|
|
||||||
let entity_uniform_size = mem::size_of::<EntityUniforms>() as wgpu::BufferAddress;
|
let entity_uniform_size = mem::size_of::<EntityUniforms>() as wgpu::BufferAddress;
|
||||||
let plane_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
let plane_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||||
@@ -239,8 +487,10 @@ impl Renderer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Create the render pipeline
|
// Create the render pipeline
|
||||||
let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv"));
|
let vs_module =
|
||||||
let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv"));
|
device.create_shader_module(wgpu::include_spirv!("../resources/bake.vert.spv"));
|
||||||
|
let fs_module =
|
||||||
|
device.create_shader_module(wgpu::include_spirv!("../resources/bake.frag.spv"));
|
||||||
|
|
||||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
label: Some("shadow"),
|
label: Some("shadow"),
|
||||||
@@ -297,7 +547,8 @@ impl Renderer {
|
|||||||
dynamic: false,
|
dynamic: false,
|
||||||
min_binding_size: wgpu::BufferSize::new(mem::size_of::<
|
min_binding_size: wgpu::BufferSize::new(mem::size_of::<
|
||||||
ForwardUniforms,
|
ForwardUniforms,
|
||||||
>()
|
>(
|
||||||
|
)
|
||||||
as _),
|
as _),
|
||||||
},
|
},
|
||||||
count: None,
|
count: None,
|
||||||
@@ -346,7 +597,6 @@ impl Renderer {
|
|||||||
num_lights: [1 as u32, 0, 0, 0],
|
num_lights: [1 as u32, 0, 0, 0],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
let uniform_buf = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||||
label: Some("Uniform Buffer"),
|
label: Some("Uniform Buffer"),
|
||||||
contents: bytemuck::bytes_of(&forward_uniforms),
|
contents: bytemuck::bytes_of(&forward_uniforms),
|
||||||
@@ -380,7 +630,6 @@ impl Renderer {
|
|||||||
// shadow_target_views[0].take().unwrap(),
|
// shadow_target_views[0].take().unwrap(),
|
||||||
// pub(crate) target_view: wgpu::TextureView,
|
// pub(crate) target_view: wgpu::TextureView,
|
||||||
|
|
||||||
|
|
||||||
let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
let shadow_view = shadow_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
|
|
||||||
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
let shadow_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||||
@@ -395,7 +644,6 @@ impl Renderer {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
// Create bind group
|
// Create bind group
|
||||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||||
layout: &bind_group_layout,
|
layout: &bind_group_layout,
|
||||||
@@ -421,8 +669,10 @@ impl Renderer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Create the render pipeline
|
// Create the render pipeline
|
||||||
let vs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv"));
|
let vs_module =
|
||||||
let fs_module = device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv"));
|
device.create_shader_module(wgpu::include_spirv!("../resources/forward.vert.spv"));
|
||||||
|
let fs_module =
|
||||||
|
device.create_shader_module(wgpu::include_spirv!("../resources/forward.frag.spv"));
|
||||||
|
|
||||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||||
label: Some("main"),
|
label: Some("main"),
|
||||||
@@ -479,18 +729,25 @@ impl Renderer {
|
|||||||
});
|
});
|
||||||
|
|
||||||
Renderer {
|
Renderer {
|
||||||
|
window,
|
||||||
|
swapchain: swap_chain,
|
||||||
|
queue: queue,
|
||||||
|
size,
|
||||||
device: device,
|
device: device,
|
||||||
lights_are_dirty: false,
|
lights_are_dirty: false,
|
||||||
shadow_pass,
|
shadow_pass,
|
||||||
forward_pass,
|
forward_pass,
|
||||||
forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
forward_depth: depth_texture.create_view(&wgpu::TextureViewDescriptor::default()),
|
||||||
light_uniform_buf,
|
light_uniform_buf,
|
||||||
// plane_uniform_buf,
|
// plane_uniform_buf,
|
||||||
// plane_vertex_buf: (),
|
// plane_vertex_buf: (),
|
||||||
// plane_index_buf: ()
|
// plane_index_buf: ()
|
||||||
|
|
||||||
|
swapchain_description: sc_desc,
|
||||||
|
surface,
|
||||||
|
instance: Arc::new(instance)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//
|
|
||||||
|
|
||||||
|
|
||||||
pub fn render(
|
pub fn render(
|
||||||
@@ -499,8 +756,7 @@ impl Renderer {
|
|||||||
device: &wgpu::Device,
|
device: &wgpu::Device,
|
||||||
queue: &wgpu::Queue,
|
queue: &wgpu::Queue,
|
||||||
_spawner: &impl futures::task::LocalSpawn,
|
_spawner: &impl futures::task::LocalSpawn,
|
||||||
)
|
) {
|
||||||
{
|
|
||||||
// update uniforms
|
// update uniforms
|
||||||
// for entity in self.entities.iter_mut() {
|
// for entity in self.entities.iter_mut() {
|
||||||
//
|
//
|
||||||
@@ -622,6 +878,7 @@ impl Renderer {
|
|||||||
encoder.pop_debug_group();
|
encoder.pop_debug_group();
|
||||||
|
|
||||||
queue.submit(iter::once(encoder.finish()));
|
queue.submit(iter::once(encoder.finish()));
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn required_features() -> wgpu::Features {
|
pub(crate) fn required_features() -> wgpu::Features {
|
||||||
@@ -632,26 +889,20 @@ impl Renderer {
|
|||||||
wgpu::Features::DEPTH_CLAMPING
|
wgpu::Features::DEPTH_CLAMPING
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn resize(
|
pub fn resize(&mut self, width: u32, height: u32) {
|
||||||
&mut self,
|
|
||||||
sc_desc: &wgpu::SwapChainDescriptor,
|
|
||||||
device: &wgpu::Device,
|
|
||||||
queue: &wgpu::Queue,
|
|
||||||
)
|
|
||||||
{
|
|
||||||
// update view-projection matrix
|
// update view-projection matrix
|
||||||
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
|
let mx_total = Self::generate_matrix(width as f32 / height as f32);
|
||||||
let mx_ref: &[f32; 16] = mx_total.as_ref();
|
let mx_ref: &[f32; 16] = mx_total.as_ref();
|
||||||
queue.write_buffer(
|
self.queue.write_buffer(
|
||||||
&self.forward_pass.uniform_buf,
|
&self.forward_pass.uniform_buf,
|
||||||
0,
|
0,
|
||||||
bytemuck::cast_slice(mx_ref),
|
bytemuck::cast_slice(mx_ref),
|
||||||
);
|
);
|
||||||
|
|
||||||
let depth_texture = device.create_texture(&wgpu::TextureDescriptor {
|
let depth_texture = self.device.create_texture(&wgpu::TextureDescriptor {
|
||||||
size: wgpu::Extent3d {
|
size: wgpu::Extent3d {
|
||||||
width: sc_desc.width,
|
width: width,
|
||||||
height: sc_desc.height,
|
height: height,
|
||||||
depth: 1,
|
depth: 1,
|
||||||
},
|
},
|
||||||
mip_level_count: 1,
|
mip_level_count: 1,
|
||||||
@@ -664,4 +915,3 @@ impl Renderer {
|
|||||||
self.forward_depth = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
self.forward_depth = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,9 +39,10 @@ pub struct Runtime {
|
|||||||
|
|
||||||
impl Runtime {
|
impl Runtime {
|
||||||
pub fn init(
|
pub fn init(
|
||||||
sc_desc: &wgpu::SwapChainDescriptor,
|
// sc_desc: &wgpu::SwapChainDescriptor,
|
||||||
device: &wgpu::Device,
|
// device: &wgpu::Device,
|
||||||
_queue: &wgpu::Queue, ) -> Self
|
// _queue: &wgpu::Queue,
|
||||||
|
) -> Self
|
||||||
{
|
{
|
||||||
|
|
||||||
// https://sotrh.github.io/learn-wgpu/beginner/tutorial5-textures/#the-bindgroup
|
// https://sotrh.github.io/learn-wgpu/beginner/tutorial5-textures/#the-bindgroup
|
||||||
@@ -72,21 +73,21 @@ impl Runtime {
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
// Defines the Uniform buffer for the Vertex and Fragment shaders
|
// Defines the Uniform buffer for the Vertex and Fragment shaders
|
||||||
let local_bind_group_layout =
|
// let local_bind_group_layout =
|
||||||
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
// device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||||
entries: &[wgpu::BindGroupLayoutEntry {
|
// entries: &[wgpu::BindGroupLayoutEntry {
|
||||||
binding: 0,
|
// binding: 0,
|
||||||
visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
// visibility: wgpu::ShaderStage::VERTEX | wgpu::ShaderStage::FRAGMENT,
|
||||||
ty: wgpu::BindingType::UniformBuffer {
|
// ty: wgpu::BindingType::UniformBuffer {
|
||||||
dynamic: false,
|
// dynamic: false,
|
||||||
min_binding_size: wgpu::BufferSize::new(
|
// min_binding_size: wgpu::BufferSize::new(
|
||||||
mem::size_of::<EntityUniforms>() as _
|
// mem::size_of::<EntityUniforms>() as _
|
||||||
),
|
// ),
|
||||||
},
|
// },
|
||||||
count: None,
|
// count: None,
|
||||||
}],
|
// }],
|
||||||
label: None,
|
// label: None,
|
||||||
});
|
// });
|
||||||
|
|
||||||
|
|
||||||
let mut entities = Vec::default();
|
let mut entities = Vec::default();
|
||||||
|
|||||||
Reference in New Issue
Block a user