[oden] Sprites are rendered with instances

This commit is contained in:
John Doty 2023-08-24 22:43:23 -07:00
parent 20f6c8e878
commit 3f8e50cfc9
2 changed files with 143 additions and 66 deletions

View file

@ -44,6 +44,47 @@ impl Vertex {
} }
} }
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct SpriteInstance {
src_top_left: [f32; 2],
src_dims: [f32; 2],
dest_top_left: [f32; 2],
dest_dims: [f32; 2],
}
impl SpriteInstance {
fn desc() -> wgpu::VertexBufferLayout<'static> {
wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<SpriteInstance>() as wgpu::BufferAddress,
step_mode: wgpu::VertexStepMode::Instance,
attributes: &[
wgpu::VertexAttribute {
offset: 0,
shader_location: 5,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 2]>() as wgpu::BufferAddress,
shader_location: 6,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 4]>() as wgpu::BufferAddress,
shader_location: 7,
format: wgpu::VertexFormat::Float32x2,
},
wgpu::VertexAttribute {
offset: std::mem::size_of::<[f32; 6]>() as wgpu::BufferAddress,
shader_location: 8,
format: wgpu::VertexFormat::Float32x2,
},
],
}
}
}
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] #[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct ScreenUniforms { struct ScreenUniforms {
@ -59,10 +100,10 @@ impl ScreenUniforms {
} }
#[derive(Debug)] #[derive(Debug)]
struct VertexBuffer { struct VertexBuffer<T> {
buffer: wgpu::Buffer, buffer: wgpu::Buffer,
vec: Vec<Vertex>, vec: Vec<T>,
max_vertices: usize, capacity: usize,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
@ -132,6 +173,34 @@ impl WindowAndDevice {
} }
} }
// A little square of two triangles. Neat!
const SPRITE_VERTICES: &[Vertex] = &[
Vertex {
position: [0.0, 0.0, 0.0],
tex_coords: [0.0, 0.0],
},
Vertex {
position: [0.0, 1.0, 0.0],
tex_coords: [0.0, 1.0],
},
Vertex {
position: [1.0, 0.0, 0.0],
tex_coords: [1.0, 0.0],
},
Vertex {
position: [0.0, 1.0, 0.0],
tex_coords: [0.0, 1.0],
},
Vertex {
position: [1.0, 1.0, 0.0],
tex_coords: [1.0, 1.0],
},
Vertex {
position: [1.0, 0.0, 0.0],
tex_coords: [1.0, 0.0],
},
];
struct State { struct State {
surface: wgpu::Surface, surface: wgpu::Surface,
device: wgpu::Device, device: wgpu::Device,
@ -141,8 +210,9 @@ struct State {
window: Window, window: Window,
render_pipeline: wgpu::RenderPipeline, render_pipeline: wgpu::RenderPipeline,
vertex_buffers: Vec<VertexBuffer>, sprite_vertex_buffer: wgpu::Buffer,
next_free_vertex_buffer: usize, sprite_instance_buffers: Vec<VertexBuffer<SpriteInstance>>,
next_free_sprite_instance_buffer: usize,
sprite_bind_group_layout: wgpu::BindGroupLayout, sprite_bind_group_layout: wgpu::BindGroupLayout,
sprite_textures: HashMap<u32, wgpu::BindGroup>, sprite_textures: HashMap<u32, wgpu::BindGroup>,
@ -264,7 +334,7 @@ impl State {
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &sprite_shader, module: &sprite_shader,
entry_point: "vs_main", entry_point: "vs_main",
buffers: &[Vertex::desc()], buffers: &[Vertex::desc(), SpriteInstance::desc()],
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
module: &sprite_shader, module: &sprite_shader,
@ -296,6 +366,12 @@ impl State {
multiview: None, multiview: None,
}); });
let sprite_vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Sprite Vertex Buffer"),
contents: bytemuck::cast_slice(SPRITE_VERTICES),
usage: wgpu::BufferUsages::VERTEX,
});
Self { Self {
window: hardware.window, window: hardware.window,
surface: hardware.surface, surface: hardware.surface,
@ -304,8 +380,10 @@ impl State {
config, config,
size, size,
render_pipeline: sprite_pipeline, render_pipeline: sprite_pipeline,
vertex_buffers: Vec::new(),
next_free_vertex_buffer: 0, sprite_vertex_buffer,
sprite_instance_buffers: Vec::new(),
next_free_sprite_instance_buffer: 0,
sprite_bind_group_layout, sprite_bind_group_layout,
sprite_textures: HashMap::new(), sprite_textures: HashMap::new(),
@ -345,7 +423,7 @@ impl State {
let _span = span!("context render"); let _span = span!("context render");
// Reset vertex buffers. // Reset vertex buffers.
self.next_free_vertex_buffer = 0; self.next_free_sprite_instance_buffer = 0;
let mut builder = FrameBuilder::new(self)?; let mut builder = FrameBuilder::new(self)?;
for command in commands { for command in commands {
@ -426,44 +504,50 @@ impl State {
} }
fn new_vertex_buffer(&mut self) -> VertexBufferHandle { fn new_vertex_buffer(&mut self) -> VertexBufferHandle {
if self.next_free_vertex_buffer >= self.vertex_buffers.len() { if self.next_free_sprite_instance_buffer >= self.sprite_instance_buffers.len() {
let max_vertices: usize = 4096; let max_sprites: usize = 4096;
let buffer = self.device.create_buffer(&wgpu::BufferDescriptor { let buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Vertex Buffer"), label: Some("Sprite Instance Buffer"),
size: (max_vertices * std::mem::size_of::<Vertex>()) size: (max_sprites * std::mem::size_of::<SpriteInstance>())
.try_into() .try_into()
.unwrap(), .unwrap(),
mapped_at_creation: false, mapped_at_creation: false,
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
}); });
self.vertex_buffers.push(VertexBuffer { self.sprite_instance_buffers.push(VertexBuffer {
buffer, buffer,
max_vertices, capacity: max_sprites,
vec: Vec::with_capacity(max_vertices), vec: Vec::with_capacity(max_sprites),
}); });
} }
let index = self.next_free_vertex_buffer; let index = self.next_free_sprite_instance_buffer;
self.next_free_vertex_buffer += 1; self.next_free_sprite_instance_buffer += 1;
let vb = &mut self.vertex_buffers[index]; let vb = &mut self.sprite_instance_buffers[index];
vb.vec.clear(); vb.vec.clear();
VertexBufferHandle { VertexBufferHandle {
index, index,
capacity: vb.max_vertices, capacity: vb.capacity,
} }
} }
fn get_vertex_buffer(&self, handle: &VertexBufferHandle) -> &VertexBuffer { fn get_sprite_instance_buffer(
&self.vertex_buffers[handle.index] &self,
handle: &VertexBufferHandle,
) -> &VertexBuffer<SpriteInstance> {
&self.sprite_instance_buffers[handle.index]
} }
fn get_vertex_buffer_mut(&mut self, handle: &VertexBufferHandle) -> &mut VertexBuffer { fn get_sprite_instance_buffer_mut(
&mut self.vertex_buffers[handle.index] &mut self,
handle: &VertexBufferHandle,
) -> &mut VertexBuffer<SpriteInstance> {
&mut self.sprite_instance_buffers[handle.index]
} }
fn copy_vertex_buffers(&mut self) { fn copy_instance_buffers(&mut self) {
for i in 0..self.next_free_vertex_buffer { for i in 0..self.next_free_sprite_instance_buffer {
let vb = &self.vertex_buffers[i]; let vb = &self.sprite_instance_buffers[i];
self.queue self.queue
.write_buffer(&vb.buffer, 0, bytemuck::cast_slice(&vb.vec)); .write_buffer(&vb.buffer, 0, bytemuck::cast_slice(&vb.vec));
} }
@ -503,6 +587,7 @@ impl DrawCall {
} }
pub fn allocate_capacity(&mut self, capacity: u32) -> Option<VertexBufferHandle> { pub fn allocate_capacity(&mut self, capacity: u32) -> Option<VertexBufferHandle> {
// TODO: FIX: CAPACITY == 1 ALWAYS??
if self.vertex_buffer.capacity >= (self.draw_end + capacity) as usize { if self.vertex_buffer.capacity >= (self.draw_end + capacity) as usize {
self.draw_end += capacity; self.draw_end += capacity;
Some(self.vertex_buffer.clone()) Some(self.vertex_buffer.clone())
@ -521,10 +606,15 @@ impl DrawCall {
let bind_group = state.sprite_textures.get(&texture_id).unwrap(); let bind_group = state.sprite_textures.get(&texture_id).unwrap();
pass.set_bind_group(0, bind_group, &[]); pass.set_bind_group(0, bind_group, &[]);
let vb = state.get_vertex_buffer(&self.vertex_buffer); let vb = state.get_sprite_instance_buffer(&self.vertex_buffer);
pass.set_bind_group(1, &state.screen_uniform_bind_group, &[]); pass.set_bind_group(1, &state.screen_uniform_bind_group, &[]);
pass.set_vertex_buffer(0, vb.buffer.slice(..)); pass.set_vertex_buffer(0, state.sprite_vertex_buffer.slice(..));
pass.draw(self.draw_start..self.draw_end, 0..1); pass.set_vertex_buffer(1, vb.buffer.slice(..));
pass.draw(
0..SPRITE_VERTICES.len() as u32,
self.draw_start..self.draw_end,
);
} }
} }
} }
@ -576,7 +666,7 @@ impl<'a> FrameBuilder<'a> {
builder.flush(); builder.flush();
// At this point the state needs to copy the vertex buffers we know about. // At this point the state needs to copy the vertex buffers we know about.
builder.state.copy_vertex_buffers(); builder.state.copy_instance_buffers();
// Submit will accept anything that implements IntoIter // Submit will accept anything that implements IntoIter
builder builder
@ -665,48 +755,28 @@ impl<'a> FrameBuilder<'a> {
} }
} }
fn get_vertex_buffer(&mut self, required_capacity: u32) -> &mut VertexBuffer { fn get_sprite_instance_buffer(&mut self) -> &mut VertexBuffer<SpriteInstance> {
match self.draw_calls.last_mut() { match self.draw_calls.last_mut() {
Some(call) => match call.allocate_capacity(required_capacity) { Some(call) => match call.allocate_capacity(1) {
Some(vb) => return self.state.get_vertex_buffer_mut(&vb), Some(vb) => return self.state.get_sprite_instance_buffer_mut(&vb),
None => {} None => {}
}, },
None => {} None => {}
}; };
let mut call = DrawCall::new(self.state.new_vertex_buffer(), 0); let mut call = DrawCall::new(self.state.new_vertex_buffer(), 0);
let vb = call.allocate_capacity(required_capacity).unwrap(); let vb = call.allocate_capacity(1).unwrap();
self.draw_calls.push(call); self.draw_calls.push(call);
self.state.get_vertex_buffer_mut(&vb) self.state.get_sprite_instance_buffer_mut(&vb)
} }
fn push_sprite(&mut self, sc: script::graphics::SpriteCommand) { fn push_sprite(&mut self, sc: script::graphics::SpriteCommand) {
let vertex_buffer = self.get_vertex_buffer(6); let vertex_buffer = self.get_sprite_instance_buffer();
vertex_buffer.vec.push(SpriteInstance {
vertex_buffer.vec.push(Vertex { src_top_left: [sc.u, sc.v],
position: [sc.x, sc.y, 0.0], src_dims: [sc.sw, sc.sh],
tex_coords: [sc.u, sc.v], dest_top_left: [sc.x, sc.y],
}); dest_dims: [sc.w, sc.h],
vertex_buffer.vec.push(Vertex {
position: [sc.x, sc.y + sc.h, 0.0],
tex_coords: [sc.u, sc.v + sc.sh],
});
vertex_buffer.vec.push(Vertex {
position: [sc.x + sc.w, sc.y, 0.0],
tex_coords: [sc.u + sc.sw, sc.v],
});
vertex_buffer.vec.push(Vertex {
position: [sc.x, sc.y + sc.h, 0.0],
tex_coords: [sc.u, sc.v + sc.sh],
});
vertex_buffer.vec.push(Vertex {
position: [sc.x + sc.w, sc.y + sc.h, 0.0],
tex_coords: [sc.u + sc.sw, sc.v + sc.sh],
});
vertex_buffer.vec.push(Vertex {
position: [sc.x + sc.w, sc.y, 0.0],
tex_coords: [sc.u + sc.sw, sc.v],
}); });
} }

View file

@ -11,6 +11,13 @@ struct VertexInput {
@location(1) tex_coords : vec2<f32>, @location(1) tex_coords : vec2<f32>,
}; };
struct InstanceInput {
@location(5) src_top_left: vec2<f32>,
@location(6) src_dims: vec2<f32>,
@location(7) dest_top_left: vec2<f32>,
@location(8) dest_dims: vec2<f32>,
};
struct VertexOutput { struct VertexOutput {
@builtin(position) clip_position : vec4<f32>, @builtin(position) clip_position : vec4<f32>,
@location(0) tex_coords : vec2<f32>, @location(0) tex_coords : vec2<f32>,
@ -18,9 +25,9 @@ struct VertexOutput {
const RES = vec2f(320.0, 240.0); // The logical resolution of the screen. const RES = vec2f(320.0, 240.0); // The logical resolution of the screen.
@vertex fn vs_main(model : VertexInput)->VertexOutput { @vertex fn vs_main(vertex : VertexInput, instance : InstanceInput)->VertexOutput {
var out : VertexOutput; var out : VertexOutput;
out.tex_coords = model.tex_coords; out.tex_coords = instance.src_top_left + (vertex.tex_coords * instance.src_dims);
let RES_AR = RES.x / RES.y; // The aspect ratio of the logical screen. let RES_AR = RES.x / RES.y; // The aspect ratio of the logical screen.
@ -41,12 +48,12 @@ const RES = vec2f(320.0, 240.0); // The logical resolution of the screen.
var new_logical_resolution = RES + nudge; var new_logical_resolution = RES + nudge;
// Now we can convert the incoming position to clip space, in the new screen. // Now we can convert the incoming position to clip space, in the new screen.
let in_pos = vec2f(model.position.x, model.position.y); let in_pos = instance.dest_top_left + (vec2f(vertex.position.x, vertex.position.y) * instance.dest_dims);
let centered = in_pos + (nudge / 2.0); let centered = in_pos + (nudge / 2.0);
var position = (2.0 * centered / new_logical_resolution) - 1.0; var position = (2.0 * centered / new_logical_resolution) - 1.0;
position.y = -position.y; position.y = -position.y;
out.clip_position = vec4f(position.x, position.y, model.position.z, 1.0); out.clip_position = vec4f(position.x, position.y, vertex.position.z, 1.0);
return out; return out;
} }