More clean-up

This commit is contained in:
Sijmen 2021-05-28 03:58:49 +02:00
parent 815930cba8
commit e08cb18db5
Signed by: vijfhoek
GPG key ID: 82D05C89B28B0DAE
2 changed files with 98 additions and 93 deletions

View file

@ -4,17 +4,19 @@ use winit::{event::WindowEvent, window::Window};
use crate::{camera::Camera, cube, texture::Texture, uniforms::Uniforms, vertex::Vertex}; use crate::{camera::Camera, cube, texture::Texture, uniforms::Uniforms, vertex::Vertex};
pub struct State { pub struct State {
pub surface: wgpu::Surface, pub render_surface: wgpu::Surface,
pub device: wgpu::Device, pub render_device: wgpu::Device,
pub queue: wgpu::Queue, pub queue: wgpu::Queue,
pub sc_desc: wgpu::SwapChainDescriptor, pub swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub swap_chain: wgpu::SwapChain, pub swap_chain: wgpu::SwapChain,
pub size: winit::dpi::PhysicalSize<u32>, pub size: winit::dpi::PhysicalSize<u32>,
pub render_pipeline: wgpu::RenderPipeline, pub render_pipeline: wgpu::RenderPipeline,
pub vertex_buffer: wgpu::Buffer, pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer, pub index_buffer: wgpu::Buffer,
pub num_indices: u32, pub num_indices: u32,
pub dirt_diffuse_bind_group: wgpu::BindGroup, pub texture_bind_group: wgpu::BindGroup,
pub _uniforms: Uniforms,
pub _camera: Camera,
pub uniform_bind_group: wgpu::BindGroup, pub uniform_bind_group: wgpu::BindGroup,
} }
@ -22,41 +24,41 @@ impl State {
pub async fn new(window: &Window) -> Self { pub async fn new(window: &Window) -> Self {
let size = window.inner_size(); let size = window.inner_size();
// The instance is a handle to our GPU let instance = wgpu::Instance::new(wgpu::BackendBit::all());
// BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU let render_surface = unsafe { instance.create_surface(window) };
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
let surface = unsafe { instance.create_surface(window) };
let adapter = instance let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions { .request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance, power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface), compatible_surface: Some(&render_surface),
}) })
.await .await
.unwrap(); .unwrap();
let (device, queue) = adapter let (render_device, queue) = adapter
.request_device( .request_device(
&wgpu::DeviceDescriptor { &wgpu::DeviceDescriptor {
label: None, label: Some("render_device"),
features: wgpu::Features::empty(), features: wgpu::Features::NON_FILL_POLYGON_MODE,
limits: wgpu::Limits::default(), limits: wgpu::Limits::default(),
}, },
None, // Trace path None,
) )
.await .await
.unwrap(); .unwrap();
let swap_chain_descriptor = wgpu::SwapChainDescriptor { let swap_chain_descriptor = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::RENDER_ATTACHMENT, usage: wgpu::TextureUsage::RENDER_ATTACHMENT,
format: adapter.get_swap_chain_preferred_format(&surface).unwrap(), format: adapter
.get_swap_chain_preferred_format(&render_surface)
.unwrap(),
width: size.width, width: size.width,
height: size.height, height: size.height,
present_mode: wgpu::PresentMode::Immediate, present_mode: wgpu::PresentMode::Immediate,
}; };
let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor); let swap_chain = render_device.create_swap_chain(&render_surface, &swap_chain_descriptor);
let dirt_diffuse_texture = Texture::from_bytes( let dirt_diffuse_texture = Texture::from_bytes(
&device, &render_device,
&queue, &queue,
include_bytes!("../assets/block/dirt.png"), include_bytes!("../assets/block/dirt.png"),
"dirt_diffuse", "dirt_diffuse",
@ -64,7 +66,7 @@ impl State {
.unwrap(); .unwrap();
let texture_bind_group_layout = let texture_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("exture_bind_group_layout"), label: Some("exture_bind_group_layout"),
entries: &[ entries: &[
wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry {
@ -89,7 +91,7 @@ impl State {
], ],
}); });
let dirt_diffuse_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let texture_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("dirt_diffuse_bind_group"), label: Some("dirt_diffuse_bind_group"),
layout: &texture_bind_group_layout, layout: &texture_bind_group_layout,
entries: &[ entries: &[
@ -104,21 +106,18 @@ impl State {
], ],
}); });
let shader = device.create_shader_module(&wgpu::ShaderModuleDescriptor { let shader = render_device.create_shader_module(&wgpu::ShaderModuleDescriptor {
label: Some("Shader"), label: Some("shader"),
flags: wgpu::ShaderFlags::all(), flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()), source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
}); });
let aspect = swap_chain_descriptor.width as f32 / swap_chain_descriptor.height as f32;
let camera = Camera { let camera = Camera {
// position the camera one unit up and 2 units back eye: (0.0, 1.0, 2.0).into(), // position the camera one unit up and 2 units back
// +z is out of the screen target: (0.0, 0.0, 0.0).into(), // have it look at the origin
eye: (0.0, 1.0, 2.0).into(),
// have it look at the origin
target: (0.0, 0.0, 0.0).into(),
// which way is "up"
up: cgmath::Vector3::unit_y(), up: cgmath::Vector3::unit_y(),
aspect: swap_chain_descriptor.width as f32 / swap_chain_descriptor.height as f32, aspect,
fovy: 45.0, fovy: 45.0,
znear: 0.1, znear: 0.1,
zfar: 100.0, zfar: 100.0,
@ -127,14 +126,14 @@ impl State {
let mut uniforms = Uniforms::new(); let mut uniforms = Uniforms::new();
uniforms.update_view_proj(&camera); uniforms.update_view_proj(&camera);
let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let uniform_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Uniform Buffer"), label: Some("uniform_buffer"),
contents: bytemuck::cast_slice(&[uniforms]), contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
}); });
let uniform_bind_group_layout = let uniform_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
entries: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::VERTEX, visibility: wgpu::ShaderStage::VERTEX,
@ -149,65 +148,63 @@ impl State {
}); });
let render_pipeline_layout = let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { render_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"), label: Some("render_pipeline_layout"),
bind_group_layouts: &[&texture_bind_group_layout, &uniform_bind_group_layout], bind_group_layouts: &[&texture_bind_group_layout, &uniform_bind_group_layout],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { let render_pipeline =
label: Some("Render Pipeline"), render_device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: Some(&render_pipeline_layout), label: Some("render_pipeline"),
vertex: wgpu::VertexState { layout: Some(&render_pipeline_layout),
module: &shader, vertex: wgpu::VertexState {
entry_point: "main", module: &shader,
buffers: &[Vertex::desc()], entry_point: "main",
}, buffers: &[Vertex::desc()],
fragment: Some(wgpu::FragmentState { },
module: &shader, fragment: Some(wgpu::FragmentState {
entry_point: "main", module: &shader,
targets: &[wgpu::ColorTargetState { entry_point: "main",
format: swap_chain_descriptor.format, targets: &[wgpu::ColorTargetState {
blend: Some(wgpu::BlendState { format: swap_chain_descriptor.format,
color: wgpu::BlendComponent::REPLACE, blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE, color: wgpu::BlendComponent::REPLACE,
}), alpha: wgpu::BlendComponent::REPLACE,
write_mask: wgpu::ColorWrite::ALL, }),
}], write_mask: wgpu::ColorWrite::ALL,
}), }],
primitive: wgpu::PrimitiveState { }),
topology: wgpu::PrimitiveTopology::TriangleList, primitive: wgpu::PrimitiveState {
strip_index_format: None, topology: wgpu::PrimitiveTopology::TriangleList,
front_face: wgpu::FrontFace::Ccw, strip_index_format: None,
cull_mode: Some(wgpu::Face::Back), front_face: wgpu::FrontFace::Ccw,
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE cull_mode: Some(wgpu::Face::Back),
polygon_mode: wgpu::PolygonMode::Fill, polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLAMPING clamp_depth: false,
clamp_depth: false, conservative: false,
// Requires Features::CONSERVATIVE_RASTERIZATION },
conservative: false, depth_stencil: None,
}, multisample: wgpu::MultisampleState {
depth_stencil: None, count: 1,
multisample: wgpu::MultisampleState { mask: !0,
count: 1, alpha_to_coverage_enabled: false,
mask: !0, },
alpha_to_coverage_enabled: false, });
},
});
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let vertex_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"), label: Some("vertex_buffer"),
contents: bytemuck::cast_slice(cube::VERTICES), contents: bytemuck::cast_slice(cube::VERTICES),
usage: wgpu::BufferUsage::VERTEX, usage: wgpu::BufferUsage::VERTEX,
}); });
let index_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { let index_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Index Buffer"), label: Some("index_buffer"),
contents: bytemuck::cast_slice(cube::INDICES), contents: bytemuck::cast_slice(cube::INDICES),
usage: wgpu::BufferUsage::INDEX, usage: wgpu::BufferUsage::INDEX,
}); });
let num_indices = cube::INDICES.len() as u32; let num_indices = cube::INDICES.len() as u32;
let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let uniform_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &uniform_bind_group_layout, layout: &uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
@ -217,27 +214,31 @@ impl State {
}); });
Self { Self {
surface, render_surface,
device, render_device,
queue, queue,
sc_desc: swap_chain_descriptor, swap_chain_descriptor,
swap_chain, swap_chain,
size, size,
render_pipeline, render_pipeline,
vertex_buffer, vertex_buffer,
index_buffer, index_buffer,
num_indices, num_indices,
_uniforms: uniforms,
_camera: camera,
uniform_bind_group, uniform_bind_group,
dirt_diffuse_bind_group, texture_bind_group,
} }
} }
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
println!("resizing to {:?}", new_size); println!("resizing to {:?}", new_size);
self.size = new_size; self.size = new_size;
self.sc_desc.width = new_size.width; self.swap_chain_descriptor.width = new_size.width;
self.sc_desc.height = new_size.height; self.swap_chain_descriptor.height = new_size.height;
self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); self.swap_chain = self
.render_device
.create_swap_chain(&self.render_surface, &self.swap_chain_descriptor);
} }
#[allow(unused_variables)] #[allow(unused_variables)]
@ -250,15 +251,15 @@ impl State {
pub fn render(&mut self) -> Result<(), wgpu::SwapChainError> { pub fn render(&mut self) -> Result<(), wgpu::SwapChainError> {
let frame = self.swap_chain.get_current_frame()?.output; let frame = self.swap_chain.get_current_frame()?.output;
let mut encoder = self let mut render_encoder =
.device self.render_device
.create_command_encoder(&wgpu::CommandEncoderDescriptor { .create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"), label: Some("render_encoder"),
}); });
{ {
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let mut render_pass = render_encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"), label: Some("render_pass"),
color_attachments: &[wgpu::RenderPassColorAttachment { color_attachments: &[wgpu::RenderPassColorAttachment {
view: &frame.view, view: &frame.view,
resolve_target: None, resolve_target: None,
@ -271,14 +272,17 @@ impl State {
}); });
render_pass.set_pipeline(&self.render_pipeline); render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.dirt_diffuse_bind_group, &[]);
render_pass.set_bind_group(0, &self.texture_bind_group, &[]);
render_pass.set_bind_group(1, &self.uniform_bind_group, &[]); render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..)); render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16); render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..1); render_pass.draw_indexed(0..self.num_indices, 0, 0..1);
} }
self.queue.submit(std::iter::once(encoder.finish())); self.queue.submit(std::iter::once(render_encoder.finish()));
Ok(()) Ok(())
} }

View file

@ -1,3 +1,5 @@
use cgmath::SquareMatrix;
use crate::camera::Camera; use crate::camera::Camera;
#[repr(C)] #[repr(C)]
@ -10,7 +12,6 @@ pub struct Uniforms {
impl Uniforms { impl Uniforms {
pub fn new() -> Self { pub fn new() -> Self {
use cgmath::SquareMatrix;
Self { Self {
view_projection: cgmath::Matrix4::identity().into(), view_projection: cgmath::Matrix4::identity().into(),
} }