Split up State::new

This commit is contained in:
Sijmen 2021-05-28 21:45:12 +02:00
parent 7dbe316637
commit dc5ed8eb9a
Signed by: vijfhoek
GPG key ID: 82D05C89B28B0DAE

View file

@ -1,5 +1,5 @@
use cgmath::Rotation3;
use wgpu::util::DeviceExt;
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use winit::{event::WindowEvent, window::Window};
use crate::{
@ -13,29 +13,21 @@ use crate::{
};
const NUM_INSTANCES_PER_ROW: u32 = 10;
const INSTANCE_DISPLACEMENT: cgmath::Vector3<f32> = cgmath::Vector3::new(
NUM_INSTANCES_PER_ROW as f32 * 1.5,
0.0,
NUM_INSTANCES_PER_ROW as f32 * 1.5,
);
pub struct State {
pub render_surface: wgpu::Surface,
pub render_device: wgpu::Device,
pub queue: wgpu::Queue,
pub swap_chain_descriptor: wgpu::SwapChainDescriptor,
pub swap_chain: wgpu::SwapChain,
render_surface: wgpu::Surface,
render_device: wgpu::Device,
queue: wgpu::Queue,
swap_chain_descriptor: wgpu::SwapChainDescriptor,
swap_chain: wgpu::SwapChain,
pub size: winit::dpi::PhysicalSize<u32>,
pub render_pipeline: wgpu::RenderPipeline,
pub vertex_buffer: wgpu::Buffer,
pub index_buffer: wgpu::Buffer,
pub num_indices: u32,
pub texture_bind_group: wgpu::BindGroup,
pub _uniforms: Uniforms,
pub _camera: Camera,
pub uniform_bind_group: wgpu::BindGroup,
pub instances: Vec<Instance>,
pub instance_buffer: wgpu::Buffer,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
texture_bind_group: wgpu::BindGroup,
uniform_bind_group: wgpu::BindGroup,
instances: Vec<Instance>,
instance_buffer: wgpu::Buffer,
depth_texture: Texture,
light: Light,
light_buffer: wgpu::Buffer,
@ -44,28 +36,38 @@ pub struct State {
impl State {
fn create_render_pipeline(
device: &wgpu::Device,
layout: &wgpu::PipelineLayout,
color_format: wgpu::TextureFormat,
depth_format: Option<wgpu::TextureFormat>,
vertex_layouts: &[wgpu::VertexBufferLayout],
shader: wgpu::ShaderModuleDescriptor,
render_device: &wgpu::Device,
swap_chain_descriptor: &wgpu::SwapChainDescriptor,
bind_group_layouts: &[&wgpu::BindGroupLayout],
) -> wgpu::RenderPipeline {
let shader = device.create_shader_module(&shader);
let shader = render_device.create_shader_module(
&(wgpu::ShaderModuleDescriptor {
label: Some("shader"),
flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
}),
);
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
let render_pipeline_layout =
render_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("render_pipeline_layout"),
bind_group_layouts,
push_constant_ranges: &[],
});
render_device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&layout),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "main",
buffers: vertex_layouts,
buffers: &[Vertex::desc(), InstanceRaw::desc()],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "main",
targets: &[wgpu::ColorTargetState {
format: color_format,
format: swap_chain_descriptor.format,
blend: Some(wgpu::BlendState {
alpha: wgpu::BlendComponent::REPLACE,
color: wgpu::BlendComponent::REPLACE,
@ -78,15 +80,12 @@ impl State {
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
cull_mode: Some(wgpu::Face::Back),
// Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
polygon_mode: wgpu::PolygonMode::Fill,
// Requires Features::DEPTH_CLAMPING
clamp_depth: false,
// Requires Features::CONSERVATIVE_RASTERIZATION
conservative: false,
},
depth_stencil: depth_format.map(|format| wgpu::DepthStencilState {
format,
depth_stencil: Some(wgpu::DepthStencilState {
format: Texture::DEPTH_FORMAT,
depth_write_enabled: true,
depth_compare: wgpu::CompareFunction::Less,
stencil: wgpu::StencilState::default(),
@ -100,9 +99,9 @@ impl State {
})
}
pub async fn new(window: &Window) -> Self {
let size = window.inner_size();
async fn create_render_device(
window: &Window,
) -> (wgpu::Surface, wgpu::Adapter, wgpu::Device, wgpu::Queue) {
let instance = wgpu::Instance::new(wgpu::BackendBit::all());
let render_surface = unsafe { instance.create_surface(window) };
let adapter = instance
@ -125,10 +124,21 @@ impl State {
.await
.unwrap();
(render_surface, adapter, render_device, queue)
}
fn create_swap_chain(
window: &Window,
adapter: &wgpu::Adapter,
render_device: &wgpu::Device,
render_surface: &wgpu::Surface,
) -> (wgpu::SwapChainDescriptor, wgpu::SwapChain) {
let size = window.inner_size();
let swap_chain_descriptor = wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsage::RENDER_ATTACHMENT,
format: adapter
.get_swap_chain_preferred_format(&render_surface)
.get_swap_chain_preferred_format(render_surface)
.unwrap(),
width: size.width,
height: size.height,
@ -136,9 +146,16 @@ impl State {
};
let swap_chain = render_device.create_swap_chain(&render_surface, &swap_chain_descriptor);
let dirt_diffuse_texture = Texture::from_bytes(
&render_device,
&queue,
(swap_chain_descriptor, swap_chain)
}
fn create_textures(
render_device: &wgpu::Device,
queue: &wgpu::Queue,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
let texture = Texture::from_bytes(
render_device,
queue,
include_bytes!("../assets/block/cobblestone.png"),
"dirt_diffuse",
)
@ -146,7 +163,7 @@ impl State {
let texture_bind_group_layout =
render_device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("exture_bind_group_layout"),
label: Some("texture_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
@ -176,36 +193,38 @@ impl State {
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&dirt_diffuse_texture.view),
resource: wgpu::BindingResource::TextureView(&texture.view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&dirt_diffuse_texture.sampler),
resource: wgpu::BindingResource::Sampler(&texture.sampler),
},
],
});
let shader = wgpu::ShaderModuleDescriptor {
label: Some("shader"),
flags: wgpu::ShaderFlags::all(),
source: wgpu::ShaderSource::Wgsl(include_str!("shader.wgsl").into()),
};
(texture_bind_group_layout, texture_bind_group)
}
let aspect = swap_chain_descriptor.width as f32 / swap_chain_descriptor.height as f32;
let camera = Camera {
fn create_camera(swap_chain_descriptor: &wgpu::SwapChainDescriptor) -> Camera {
Camera {
eye: (0.0, 5.0, 10.0).into(), // position the camera one unit up and 2 units back
target: (0.0, 0.0, 0.0).into(), // have it look at the origin
up: cgmath::Vector3::unit_y(),
aspect,
aspect: swap_chain_descriptor.width as f32 / swap_chain_descriptor.height as f32,
fovy: 45.0,
znear: 0.1,
zfar: 100.0,
};
}
}
fn create_uniforms(
camera: &Camera,
render_device: &wgpu::Device,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
let mut uniforms = Uniforms::new();
uniforms.update_view_proj(&camera);
uniforms.update_view_proj(camera);
let uniform_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
let uniform_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("uniform_buffer"),
contents: bytemuck::cast_slice(&[uniforms]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
@ -226,14 +245,28 @@ impl State {
label: Some("uniform_bind_group_layout"),
});
let uniform_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
label: Some("uniform_bind_group"),
});
(uniform_bind_group_layout, uniform_bind_group)
}
fn create_light(
render_device: &wgpu::Device,
) -> (Light, wgpu::Buffer, wgpu::BindGroupLayout, wgpu::BindGroup) {
let light = Light {
position: [5.0, 5.0, 5.0],
_padding: 0,
color: [1.0, 1.0, 1.0],
};
// We'll want to update our lights position, so we use COPY_DST
let light_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
let light_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("light_buffer"),
contents: bytemuck::cast_slice(&[light]),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
@ -263,55 +296,23 @@ impl State {
label: None,
});
let render_pipeline_layout =
render_device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("render_pipeline_layout"),
bind_group_layouts: &[
&texture_bind_group_layout,
&uniform_bind_group_layout,
&light_bind_group_layout,
],
push_constant_ranges: &[],
});
(
light,
light_buffer,
light_bind_group_layout,
light_bind_group,
)
}
let render_pipeline = Self::create_render_pipeline(
&render_device,
&render_pipeline_layout,
swap_chain_descriptor.format,
Some(Texture::DEPTH_FORMAT),
&[Vertex::desc(), InstanceRaw::desc()],
shader,
);
let vertex_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("vertex_buffer"),
contents: bytemuck::cast_slice(cube::VERTICES),
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("index_buffer"),
contents: bytemuck::cast_slice(cube::INDICES),
usage: wgpu::BufferUsage::INDEX,
});
let num_indices = cube::INDICES.len() as u32;
let uniform_bind_group = render_device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &uniform_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: uniform_buffer.as_entire_binding(),
}],
label: Some("uniform_bind_group"),
});
let instances = (0..NUM_INSTANCES_PER_ROW)
fn create_instances(render_device: &wgpu::Device) -> (Vec<Instance>, wgpu::Buffer) {
let instances = (0..NUM_INSTANCES_PER_ROW as i32)
.flat_map(|z| {
(0..NUM_INSTANCES_PER_ROW).map(move |x| {
(0..NUM_INSTANCES_PER_ROW as i32).map(move |x| {
let position = cgmath::Vector3 {
x: x as f32 * 3.0,
x: (x - NUM_INSTANCES_PER_ROW as i32 / 2) as f32 * 2.0,
y: 0.0,
z: z as f32 * 3.0,
} - INSTANCE_DISPLACEMENT;
z: (z - NUM_INSTANCES_PER_ROW as i32 / 2) as f32 * 2.0,
};
let rotation = cgmath::Quaternion::from_axis_angle(
cgmath::Vector3::unit_z(),
@ -324,12 +325,50 @@ impl State {
.collect::<Vec<_>>();
let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
let instance_buffer = render_device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
let instance_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("Instance Buffer"),
contents: bytemuck::cast_slice(&instance_data),
usage: wgpu::BufferUsage::VERTEX,
});
(instances, instance_buffer)
}
pub async fn new(window: &Window) -> Self {
let size = window.inner_size();
let (render_surface, adapter, render_device, queue) =
Self::create_render_device(window).await;
let (swap_chain_descriptor, swap_chain) =
Self::create_swap_chain(window, &adapter, &render_device, &render_surface);
let (texture_layout, texture_bind_group) = Self::create_textures(&render_device, &queue);
let camera = Self::create_camera(&swap_chain_descriptor);
let (uniform_layout, uniform_bind_group) = Self::create_uniforms(&camera, &render_device);
let (light, light_buffer, light_layout, light_bind_group) =
Self::create_light(&render_device);
let layouts = [&texture_layout, &uniform_layout, &light_layout];
let render_pipeline =
Self::create_render_pipeline(&render_device, &swap_chain_descriptor, &layouts);
let vertex_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("vertex_buffer"),
contents: bytemuck::cast_slice(cube::VERTICES),
usage: wgpu::BufferUsage::VERTEX,
});
let index_buffer = render_device.create_buffer_init(&BufferInitDescriptor {
label: Some("index_buffer"),
contents: bytemuck::cast_slice(cube::INDICES),
usage: wgpu::BufferUsage::INDEX,
});
let (instances, instance_buffer) = Self::create_instances(&render_device);
let depth_texture =
Texture::create_depth_texture(&render_device, &swap_chain_descriptor, "depth_texture");
@ -343,9 +382,6 @@ impl State {
render_pipeline,
vertex_buffer,
index_buffer,
num_indices,
_uniforms: uniforms,
_camera: camera,
uniform_bind_group,
texture_bind_group,
instances,
@ -430,7 +466,11 @@ impl State {
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
render_pass.draw_indexed(0..self.num_indices, 0, 0..self.instances.len() as _);
render_pass.draw_indexed(
0..cube::INDICES.len() as u32,
0,
0..self.instances.len() as u32,
);
}
self.queue.submit(std::iter::once(render_encoder.finish()));