resizing fixed

This commit is contained in:
2021-02-04 22:00:14 -08:00
parent e2c459872f
commit f3e308cb2f
4 changed files with 93 additions and 108 deletions

View File

@@ -1,5 +1,6 @@
extern crate tobj;
extern crate winit;
extern crate ncollide3d;
use std::rc::Rc;
use std::sync::Arc;
@@ -19,6 +20,7 @@ use winit::{
};
use crate::render::Renderer;
use winit::event::DeviceEvent::MouseMotion;
mod framework;
mod geometry;
@@ -124,66 +126,28 @@ pub struct Mesh {
bind_group: Arc<BindGroup>,
}
//log::info!("");
fn main() {
// #[cfg(not(target_arch = "wasm32"))]
// {
// let chrome_tracing_dir = std::env::var("WGPU_CHROME_TRACE");
// wgpu_subscriber::initialize_default_subscriber(
// chrome_tracing_dir.as_ref().map(std::path::Path::new).ok(),
// );
// };
// #[cfg(target_arch = "wasm32")]
// console_log::init().expect("could not initialize logger");
use legion::*;
let mut world = World::default();
/*
Querying entities by their handle
// entries return `None` if the entity does not exist
if let Some(mut entry) = world.entry(entity) {
// access information about the entity's archetype
//println!("{:?} has {:?}", entity, entry.archetype().layout().component_types());
// add an extra component
//entry.add_component(12f32);
// access the entity's components, returns `None` if the entity does not have the component
//assert_eq!(entry.get_component::<f32>().unwrap(), &12f32);
}
*/
#[cfg(not(target_arch = "wasm32"))]
let (mut pool, spawner) = {
let local_pool = futures::executor::LocalPool::new();
let spawner = local_pool.spawner();
(local_pool, spawner)
};
// Schedule for the render systen
let mut render_schedule = Schedule::builder()
.add_system(render::render_test_system())
.build();
// run our schedule (you should do this each update)
//schedule.execute(&mut world, &mut resources);
// Querying entities by component is just defining the component type!
let mut query = Read::<Position>::query();
// you can then iterate through the components found in the world
for position in query.iter(&world) {
//println!("{:?}", position);
}
// TODO schedule for the update system and others
let event_loop = EventLoop::new();
let mut builder = winit::window::WindowBuilder::new();
builder = builder.with_title("title");
builder = builder.with_title("MVGE");
// I don't know what they are doing here
#[cfg(windows_OFF)] // TODO
@@ -192,66 +156,48 @@ fn main() {
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();
// Not sure why this is guarded, maybe we don't handle the event loop timing?
#[cfg(not(target_arch = "wasm32"))]
let mut last_update_inst = Instant::now();
log::info!("Entering render loop...");
// Load up the renderer (and the resources)
let mut renderer = render::Renderer::init(window);
entity_loading(&mut world, &mut renderer);
let mut renderer = {
let mut renderer = render::Renderer::init(&window);
entity_loading(&mut world, &mut renderer);
renderer
};
let mut resources = Resources::default();
resources.insert(renderer);
// This is just an winit event loop
event_loop.run(move |event, _, control_flow| {
//let _ = (&instance, &adapter); // force ownership by the closure (wtf??)
// Override the control flow behaviour based on our system
*control_flow = if cfg!(feature = "metal-auto-capture") {
ControlFlow::Exit
} else {
#[cfg(not(target_arch = "wasm32"))]
{
// Artificially slows the loop rate to 10 millis
// This is called after redraw events cleared
ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(10))
}
#[cfg(target_arch = "wasm32")]
{
ControlFlow::Poll
}
};
event_loop.run(move |event, _, control_flow| {
// Artificially slows the loop rate to 10 millis
// This is called after redraw events cleared
*control_flow = ControlFlow::WaitUntil(Instant::now() + Duration::from_millis(10));
match event {
event::Event::MainEventsCleared => {
#[cfg(not(target_arch = "wasm32"))]
{
// ask for a redraw every 20 millis
if last_update_inst.elapsed() > Duration::from_millis(20) {
//window.request_redraw();
resources
.get_mut::<Renderer>()
.unwrap()
.window
.request_redraw();
last_update_inst = Instant::now();
}
pool.run_until_stalled();
// ask for a redraw every 20 millis
if last_update_inst.elapsed() > Duration::from_millis(20) {
window.request_redraw();
last_update_inst = Instant::now();
}
#[cfg(target_arch = "wasm32")]
window.request_redraw();
pool.run_until_stalled();
}
event::Event::DeviceEvent {
event: MouseMotion{ delta },
..
} => {
resources
.get_mut::<Renderer>()
.unwrap()
.cam_look_delta((delta.0, delta.1));
//swap_chain = device.create_swap_chain(&surface, &sc_desc);
},
// Resizing will queue a request_redraw
event::Event::WindowEvent {
event: WindowEvent::Resized(size),
@@ -267,7 +213,7 @@ fn main() {
.resize(width, height);
//swap_chain = device.create_swap_chain(&surface, &sc_desc);
}
},
event::Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
@@ -286,8 +232,8 @@ fn main() {
}
},
event::Event::RedrawRequested(_) => {
// Call the render system
render_schedule.execute(&mut world, &mut resources);
//resources.get_mut::<Renderer>().unwrap().render();
}
_ => {}
}

View File

@@ -3,7 +3,7 @@ use std::{iter, num::NonZeroU32, ops::Range, rc::Rc};
use bytemuck::__core::mem;
use bytemuck::{Pod, Zeroable};
use cgmath::Point3;
use cgmath::{Point3, Matrix4, Transform, vec3};
use futures::executor::LocalPool;
use legion::world::SubWorld;
use legion::*;
@@ -54,9 +54,9 @@ pub struct Pass {
}
pub struct Renderer {
pub window: Window,
swapchain: SwapChain,
swapchain_description: Arc<SwapChainDescriptor>,
swapchain_description: SwapChainDescriptor,
instance: Arc<Instance>,
device: Arc<Device>,
queue: Arc<Queue>,
@@ -66,14 +66,18 @@ pub struct Renderer {
lights_are_dirty: bool,
shadow_pass: Pass,
forward_pass: Pass,
forward_depth: wgpu::TextureView,
entity_bind_group_layout: BindGroupLayout,
shadow_target_views: Vec<Arc<TextureView>>,
views_given: u32,
forward_pass: Pass,
forward_depth: wgpu::TextureView,
entity_bind_group_layout: BindGroupLayout,
light_uniform_buf: wgpu::Buffer,
camera_projection: Matrix4<f32>,
}
impl Renderer {
@@ -87,12 +91,15 @@ impl Renderer {
const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float;
pub(crate) fn generate_matrix(aspect_ratio: f32) -> cgmath::Matrix4<f32> {
// Specifies the aspect ratio that determines the field of view in the x direction.
// The aspect ratio is the ratio of x (width) to y (height).
let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 20.0);
let mx_view = cgmath::Matrix4::look_at(
cgmath::Point3::new(3.0f32, -10.0, 6.0),
cgmath::Point3::new(3.0f32, -9.0, 6.0),
cgmath::Point3::new(0f32, 0.0, 0.0),
cgmath::Vector3::unit_z(),
);
let mx_correction = OPENGL_TO_WGPU_MATRIX;
mx_correction * mx_projection * mx_view
}
@@ -239,6 +246,7 @@ pub fn render_test(world: &mut SubWorld, #[resource] renderer: &mut Renderer) {
}
impl Renderer {
pub fn get_current_frame(&mut self) -> SwapChainFrame {
// Update the renderers swapchain state
match self.swapchain.get_current_frame() {
@@ -367,14 +375,14 @@ impl Renderer {
}
}
pub fn init(window: Window) -> Renderer {
pub fn init(window: &Window) -> Renderer {
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);
let surface = instance.create_surface(window);
(size, surface)
};
let surface = Arc::new(surface);
@@ -443,7 +451,7 @@ impl Renderer {
log::info!("Done doing the loading part...");
let mut sc_desc = Arc::new(wgpu::SwapChainDescriptor {
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") {
@@ -624,6 +632,9 @@ impl Renderer {
})
.collect::<Vec<_>>();
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let forward_pass = {
// Create pipeline layout
let bind_group_layout =
@@ -677,8 +688,6 @@ impl Renderer {
push_constant_ranges: &[],
});
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
// I need to know the number of lights...
let forward_uniforms = ForwardUniforms {
proj: *mx_total.as_ref(),
@@ -791,7 +800,6 @@ impl Renderer {
});
Renderer {
window,
swapchain: swap_chain,
queue: queue,
size,
@@ -807,10 +815,11 @@ impl Renderer {
surface,
instance: Arc::new(instance),
views_given: 0,
camera_projection: mx_total,
}
}
pub(crate) fn required_features() -> wgpu::Features {
pub fn required_features() -> wgpu::Features {
wgpu::Features::empty()
}
@@ -818,7 +827,36 @@ impl Renderer {
wgpu::Features::DEPTH_CLAMPING
}
pub fn cam_look_delta(&mut self, delta: (f64, f64)) {
// let mx_projection = cgmath::perspective(cgmath::Deg(45f32), aspect_ratio, 1.0, 20.0);
// let mx_view = cgmath::Matrix4::look_at(
// cgmath::Point3::new(3.0f32, -9.0, 6.0),
// cgmath::Point3::new(0f32, 0.0, 0.0),
// cgmath::Vector3::unit_z(),
// );
// let mx_correction = OPENGL_TO_WGPU_MATRIX;
// let mx_total = mx_correction * mx_projection * mx_view;
let mut mx_total = self.camera_projection.clone();
let q = vec3(delta.0 as f32, delta.1 as f32, 1.0);
mx_total.transform_vector(q);
let mx_ref: &[f32; 16] = mx_total.as_ref();
self.queue.write_buffer(
&self.forward_pass.uniform_buf,
0,
bytemuck::cast_slice(mx_ref),
);
}
pub fn resize(&mut self, width: u32, height: u32) {
self.swapchain_description.width = width;
self.swapchain_description.height = height;
self.swapchain = self.device.create_swap_chain(
&self.surface, &self.swapchain_description.clone()
);
// update view-projection matrix
let mx_total = Self::generate_matrix(width as f32 / height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
@@ -842,5 +880,8 @@ impl Renderer {
label: Some("Depth Texture"),
});
self.forward_depth = depth_texture.create_view(&wgpu::TextureViewDescriptor::default());
self.camera_projection = mx_total;
}
}