431 lines
14 KiB
Rust
431 lines
14 KiB
Rust
use std::borrow::Cow;
|
|
use std::sync::Arc;
|
|
use std::time::Instant;
|
|
|
|
use cgmath::{Matrix4, Point3, Rad, Vector3, perspective};
|
|
use futures::executor::block_on;
|
|
use thiserror::Error;
|
|
use wgpu::util::DeviceExt;
|
|
use winit::window::Window;
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum ContextError {
|
|
#[error("Failed to create WGPU surface: {0}")]
|
|
SurfaceCreationFailure(#[from] wgpu::CreateSurfaceError),
|
|
}
|
|
|
|
const CUBE_SHADER: &str = r#"
|
|
struct Uniforms {
|
|
mvp: mat4x4<f32>,
|
|
};
|
|
|
|
@group(0) @binding(0)
|
|
var<uniform> u: Uniforms;
|
|
|
|
struct VertexInput {
|
|
@location(0) position: vec3<f32>,
|
|
@location(1) normal: vec3<f32>,
|
|
};
|
|
|
|
struct VertexOutput {
|
|
@builtin(position) clip_position: vec4<f32>,
|
|
@location(0) normal: vec3<f32>,
|
|
};
|
|
|
|
@vertex
|
|
fn vs_main(input: VertexInput) -> VertexOutput {
|
|
var output: VertexOutput;
|
|
output.clip_position = u.mvp * vec4<f32>(input.position, 1.0);
|
|
output.normal = input.normal;
|
|
return output;
|
|
}
|
|
|
|
@fragment
|
|
fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
|
|
let light_dir = normalize(vec3<f32>(0.5, 1.0, 0.5));
|
|
let brightness = clamp(dot(normalize(input.normal), light_dir), 0.0, 1.0);
|
|
return vec4<f32>(0.7 * brightness, 0.7 * brightness, 0.9 * brightness, 1.0);
|
|
}
|
|
"#;
|
|
|
|
#[repr(C)]
|
|
#[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
|
|
struct Vertex {
|
|
position: [f32; 3],
|
|
normal: [f32; 3],
|
|
}
|
|
|
|
impl Vertex {
|
|
const ATTRIBS: [wgpu::VertexAttribute; 2] = [
|
|
wgpu::VertexAttribute {
|
|
offset: 0,
|
|
shader_location: 0,
|
|
format: wgpu::VertexFormat::Float32x3,
|
|
},
|
|
wgpu::VertexAttribute {
|
|
offset: std::mem::size_of::<[f32; 3]>() as wgpu::BufferAddress,
|
|
shader_location: 1,
|
|
format: wgpu::VertexFormat::Float32x3,
|
|
},
|
|
];
|
|
|
|
fn desc<'a>() -> wgpu::VertexBufferLayout<'a> {
|
|
wgpu::VertexBufferLayout {
|
|
array_stride: std::mem::size_of::<Vertex>() as wgpu::BufferAddress,
|
|
step_mode: wgpu::VertexStepMode::Vertex,
|
|
attributes: &Self::ATTRIBS,
|
|
}
|
|
}
|
|
}
|
|
|
|
const CUBE_VERTICES: &[Vertex] = &[
|
|
Vertex {
|
|
position: [-0.5, -0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, 0.5],
|
|
normal: [0.0, 0.0, 1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, -0.5],
|
|
normal: [0.0, 0.0, -1.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, 0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, -0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, -0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, -0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, 0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, 0.5],
|
|
normal: [1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, -0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, 0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, 0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, 0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, -0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, -0.5],
|
|
normal: [-1.0, 0.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, 0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, 0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, -0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, 0.5, -0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, -0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, 0.5, 0.5],
|
|
normal: [0.0, 1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, -0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, -0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, 0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [0.5, -0.5, 0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, 0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
Vertex {
|
|
position: [-0.5, -0.5, -0.5],
|
|
normal: [0.0, -1.0, 0.0],
|
|
},
|
|
];
|
|
|
|
pub struct WgpuCtx<'window> {
|
|
device: wgpu::Device,
|
|
queue: wgpu::Queue,
|
|
surface: wgpu::Surface<'window>,
|
|
surface_config: wgpu::SurfaceConfiguration,
|
|
adapter: wgpu::Adapter,
|
|
render_pipeline: wgpu::RenderPipeline,
|
|
uniform_buffer: wgpu::Buffer,
|
|
vertex_buffer: wgpu::Buffer,
|
|
start_time: Instant,
|
|
}
|
|
|
|
impl<'window> WgpuCtx<'window> {
|
|
pub async fn new(window: Arc<Window>) -> Result<WgpuCtx<'window>, ContextError> {
|
|
let instance = wgpu::Instance::default();
|
|
let surface = instance.create_surface(Arc::clone(&window))?;
|
|
let adapter = instance
|
|
.request_adapter(&wgpu::RequestAdapterOptions {
|
|
power_preference: wgpu::PowerPreference::default(),
|
|
force_fallback_adapter: false,
|
|
compatible_surface: Some(&surface),
|
|
})
|
|
.await
|
|
.expect("Failed to obtain render adapter");
|
|
let (device, queue) = adapter
|
|
.request_device(
|
|
&wgpu::DeviceDescriptor {
|
|
label: None,
|
|
required_features: wgpu::Features::empty(),
|
|
required_limits: wgpu::Limits::downlevel_webgl2_defaults()
|
|
.using_resolution(adapter.limits()),
|
|
memory_hints: wgpu::MemoryHints::Performance,
|
|
},
|
|
None,
|
|
)
|
|
.await
|
|
.expect("Failed to create rendering device");
|
|
let size = window.inner_size();
|
|
let width = size.width.max(1);
|
|
let height = size.height.max(1);
|
|
let surface_config = surface.get_default_config(&adapter, width, height).unwrap();
|
|
surface.configure(&device, &surface_config);
|
|
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
|
label: Some("Uniform Buffer"),
|
|
size: 64,
|
|
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
|
mapped_at_creation: false,
|
|
});
|
|
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
|
label: Some("Cube Vertex Buffer"),
|
|
contents: bytemuck::cast_slice(CUBE_VERTICES),
|
|
usage: wgpu::BufferUsages::VERTEX,
|
|
});
|
|
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
|
label: Some("Cube Shader"),
|
|
source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(CUBE_SHADER)),
|
|
});
|
|
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
|
label: Some("Uniform Bind Group Layout"),
|
|
entries: &[wgpu::BindGroupLayoutEntry {
|
|
binding: 0,
|
|
visibility: wgpu::ShaderStages::VERTEX,
|
|
ty: wgpu::BindingType::Buffer {
|
|
ty: wgpu::BufferBindingType::Uniform,
|
|
has_dynamic_offset: false,
|
|
min_binding_size: wgpu::BufferSize::new(64),
|
|
},
|
|
count: None,
|
|
}],
|
|
});
|
|
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
|
label: Some("Cube Pipeline Layout"),
|
|
bind_group_layouts: &[&bind_group_layout],
|
|
push_constant_ranges: &[],
|
|
});
|
|
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
|
label: Some("Cube Render Pipeline"),
|
|
layout: Some(&pipeline_layout),
|
|
vertex: wgpu::VertexState {
|
|
module: &shader,
|
|
entry_point: Some("vs_main"),
|
|
buffers: &[Vertex::desc()],
|
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
|
},
|
|
fragment: Some(wgpu::FragmentState {
|
|
module: &shader,
|
|
entry_point: Some("fs_main"),
|
|
targets: &[Some(wgpu::ColorTargetState {
|
|
format: surface_config.format,
|
|
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
|
|
write_mask: wgpu::ColorWrites::ALL,
|
|
})],
|
|
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
|
}),
|
|
primitive: wgpu::PrimitiveState {
|
|
topology: wgpu::PrimitiveTopology::TriangleList,
|
|
strip_index_format: None,
|
|
front_face: wgpu::FrontFace::Ccw,
|
|
cull_mode: Some(wgpu::Face::Back),
|
|
polygon_mode: wgpu::PolygonMode::Fill,
|
|
unclipped_depth: false,
|
|
conservative: false,
|
|
},
|
|
depth_stencil: None,
|
|
multisample: wgpu::MultisampleState {
|
|
count: 1,
|
|
mask: !0,
|
|
alpha_to_coverage_enabled: false,
|
|
},
|
|
multiview: None,
|
|
cache: None,
|
|
});
|
|
Ok(WgpuCtx {
|
|
device,
|
|
queue,
|
|
surface,
|
|
surface_config,
|
|
adapter,
|
|
render_pipeline,
|
|
uniform_buffer,
|
|
vertex_buffer,
|
|
start_time: Instant::now(),
|
|
})
|
|
}
|
|
|
|
pub fn new_blocking(window: Arc<Window>) -> Result<WgpuCtx<'window>, ContextError> {
|
|
block_on(Self::new(window))
|
|
}
|
|
|
|
pub fn resize(&mut self, new_size: (u32, u32)) {
|
|
let (width, height) = new_size;
|
|
self.surface_config.width = width.max(1);
|
|
self.surface_config.height = height.max(1);
|
|
self.surface.configure(&self.device, &self.surface_config);
|
|
}
|
|
|
|
pub fn draw(&mut self) {
|
|
let elapsed = self.start_time.elapsed().as_secs_f32();
|
|
let model = Matrix4::from_angle_x(Rad(elapsed)) * Matrix4::from_angle_y(Rad(elapsed));
|
|
let view = Matrix4::look_at_rh(
|
|
Point3::new(0.0, 0.0, 3.0),
|
|
Point3::new(0.0, 0.0, 0.0),
|
|
Vector3::unit_y(),
|
|
);
|
|
let aspect = self.surface_config.width as f32 / self.surface_config.height as f32;
|
|
let proj = perspective(Rad(std::f32::consts::FRAC_PI_4), aspect, 0.1, 100.0);
|
|
let mvp = proj * view * model;
|
|
let mvp_array: [[f32; 4]; 4] = [
|
|
[mvp.x.x, mvp.x.y, mvp.x.z, mvp.x.w],
|
|
[mvp.y.x, mvp.y.y, mvp.y.z, mvp.y.w],
|
|
[mvp.z.x, mvp.z.y, mvp.z.z, mvp.z.w],
|
|
[mvp.w.x, mvp.w.y, mvp.w.z, mvp.w.w],
|
|
];
|
|
self.queue
|
|
.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&mvp_array));
|
|
let surface_texture = self
|
|
.surface
|
|
.get_current_texture()
|
|
.expect("Failed to get surface texture");
|
|
let view_texture = surface_texture
|
|
.texture
|
|
.create_view(&wgpu::TextureViewDescriptor::default());
|
|
let mut encoder = self
|
|
.device
|
|
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
|
label: Some("Cube Command Encoder"),
|
|
});
|
|
{
|
|
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
|
label: Some("Cube Render Pass"),
|
|
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
|
view: &view_texture,
|
|
resolve_target: None,
|
|
ops: wgpu::Operations {
|
|
load: wgpu::LoadOp::Clear(wgpu::Color {
|
|
r: 0.1,
|
|
g: 0.1,
|
|
b: 0.1,
|
|
a: 1.0,
|
|
}),
|
|
store: wgpu::StoreOp::Store,
|
|
},
|
|
})],
|
|
depth_stencil_attachment: None,
|
|
timestamp_writes: None,
|
|
occlusion_query_set: None,
|
|
});
|
|
render_pass.set_pipeline(&self.render_pipeline);
|
|
let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
|
|
label: Some("Uniform Bind Group"),
|
|
layout: &self.render_pipeline.get_bind_group_layout(0),
|
|
entries: &[wgpu::BindGroupEntry {
|
|
binding: 0,
|
|
resource: self.uniform_buffer.as_entire_binding(),
|
|
}],
|
|
});
|
|
render_pass.set_bind_group(0, &bind_group, &[]);
|
|
render_pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
|
|
render_pass.draw(0..36, 0..1);
|
|
}
|
|
self.queue.submit(Some(encoder.finish()));
|
|
surface_texture.present();
|
|
}
|
|
}
|