project structure cleanup
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
use cgmath::{Point3, Vector3, Matrix4, Deg};
|
||||
|
||||
pub struct Camera {
|
||||
pub position: Point3<f32>,
|
||||
pub forward: Vector3<f32>,
|
||||
pub up: Vector3<f32>,
|
||||
aspect: f32,
|
||||
fovy: f32,
|
||||
znear: f32,
|
||||
zfar: f32,
|
||||
}
|
||||
|
||||
impl Camera {
|
||||
|
||||
pub fn new(aspect: f32, fov: f32) -> Self {
|
||||
Self {
|
||||
position: (0.0, 1.0, 0.0).into(),
|
||||
forward: (0.0, 0.0, 1.0).into(),
|
||||
up: Vector3::unit_y(),
|
||||
aspect,
|
||||
fovy: fov,
|
||||
znear: 0.1,
|
||||
zfar: 100.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_aspect(&mut self, aspect: f32) {
|
||||
self.aspect = aspect;
|
||||
}
|
||||
|
||||
pub fn proj_matrix(&self) -> Matrix4<f32> {
|
||||
return cgmath::perspective(Deg(self.fovy), self.aspect, self.znear, self.zfar);
|
||||
}
|
||||
|
||||
pub fn view_matrix(&self) -> Matrix4<f32> {
|
||||
return Matrix4::look_to_rh((0.0,0.0,0.0).into(), self.forward, self.up);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
use winit::{window::Window, dpi::PhysicalSize};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
mod vertex; use vertex::Vertex;
|
||||
mod texture; use texture::Texture;
|
||||
pub mod camera; use camera::Camera;
|
||||
mod uniforms; use uniforms::Uniforms;
|
||||
|
||||
|
||||
const VERTICES: &[Vertex] = &[
|
||||
Vertex { position: [-1.0, 1.0, 0.0], uv: [-1.0, 1.0] }, // top left
|
||||
Vertex { position: [ 1.0, 1.0, 0.0], uv: [1.0, 1.0] }, // top right
|
||||
Vertex { position: [ 1.0,-1.0, 0.0], uv: [1.0, -1.0] }, // bottom right
|
||||
Vertex { position: [-1.0,-1.0, 0.0], uv: [-1.0, -1.0] }, // bottom left
|
||||
];
|
||||
const INDICES: &[u16] = &[ 0, 1, 3, 3, 1, 2 ];
|
||||
|
||||
|
||||
pub struct Renderer {
|
||||
surface: wgpu::Surface,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
swapchain_desc: wgpu::SwapChainDescriptor,
|
||||
swapchain: wgpu::SwapChain,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
// Buffers
|
||||
vertex_buffer: wgpu::Buffer,
|
||||
index_buffer: wgpu::Buffer,
|
||||
uniform_buffer: wgpu::Buffer,
|
||||
// Uniform bind group
|
||||
uniform_bind_group: wgpu::BindGroup,
|
||||
// Texture
|
||||
bind_group: wgpu::BindGroup,
|
||||
// Camera
|
||||
pub camera: Camera,
|
||||
uniforms: Uniforms
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
|
||||
fn create_swapchain(adapter: &wgpu::Adapter, device: &wgpu::Device, surface: &wgpu::Surface, size: PhysicalSize<u32>) -> (wgpu::SwapChainDescriptor, wgpu::SwapChain) {
|
||||
let swapchain_desc = wgpu::SwapChainDescriptor {
|
||||
usage: wgpu::TextureUsage::RENDER_ATTACHMENT, // render to screen
|
||||
format: adapter.get_swap_chain_preferred_format(&surface),
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
present_mode: wgpu::PresentMode::Immediate, // Fifo = Vsync
|
||||
};
|
||||
let swapchain = device.create_swap_chain(&surface, &swapchain_desc);
|
||||
(swapchain_desc, swapchain)
|
||||
}
|
||||
|
||||
fn create_pipeline(device: &wgpu::Device, swapchain_desc: &wgpu::SwapChainDescriptor, bind_group_layouts: &[&wgpu::BindGroupLayout]) -> wgpu::RenderPipeline{
|
||||
// Pipeline stuff
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: bind_group_layouts,
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
let vert_state = wgpu::VertexState { //vert
|
||||
module: &device.create_shader_module(&wgpu::include_spirv!("..\\shaders\\bin\\shader.vert.spv")),
|
||||
entry_point: "main",
|
||||
buffers: &[Vertex::desc()],
|
||||
};
|
||||
let frag_state = wgpu::FragmentState { // frag
|
||||
module: &device.create_shader_module(&wgpu::include_spirv!("..\\shaders\\bin\\shader.frag.spv")),
|
||||
entry_point: "main",
|
||||
targets: &[wgpu::ColorTargetState {
|
||||
format: swapchain_desc.format,
|
||||
alpha_blend: wgpu::BlendState::REPLACE,
|
||||
color_blend: wgpu::BlendState::REPLACE,
|
||||
write_mask: wgpu::ColorWrite::ALL,
|
||||
}],
|
||||
};
|
||||
let prim_state = wgpu::PrimitiveState { // primitive
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Cw,
|
||||
cull_mode: wgpu::CullMode::Back,
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
};
|
||||
let multisample_state = wgpu::MultisampleState { // multisample
|
||||
count: 1,
|
||||
mask: !0,
|
||||
alpha_to_coverage_enabled: false,
|
||||
};
|
||||
|
||||
// Create pipeline
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("Render Pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: vert_state,
|
||||
fragment: Some(frag_state),
|
||||
primitive: prim_state,
|
||||
depth_stencil: None,
|
||||
multisample: multisample_state,
|
||||
})
|
||||
}
|
||||
|
||||
fn create_bind_group(device: &wgpu::Device, tex: &Texture) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
|
||||
let bind_group_layout = device.create_bind_group_layout(
|
||||
&wgpu::BindGroupLayoutDescriptor {
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
multisampled: false,
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler {
|
||||
comparison: false,
|
||||
filtering: true,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
label: None,
|
||||
}
|
||||
);
|
||||
|
||||
let bind_group = device.create_bind_group(
|
||||
&wgpu::BindGroupDescriptor {
|
||||
layout: &bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&tex.view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&tex.sampler),
|
||||
}
|
||||
],
|
||||
label: None,
|
||||
}
|
||||
);
|
||||
|
||||
(bind_group_layout, bind_group)
|
||||
}
|
||||
|
||||
fn create_uniform_bind_group(device: &wgpu::Device, buf: &wgpu::Buffer) -> (wgpu::BindGroupLayout, wgpu::BindGroup) {
|
||||
let uniform_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStage::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
}
|
||||
],
|
||||
label: Some("uniform_bind_group_layout"),
|
||||
});
|
||||
|
||||
let uniform_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
layout: &uniform_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: buf.as_entire_binding(),
|
||||
}
|
||||
],
|
||||
label: Some("uniform_bind_group"),
|
||||
});
|
||||
|
||||
(uniform_bind_group_layout, uniform_bind_group)
|
||||
}
|
||||
|
||||
fn create_buffer(device: &wgpu::Device, usage: wgpu::BufferUsage, content: &[u8]) -> wgpu::Buffer {
|
||||
device.create_buffer_init(
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: None,
|
||||
contents: content,
|
||||
usage: usage,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
pub async fn new(window: &Window) -> Self {
|
||||
|
||||
// Create surface and pick device
|
||||
let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
|
||||
let surface = unsafe { instance.create_surface(window) };
|
||||
|
||||
// Pick adapter (physical gpu)
|
||||
let adapter_options = wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, compatible_surface: Some(&surface) };
|
||||
let adapter = instance.request_adapter(&adapter_options).await.unwrap();
|
||||
println!("Adapter: {}", adapter.get_info().name);
|
||||
|
||||
// Pick device (logical gpu) from adapter
|
||||
let device_desc = wgpu::DeviceDescriptor { features: wgpu::Features::empty(), limits: wgpu::Limits::default(), label: None };
|
||||
let (device, queue) = adapter.request_device(&device_desc, None).await.unwrap();
|
||||
|
||||
// Create swapchain
|
||||
let (swapchain_desc, swapchain) = Self::create_swapchain(&adapter, &device, &surface, window.inner_size());
|
||||
|
||||
// Cam
|
||||
let aspect = swapchain_desc.width as f32 / swapchain_desc.height as f32;
|
||||
let camera = Camera::new(aspect, 60.0);
|
||||
let mut uniforms = Uniforms::new();
|
||||
uniforms.update(&camera);
|
||||
|
||||
// Buffers
|
||||
let vertex_buffer = Self::create_buffer(&device, wgpu::BufferUsage::VERTEX, bytemuck::cast_slice(VERTICES));
|
||||
let index_buffer = Self::create_buffer(&device, wgpu::BufferUsage::INDEX, bytemuck::cast_slice(INDICES));
|
||||
let uniform_buffer = Self::create_buffer(&device, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, bytemuck::cast_slice(&[uniforms]));
|
||||
|
||||
// Load image
|
||||
let tex = Texture::from_file(&device, &queue, "./assets/rick.png");
|
||||
let (bind_group_layout, bind_group) = Self::create_bind_group(&device, &tex);
|
||||
let (uniform_bind_group_layout, uniform_bind_group) = Self::create_uniform_bind_group(&device, &uniform_buffer);
|
||||
|
||||
// Pipeline
|
||||
let bind_groups = [&bind_group_layout, &uniform_bind_group_layout];
|
||||
let pipeline = Self::create_pipeline(&device, &swapchain_desc, &bind_groups);
|
||||
|
||||
// Save values in app
|
||||
println!("Initialized");
|
||||
Self { surface, device, queue, swapchain_desc, swapchain, pipeline, vertex_buffer, index_buffer, uniform_buffer, bind_group, uniform_bind_group, camera, uniforms }
|
||||
}
|
||||
|
||||
pub fn resize(&mut self, new_size: Option<PhysicalSize<u32>>) {
|
||||
if let Some(size) = new_size {
|
||||
// Minimized or manually resized to 0
|
||||
if size.width == 0 || size.height == 0 { return }
|
||||
// Recreate swapchain
|
||||
self.swapchain_desc.width = size.width;
|
||||
self.swapchain_desc.height = size.height;
|
||||
// Update camera
|
||||
self.camera.set_aspect(size.width as f32 / size.height as f32);
|
||||
}
|
||||
// Recreate swapchain
|
||||
self.swapchain = self.device.create_swap_chain(&self.surface, &self.swapchain_desc);
|
||||
}
|
||||
|
||||
pub fn render(&mut self) -> Result<(), wgpu::SwapChainError> {
|
||||
|
||||
// Update uniform buffer
|
||||
self.uniforms.update(&self.camera);
|
||||
self.queue.write_buffer(&self.uniform_buffer, 0, bytemuck::cast_slice(&[self.uniforms]));
|
||||
|
||||
// Get next frame to render to
|
||||
let frame = self.swapchain.get_current_frame()?.output;
|
||||
|
||||
// Create encoder that will build command buffer for us
|
||||
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"),});
|
||||
|
||||
// Create render pass
|
||||
{
|
||||
let ops = wgpu::Operations {
|
||||
// Clear command
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color {r: 0.1, g: 0.2, b: 0.3, a: 1.0,}),
|
||||
// Store command
|
||||
store: true,
|
||||
};
|
||||
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("Render Pass"),
|
||||
color_attachments: &[ wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, ops } ],
|
||||
depth_stencil_attachment: None,
|
||||
});
|
||||
|
||||
// Data
|
||||
render_pass.set_pipeline(&self.pipeline);
|
||||
render_pass.set_bind_group(0, &self.bind_group, &[]);
|
||||
render_pass.set_bind_group(1, &self.uniform_bind_group, &[]);
|
||||
// Vertices and indices
|
||||
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
||||
render_pass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint16);
|
||||
render_pass.draw_indexed(0..(INDICES.len() as u32), 0, 0..1);
|
||||
}
|
||||
|
||||
// Submit encoder (command buffer)
|
||||
self.queue.submit(std::iter::once(encoder.finish()));
|
||||
|
||||
// Return ok
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use std::path::Path;
|
||||
use image::GenericImageView;
|
||||
|
||||
pub struct Texture {
|
||||
pub texture: wgpu::Texture,
|
||||
pub view: wgpu::TextureView,
|
||||
pub sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
impl Texture {
|
||||
|
||||
pub fn from_file(device: &wgpu::Device, queue: &wgpu::Queue, str_path: &str) -> Self {
|
||||
let img_path = Path::new(str_path);
|
||||
let img = image::open(img_path).unwrap();
|
||||
Self::from_image(&device, &queue, &img)
|
||||
}
|
||||
|
||||
pub fn from_image(device: &wgpu::Device, queue: &wgpu::Queue, img: &image::DynamicImage) -> Self {
|
||||
// Data from image
|
||||
let img_dim = img.dimensions();
|
||||
let img_data = img.as_rgba8().unwrap();
|
||||
|
||||
// Create texture on device
|
||||
let texture_size = wgpu::Extent3d { width: img_dim.0, height: img_dim.1, depth: 1, };
|
||||
let texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
size: texture_size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8UnormSrgb,
|
||||
usage: wgpu::TextureUsage::SAMPLED | wgpu::TextureUsage::COPY_DST,
|
||||
label: None,
|
||||
});
|
||||
|
||||
// Write texture to memory
|
||||
queue.write_texture(
|
||||
wgpu::TextureCopyView { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO },
|
||||
img_data,
|
||||
wgpu::TextureDataLayout { offset: 0, bytes_per_row: 4 * img_dim.0, rows_per_image: img_dim.1 },
|
||||
texture_size,
|
||||
);
|
||||
|
||||
// Create view and sampler
|
||||
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let sampler = device.create_sampler(
|
||||
&wgpu::SamplerDescriptor {
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
//mag_filter: wgpu::FilterMode::Linear,
|
||||
mag_filter: wgpu::FilterMode::Nearest,
|
||||
min_filter: wgpu::FilterMode::Nearest,
|
||||
mipmap_filter: wgpu::FilterMode::Nearest,
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
Self { texture, view, sampler }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
use cgmath::SquareMatrix;
|
||||
use super::camera::Camera;
|
||||
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Default, Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Uniforms {
|
||||
view_inv: [[f32; 4]; 4],
|
||||
proj_inv: [[f32; 4]; 4],
|
||||
cam_pos: [f32; 3]
|
||||
}
|
||||
|
||||
impl Uniforms {
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn update(&mut self, camera: &Camera) {
|
||||
self.view_inv = camera.view_matrix().invert().unwrap().into();
|
||||
self.proj_inv = camera.proj_matrix().invert().unwrap().into();
|
||||
self.cam_pos = camera.position.into();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
|
||||
|
||||
#[repr(C)]
|
||||
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct Vertex {
|
||||
pub position: [f32; 3],
|
||||
pub uv: [f32; 2],
|
||||
}
|
||||
|
||||
impl Vertex {
|
||||
pub fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
|
||||
wgpu::VertexBufferLayout {
|
||||
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
||||
step_mode: wgpu::InputStepMode::Vertex,
|
||||
attributes: &[
|
||||
// position
|
||||
wgpu::VertexAttribute {
|
||||
offset: 0,
|
||||
shader_location: 0,
|
||||
format: wgpu::VertexFormat::Float3,
|
||||
},
|
||||
// color
|
||||
wgpu::VertexAttribute {
|
||||
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
||||
shader_location: 1,
|
||||
format: wgpu::VertexFormat::Float2,
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user