Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

large backend performance increase: combined upload buffer + per-texgen vertex packing

Layle2a275680dc86
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 8c45fcc..f2adf22 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,8 +1,8 @@
use crate::pipeline::{FullPipelineKey, PipelineKey};
use crate::shader_specialization::{self, ShaderKey};
use crate::{
- BindGroupCacheKey, DRAW_UNIFORMS_SIZE, DrawUniforms, FRAME_UNIFORMS_SIZE, FrameUniforms, GpuVertex, GxRenderer,
- SamplerKey, helpers,
+ BindGroupCacheKey, DRAW_UNIFORMS_SIZE, DrawUniforms, FRAME_UNIFORMS_SIZE, FrameUniforms, GxRenderer, SamplerKey,
+ helpers,
};
use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
use gecko::flipper::gx::texture::CopyFormat;
@@ -78,9 +78,48 @@ impl GxRenderer {
}
}
- /// Process a single [`GxAction`]. Called by the worker thread for each
- /// action received from the channel. Draws are accumulated and flushed
- /// lazily when a non-draw action arrives.
+ /// Replace the renderer's vertex scratch with `new_scratch`, returning the
+ /// previous buffer. For sinks (like web) that decouple vertex appending
+ /// from action processing vertices are collected in a shared `Vec`
+ /// while actions are queued, then both are drained together on the main
+ /// thread, at which point the drained scratch must become the renderer's
+ /// `scratch_vertices` so each `Draw`'s `base_vertex` indexes correctly.
+ pub fn replace_vertex_scratch(
+ &mut self,
+ new_scratch: Vec<gecko::host::DrawVertex>,
+ ) -> Vec<gecko::host::DrawVertex> {
+ std::mem::replace(&mut self.scratch_vertices, new_scratch)
+ }
+
+ /// Wrapper around [`Self::process_action`] for sinks that wrap a
+ /// `GxRenderer` in a `Mutex` (and therefore can't expose this renderer's
+ /// `scratch_vertices` directly to the gecko side via the `RenderSink`
+ /// trait). Maintains the invariant that `external_scratch` and
+ /// `self.scratch_vertices` stay length-synced across `exec` calls: any
+ /// new vertices appended to `external_scratch` since the last sync are
+ /// brought into `self.scratch_vertices` before processing the action,
+ /// and if `process_action` triggers a flush that clears the renderer's
+ /// scratch, `external_scratch` is truncated to match.
+ pub fn process_action_with_external_scratch(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ action: &GxAction,
+ external_scratch: &mut Vec<gecko::host::DrawVertex>,
+ ) {
+ if external_scratch.len() > self.scratch_vertices.len() {
+ let start = self.scratch_vertices.len();
+ self.scratch_vertices.extend_from_slice(&external_scratch[start..]);
+ }
+ self.process_action(device, queue, action);
+ if self.scratch_vertices.len() < external_scratch.len() {
+ external_scratch.truncate(self.scratch_vertices.len());
+ }
+ }
+
+ /// Process a single [`GxAction`]. Called inline on the emu thread by
+ /// [`InlineSink::exec`]. Draws are accumulated and flushed lazily when a
+ /// non-draw action arrives.
pub fn process_action(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, action: &GxAction) {
let draw_stride = self.draw_uniform_stride as usize;
let draw_struct_size = DRAW_UNIFORMS_SIZE.get() as usize;
@@ -227,7 +266,7 @@ impl GxRenderer {
};
if !self.pipeline_cache.contains_key(&full_key) {
let module = &self.shader_cache[&shader_key];
- let pipeline = self.create_pipeline(device, module, &pipeline_key);
+ let pipeline = self.create_pipeline(device, module, &full_key);
self.pipeline_cache.insert(full_key, pipeline);
}
@@ -310,8 +349,24 @@ impl GxRenderer {
#[cfg(feature = "renderdoc-capture")]
self.draw_primitives.push(draw.primitive);
- self.scratch_draws
- .push((first_vertex, vertex_count, first_index, index_count));
+ // Compute packed vertex stride/offset for this draw. Stride
+ // matches the WESL `VsIn` layout gated by
+ // `TEXCOORD_N_ENABLED`: 5 fixed attrs (68b) + N texcoord
+ // attrs (12 byteroos each).
+ let stride = 68 + 12 * shader_key.active_texcoords as u32;
+ let packed_byte_offset = self
+ .scratch_draws
+ .last()
+ .map(|d| d.packed_vertex_byte_offset + d.vertex_count * d.packed_vertex_stride)
+ .unwrap_or(0);
+ self.scratch_draws.push(crate::DrawRecord {
+ src_vertex_index: first_vertex,
+ vertex_count,
+ first_index,
+ index_count,
+ packed_vertex_byte_offset: packed_byte_offset,
+ packed_vertex_stride: stride,
+ });
}
GxAction::CopyXfb {
@@ -501,16 +556,16 @@ impl GxRenderer {
0 => wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.frame_uniform_buffer,
- offset: 0,
+ buffer: &self.draw_buffer,
+ offset: self.draw_buffer_layout.frame_offset,
size: Some(FRAME_UNIFORMS_SIZE),
}),
},
1 => wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
- buffer: &self.draw_uniform_buffer,
- offset: 0,
+ buffer: &self.draw_buffer,
+ offset: self.draw_buffer_layout.draw_offset,
size: Some(DRAW_UNIFORMS_SIZE),
}),
},
@@ -589,7 +644,7 @@ impl GxRenderer {
timestamp_writes: None,
multiview_mask: None,
});
- rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+ let vertex_section_off = self.draw_buffer_layout.vertex_offset;
#[cfg(feature = "renderdoc-capture")]
{
if needs_initial_clear {
@@ -604,15 +659,37 @@ impl GxRenderer {
}
}
- rpass.set_index_buffer(self.index_buffer.slice(..), wgpu::IndexFormat::Uint32);
+ let index_used = (self.scratch_indices.len() * std::mem::size_of::<u32>()) as u64;
+ let index_off = self.draw_buffer_layout.index_offset;
+ rpass.set_index_buffer(
+ self.draw_buffer.slice(index_off..index_off + index_used),
+ wgpu::IndexFormat::Uint32,
+ );
let mut last_pipeline_ptr: *const wgpu::RenderPipeline = std::ptr::null();
+ let mut last_vertex_slice: Option<(u64, u64)> = None;
let mut last_viewport: Option<(f32, f32, f32, f32, f32, f32)> = None;
let mut last_scissor: Option<(u32, u32, u32, u32)> = None;
-
- for (index, (first_vertex, vertex_count, first_index, index_count)) in
- self.scratch_draws.iter().copied().enumerate()
- {
+
+ for (index, draw) in self.scratch_draws.iter().copied().enumerate() {
+ let crate::DrawRecord {
+ vertex_count,
+ first_index,
+ index_count,
+ packed_vertex_byte_offset,
+ packed_vertex_stride,
+ src_vertex_index: _,
+ } = draw;
+
+ let first_vertex = 0u32;
+ let vertex_bytes = u64::from(vertex_count) * u64::from(packed_vertex_stride);
+ let vertex_slice_start = vertex_section_off + u64::from(packed_vertex_byte_offset);
+ let vertex_slice_end = vertex_slice_start + vertex_bytes;
+ if last_vertex_slice != Some((vertex_slice_start, vertex_slice_end)) {
+ rpass.set_vertex_buffer(0, self.draw_buffer.slice(vertex_slice_start..vertex_slice_end));
+ last_vertex_slice = Some((vertex_slice_start, vertex_slice_end));
+ }
+
#[cfg(feature = "renderdoc-capture")]
{
let primitive = self.draw_primitives[index];
@@ -686,7 +763,7 @@ impl GxRenderer {
rpass.set_scissor_rect(sc_x, sc_y, sc_w, sc_h);
last_scissor = Some(sc_tuple);
}
-
+
#[cfg(feature = "renderdoc-capture")]
{
let raster_marker = format!(
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 6a94d1a..77c591e 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -30,6 +30,32 @@ pub(crate) fn align_up(value: u64, alignment: u64) -> u64 {
(value + alignment - 1) & !(alignment - 1)
}
+pub(crate) fn compute_draw_buffer_layout(
+ uniform_alignment: u64,
+ frame_capacity: u64,
+ draw_capacity: u64,
+ vertex_capacity: u64,
+ index_capacity: u64,
+) -> DrawBufferLayout {
+ let frame_offset = 0;
+ let draw_offset = align_up(frame_offset + frame_capacity, uniform_alignment);
+ let vertex_offset = align_up(draw_offset + draw_capacity, uniform_alignment);
+ let index_offset = align_up(vertex_offset + vertex_capacity, 4);
+ let total_size = (index_offset + index_capacity).max(uniform_alignment);
+
+ DrawBufferLayout {
+ frame_offset,
+ frame_capacity,
+ draw_offset,
+ draw_capacity,
+ vertex_offset,
+ vertex_capacity,
+ index_offset,
+ index_capacity,
+ total_size,
+ }
+}
+
type SamplerKey = (WrapMode, WrapMode, MagFilter, MinFilter);
#[derive(Clone, PartialEq, Eq, Hash)]
@@ -116,21 +142,33 @@ impl EfbCopyEntry {
}
}
+/// Layout of [`GxRenderer::draw_buffer`]: a single backing wgpu buffer with
+/// usage `COPY_DST | UNIFORM | VERTEX | INDEX` that holds all per-frame
+/// upload data in four sections at fixed offsets.
+#[derive(Copy, Clone, Debug)]
+pub(crate) struct DrawBufferLayout {
+ pub(crate) frame_offset: u64,
+ pub(crate) frame_capacity: u64,
+ pub(crate) draw_offset: u64,
+ pub(crate) draw_capacity: u64,
+ pub(crate) vertex_offset: u64,
+ pub(crate) vertex_capacity: u64,
+ pub(crate) index_offset: u64,
+ pub(crate) index_capacity: u64,
+ pub(crate) total_size: u64,
+}
+
pub struct GxRenderer {
pub(crate) pipeline_cache: FxHashMap<FullPipelineKey, wgpu::RenderPipeline>,
pub(crate) shader_cache: FxHashMap<ShaderKey, wgpu::ShaderModule>,
pub(crate) pipeline_layout: wgpu::PipelineLayout,
pub(crate) surface_format: wgpu::TextureFormat,
pub(crate) bind_group_layout: wgpu::BindGroupLayout,
- pub(crate) frame_uniform_buffer: wgpu::Buffer,
- pub(crate) draw_uniform_buffer: wgpu::Buffer,
+ pub(crate) draw_buffer: wgpu::Buffer,
+ pub(crate) draw_buffer_layout: DrawBufferLayout,
+ pub(crate) uniform_alignment: u64,
pub(crate) draw_uniform_stride: u64,
pub(crate) draw_uniform_capacity: usize,
- pub(crate) vertex_buffer: wgpu::Buffer,
- pub(crate) vertex_capacity: usize,
- // Index buffers.
- pub(crate) index_buffer: wgpu::Buffer,
- pub(crate) index_buffer_capacity: usize,
pub(crate) scratch_indices: Vec<u32>,
// EFB: resolved (1x) color used for CopyXfb reads + texture binding.
pub(crate) efb_texture: wgpu::Texture,
@@ -157,11 +195,7 @@ pub struct GxRenderer {
pub(crate) efb_depth_writeback_target: Option<(wgpu::Texture, wgpu::TextureView)>,
pub(crate) fallback_view: wgpu::TextureView,
pub(crate) scratch_vertices: Vec<GpuVertex>,
- /// `(first_vertex, vertex_count, first_index, index_count)`. When
- /// `index_count == 0` the draw is non-indexed (input was Triangles,
- /// no expansion needed). Otherwise `draw_indexed` is used with
- /// `base_vertex = first_vertex`.
- pub(crate) scratch_draws: Vec<(u32, u32, u32, u32)>,
+ pub(crate) scratch_draws: Vec<DrawRecord>,
pub(crate) scratch_uniform_bytes: Vec<u8>,
pub(crate) bind_group_cache: FxHashMap<BindGroupCacheKey, wgpu::BindGroup>,
// Per-frame draw accumulation (persists across process_action calls,
@@ -213,6 +247,24 @@ pub struct GxRenderer {
pub(crate) pending_writebacks: Vec<PendingWriteback>,
}
+#[derive(Copy, Clone, Debug)]
+pub(crate) struct DrawRecord {
+ /// Index into [`GxRenderer::scratch_vertices`] (Vec<DrawVertex>) where
+ /// this draw's source vertices start. Used at upload time to pack each
+ /// vertex into the destination stride.
+ pub src_vertex_index: u32,
+ pub vertex_count: u32,
+ pub first_index: u32,
+ pub index_count: u32,
+ /// Byte offset of this draw's vertices inside the packed vertex
+ /// section of `draw_buffer` (relative to section start, not buffer
+ /// start). Used to compute the buffer slice for `set_vertex_buffer`.
+ pub packed_vertex_byte_offset: u32,
+ /// Bytes per vertex in the packed stream
+ /// (`68 + 12 * active_texcoords`).
+ pub packed_vertex_stride: u32,
+}
+
pub(crate) struct PendingWriteback {
pub dest_addr: Address,
pub staging: wgpu::Buffer,
@@ -303,19 +355,7 @@ impl GxRenderer {
immediate_size: 0,
});
- let frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_frame_uniforms"),
- size: frame_uniform_size,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
-
- let draw_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_draw_uniforms"),
- size: draw_uniform_stride,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
+ let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64;
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("gx_sampler"),
@@ -357,17 +397,23 @@ impl GxRenderer {
let fallback_view = fallback_texture.create_view(&Default::default());
let initial_capacity = 1024;
- let vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_vertices"),
- size: (initial_capacity * std::mem::size_of::<GpuVertex>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
let initial_index_capacity = 4096;
- let index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_indices"),
- size: (initial_index_capacity * std::mem::size_of::<u32>()) as u64,
- usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
+ let initial_frame_slot_count = 8u64;
+ let initial_draw_slot_count = 256u64;
+ let draw_buffer_layout = compute_draw_buffer_layout(
+ uniform_alignment,
+ frame_uniform_size * initial_frame_slot_count,
+ draw_uniform_stride * initial_draw_slot_count,
+ (initial_capacity * std::mem::size_of::<GpuVertex>()) as u64,
+ (initial_index_capacity * std::mem::size_of::<u32>()) as u64,
+ );
+ let draw_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_draw_buffer"),
+ size: draw_buffer_layout.total_size,
+ usage: wgpu::BufferUsages::COPY_DST
+ | wgpu::BufferUsages::UNIFORM
+ | wgpu::BufferUsages::VERTEX
+ | wgpu::BufferUsages::INDEX,
mapped_at_creation: false,
});
@@ -654,14 +700,11 @@ impl GxRenderer {
pipeline_layout,
surface_format,
bind_group_layout,
- frame_uniform_buffer,
- draw_uniform_buffer,
+ draw_buffer,
+ draw_buffer_layout,
+ uniform_alignment,
draw_uniform_stride,
- draw_uniform_capacity: 1,
- vertex_buffer,
- vertex_capacity: initial_capacity,
- index_buffer,
- index_buffer_capacity: initial_index_capacity,
+ draw_uniform_capacity: initial_draw_slot_count as usize,
scratch_indices: Vec::new(),
efb_texture,
efb_view,
@@ -834,7 +877,7 @@ impl GxRenderer {
.iter()
.map(|&k| {
let module = &self_ref.shader_cache[&k.shader];
- (k, self_ref.create_pipeline(device, module, &k.fixed))
+ (k, self_ref.create_pipeline(device, module, &k))
})
.collect::<Vec<_>>()
})
diff --git a/crates/backend-wgpu/src/pipeline.rs b/crates/backend-wgpu/src/pipeline.rs
index f089b94..bb054f4 100644
--- a/crates/backend-wgpu/src/pipeline.rs
+++ b/crates/backend-wgpu/src/pipeline.rs
@@ -1,5 +1,5 @@
use crate::shader_specialization::{KEY_BYTES as SHADER_KEY_BYTES, ShaderKey};
-use crate::{GpuVertex, GxRenderer, helpers};
+use crate::{GxRenderer, helpers};
use chapa::BitField;
use gecko::flipper::gx::regs::{BlendFactor, CompareFunc, CullMode, LogicOp};
@@ -186,84 +186,54 @@ impl GxRenderer {
&self,
device: &wgpu::Device,
shader: &wgpu::ShaderModule,
- key: &PipelineKey,
+ full_key: &FullPipelineKey,
) -> wgpu::RenderPipeline {
+ let key = &full_key.fixed;
+ let active_texcoords = full_key.shader.active_texcoords.min(8) as usize;
+
+ const BASE_ATTRS: [wgpu::VertexAttribute; 5] = [
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 0,
+ shader_location: 0,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x4,
+ offset: 12,
+ shader_location: 1,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x4,
+ offset: 28,
+ shader_location: 2,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 44,
+ shader_location: 3,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 56,
+ shader_location: 4,
+ },
+ ];
+
+ let mut attrs: Vec<wgpu::VertexAttribute> = Vec::with_capacity(5 + active_texcoords);
+ attrs.extend_from_slice(&BASE_ATTRS);
+
+ for i in 0..active_texcoords {
+ attrs.push(wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 68 + (i as u64) * 12,
+ shader_location: 5 + i as u32,
+ });
+ }
+
let vertex_layout = wgpu::VertexBufferLayout {
- array_stride: std::mem::size_of::<GpuVertex>() as u64,
+ array_stride: 68 + (active_texcoords as u64) * 12,
step_mode: wgpu::VertexStepMode::Vertex,
- attributes: &[
- // position: vec3<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 0,
- shader_location: 0,
- },
- // color0: vec4<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x4,
- offset: 12,
- shader_location: 1,
- },
- // color1: vec4<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x4,
- offset: 28,
- shader_location: 2,
- },
- // normal: vec3<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 44,
- shader_location: 3,
- },
- // pos_view: vec3<f32>
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 56,
- shader_location: 4,
- },
- // tex0-tex7: vec3<f32> each (s, t, q for perspective-correct interpolation)
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 68,
- shader_location: 5,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 80,
- shader_location: 6,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 92,
- shader_location: 7,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 104,
- shader_location: 8,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 116,
- shader_location: 9,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 128,
- shader_location: 10,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 140,
- shader_location: 11,
- },
- wgpu::VertexAttribute {
- format: wgpu::VertexFormat::Float32x3,
- offset: 152,
- shader_location: 12,
- },
- ],
+ attributes: &attrs,
};
let blend = if key.blend_enable {
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index 3ded8a8..3022757 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -1,4 +1,4 @@
-use crate::{GpuVertex, GxRenderer, PendingWriteback, align_up};
+use crate::{GxRenderer, PendingWriteback, align_up, compute_draw_buffer_layout};
use gecko::common::Address;
use gecko::flipper::gx::texture::{self, CopyFormat};
use gecko::host::XfbPart;
@@ -49,61 +49,84 @@ impl EfbPackPipelines {
}
}
-/// Upload `bytes` into `buffer` at offset 0 via `write_buffer_with`, which
-/// hands us a writable view into wgpu's staging memory and skips the extra
-/// copy `write_buffer` would do. No-op when `bytes` is empty.
-fn write_buffer(queue: &wgpu::Queue, buffer: &wgpu::Buffer, bytes: &[u8]) {
- let Some(size) = std::num::NonZeroU64::new(bytes.len() as u64) else {
- return;
- };
- let mut view = queue
- .write_buffer_with(buffer, 0, size)
- .expect("buffer too small for write_buffer_with");
- view.copy_from_slice(bytes);
-}
-
impl GxRenderer {
pub(crate) fn upload_buffers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame_uniform_bytes: &[u8]) {
let num_draws = self.scratch_draws.len();
- self.ensure_draw_capacity(device, num_draws);
-
- if self.scratch_vertices.len() > self.vertex_capacity {
- self.vertex_capacity = self.scratch_vertices.len().next_power_of_two();
- self.vertex_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_vertices"),
- size: (self.vertex_capacity * std::mem::size_of::<GpuVertex>()) as u64,
- usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
+ self.ensure_draw_capacity(num_draws);
+
+ // Total packed vertex bytes = sum of per-draw (vertex_count * stride).
+ // Variable per draw because stride depends on `active_texcoords`.
+ let vertex_used: u64 = self
+ .scratch_draws
+ .iter()
+ .map(|d| u64::from(d.vertex_count) * u64::from(d.packed_vertex_stride))
+ .sum();
+ let frame_used = frame_uniform_bytes.len() as u64;
+ let draw_used = self.scratch_uniform_bytes.len() as u64;
+ let index_used = (self.scratch_indices.len() * std::mem::size_of::<u32>()) as u64;
+
+ let layout = self.draw_buffer_layout;
+ let needs_grow = frame_used > layout.frame_capacity
+ || draw_used > layout.draw_capacity
+ || vertex_used > layout.vertex_capacity
+ || index_used > layout.index_capacity;
+ if needs_grow {
+ let frame_cap = grow_capacity(layout.frame_capacity, frame_used);
+ let draw_cap = grow_capacity(layout.draw_capacity, draw_used);
+ let vertex_cap = grow_capacity(layout.vertex_capacity, vertex_used);
+ let index_cap = grow_capacity(layout.index_capacity, index_used);
+ self.draw_buffer_layout =
+ compute_draw_buffer_layout(self.uniform_alignment, frame_cap, draw_cap, vertex_cap, index_cap);
+ self.draw_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_draw_buffer"),
+ size: self.draw_buffer_layout.total_size,
+ usage: wgpu::BufferUsages::COPY_DST
+ | wgpu::BufferUsages::UNIFORM
+ | wgpu::BufferUsages::VERTEX
+ | wgpu::BufferUsages::INDEX,
mapped_at_creation: false,
});
+ // Bind groups embed BufferBinding pointers to the now-stale buffer.
+ self.bind_group_cache.clear();
}
- if self.scratch_indices.len() > self.index_buffer_capacity {
- self.index_buffer_capacity = self.scratch_indices.len().next_power_of_two();
- self.index_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_indices"),
- size: (self.index_buffer_capacity * std::mem::size_of::<u32>()) as u64,
- usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- }
+ let layout = self.draw_buffer_layout;
+ let total_used = layout.index_offset + index_used;
+ let Some(size) = std::num::NonZeroU64::new(total_used) else {
+ return;
+ };
+ let mut view = queue
+ .write_buffer_with(&self.draw_buffer, 0, size)
+ .expect("gx_draw_buffer too small for write_buffer_with");
+ let frame_off = layout.frame_offset as usize;
+ let draw_off = layout.draw_offset as usize;
+ let vertex_off = layout.vertex_offset as usize;
+ let index_off = layout.index_offset as usize;
+ view[frame_off..frame_off + frame_uniform_bytes.len()].copy_from_slice(frame_uniform_bytes);
+ view[draw_off..draw_off + self.scratch_uniform_bytes.len()].copy_from_slice(&self.scratch_uniform_bytes);
+
+ for draw in &self.scratch_draws {
+ let stride = draw.packed_vertex_stride as usize;
+ let texcoord_bytes = stride - 68;
+ let mut cursor = vertex_off + draw.packed_vertex_byte_offset as usize;
+ let src_base = draw.src_vertex_index as usize;
+ let src_end = src_base + draw.vertex_count as usize;
+ for src_v in &self.scratch_vertices[src_base..src_end] {
+ let src_bytes = bytemuck::bytes_of(src_v);
+
+ view[cursor..cursor + 68].copy_from_slice(&src_bytes[..68]);
+ if texcoord_bytes > 0 {
+ view[cursor + 68..cursor + 68 + texcoord_bytes]
+ .copy_from_slice(&src_bytes[68..68 + texcoord_bytes]);
+ }
- let needed_frame_size = frame_uniform_bytes.len() as u64;
- if needed_frame_size > self.frame_uniform_buffer.size() {
- let new_size = needed_frame_size.next_power_of_two().max(needed_frame_size);
- self.frame_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_frame_uniforms"),
- size: new_size,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- self.bind_group_cache.clear();
+ cursor += stride;
+ }
}
- write_buffer(queue, &self.frame_uniform_buffer, frame_uniform_bytes);
- write_buffer(queue, &self.draw_uniform_buffer, &self.scratch_uniform_bytes);
- write_buffer(queue, &self.vertex_buffer, bytemuck::cast_slice(&self.scratch_vertices));
if !self.scratch_indices.is_empty() {
- write_buffer(queue, &self.index_buffer, bytemuck::cast_slice(&self.scratch_indices));
+ view[index_off..index_off + index_used as usize]
+ .copy_from_slice(bytemuck::cast_slice(&self.scratch_indices));
}
}
@@ -946,18 +969,18 @@ impl GxRenderer {
}
}
- fn ensure_draw_capacity(&mut self, device: &wgpu::Device, count: usize) {
+ fn ensure_draw_capacity(&mut self, count: usize) {
if count <= self.draw_uniform_capacity {
return;
}
-
self.draw_uniform_capacity = count.next_power_of_two();
- self.draw_uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("gx_draw_uniforms"),
- size: self.draw_uniform_stride * self.draw_uniform_capacity as u64,
- usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
- mapped_at_creation: false,
- });
- self.bind_group_cache.clear();
+ }
+}
+
+pub(crate) fn grow_capacity(current: u64, needed: u64) -> u64 {
+ if needed <= current {
+ current
+ } else {
+ needed.next_power_of_two().max(needed).max(current)
}
}
diff --git a/crates/backend-wgpu/src/shader_specialization.rs b/crates/backend-wgpu/src/shader_specialization.rs
index 5b50dc2..2a3d8e1 100644
--- a/crates/backend-wgpu/src/shader_specialization.rs
+++ b/crates/backend-wgpu/src/shader_specialization.rs
@@ -13,9 +13,9 @@ const ALPHA_TEST_WESL: &str = include_str!("shaders/alpha_test.wesl");
const LIGHTING_WESL: &str = include_str!("shaders/lighting.wesl");
const MAIN_WESL: &str = include_str!("shaders/main.wesl");
-pub(crate) const KEY_BYTES: usize = 5;
+pub(crate) const KEY_BYTES: usize = 6;
const CACHE_MAGIC: [u8; 4] = *b"GSKC";
-pub(crate) const CACHE_VERSION: u32 = 5;
+pub(crate) const CACHE_VERSION: u32 = 6;
pub(crate) const SHADER_CACHE_PATH: &str = "cache/shader_keys.bin";
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
@@ -25,6 +25,7 @@ pub(crate) struct ShaderKey {
pub has_lighting_c0: bool,
pub has_lighting_c1: bool,
pub alpha_test_enabled: bool,
+ pub active_texcoords: u8,
}
impl ShaderKey {
@@ -45,6 +46,7 @@ impl ShaderKey {
has_lighting_c0,
has_lighting_c1,
alpha_test_enabled: !always_pass,
+ active_texcoords: draw.active_texcoords.min(8),
}
}
}
@@ -69,6 +71,7 @@ impl ShaderKey {
self.has_lighting_c0 as u8,
self.has_lighting_c1 as u8,
self.alpha_test_enabled as u8,
+ self.active_texcoords,
]
}
@@ -79,6 +82,7 @@ impl ShaderKey {
has_lighting_c0: b[2] != 0,
has_lighting_c1: b[3] != 0,
alpha_test_enabled: b[4] != 0,
+ active_texcoords: b[5].min(8),
}
}
}
@@ -143,6 +147,10 @@ pub(crate) fn compile_variant(key: ShaderKey) -> String {
compiler.set_feature("HAS_LIGHTING_C1", key.has_lighting_c1);
compiler.set_feature("ALPHA_TEST_ENABLED", key.alpha_test_enabled);
+ for i in 0..8u8 {
+ compiler.set_feature(&format!("TEXCOORD_{i}_ENABLED"), i < key.active_texcoords);
+ }
+
let entry = "package::main".parse().expect("valid module path");
compiler
.compile(&entry)
diff --git a/crates/backend-wgpu/src/shaders/common.wesl b/crates/backend-wgpu/src/shaders/common.wesl
index 5224c39..fe5b4ec 100644
--- a/crates/backend-wgpu/src/shaders/common.wesl
+++ b/crates/backend-wgpu/src/shaders/common.wesl
@@ -70,14 +70,14 @@ struct VsIn {
@location(2) color1: vec4<f32>,
@location(3) normal: vec3<f32>,
@location(4) pos_view: vec3<f32>,
- @location(5) tex0: vec3<f32>,
- @location(6) tex1: vec3<f32>,
- @location(7) tex2: vec3<f32>,
- @location(8) tex3: vec3<f32>,
- @location(9) tex4: vec3<f32>,
- @location(10) tex5: vec3<f32>,
- @location(11) tex6: vec3<f32>,
- @location(12) tex7: vec3<f32>,
+ @if(TEXCOORD_0_ENABLED) @location(5) tex0: vec3<f32>,
+ @if(TEXCOORD_1_ENABLED) @location(6) tex1: vec3<f32>,
+ @if(TEXCOORD_2_ENABLED) @location(7) tex2: vec3<f32>,
+ @if(TEXCOORD_3_ENABLED) @location(8) tex3: vec3<f32>,
+ @if(TEXCOORD_4_ENABLED) @location(9) tex4: vec3<f32>,
+ @if(TEXCOORD_5_ENABLED) @location(10) tex5: vec3<f32>,
+ @if(TEXCOORD_6_ENABLED) @location(11) tex6: vec3<f32>,
+ @if(TEXCOORD_7_ENABLED) @location(12) tex7: vec3<f32>,
};
struct VsOut {
diff --git a/crates/backend-wgpu/src/shaders/main.wesl b/crates/backend-wgpu/src/shaders/main.wesl
index 2ae4cd4..992c913 100644
--- a/crates/backend-wgpu/src/shaders/main.wesl
+++ b/crates/backend-wgpu/src/shaders/main.wesl
@@ -20,14 +20,16 @@ fn vs_main(in: VsIn) -> VsOut {
frame.ambient_color1, frame.material_color1,
in.color1, in.normal, in.pos_view,
);
- out.uv0 = in.tex0;
- out.uv1 = in.tex1;
- out.uv2 = in.tex2;
- out.uv3 = in.tex3;
- out.uv4 = in.tex4;
- out.uv5 = in.tex5;
- out.uv6 = in.tex6;
- out.uv7 = in.tex7;
+
+ @if(TEXCOORD_0_ENABLED) { out.uv0 = in.tex0; } @else { out.uv0 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_1_ENABLED) { out.uv1 = in.tex1; } @else { out.uv1 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_2_ENABLED) { out.uv2 = in.tex2; } @else { out.uv2 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_3_ENABLED) { out.uv3 = in.tex3; } @else { out.uv3 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_4_ENABLED) { out.uv4 = in.tex4; } @else { out.uv4 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_5_ENABLED) { out.uv5 = in.tex5; } @else { out.uv5 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_6_ENABLED) { out.uv6 = in.tex6; } @else { out.uv6 = vec3<f32>(0.0, 0.0, 1.0); }
+ @if(TEXCOORD_7_ENABLED) { out.uv7 = in.tex7; } @else { out.uv7 = vec3<f32>(0.0, 0.0, 1.0); }
+
return out;
}
diff --git a/crates/gecko/src/flipper/gx/vertex.rs b/crates/gecko/src/flipper/gx/vertex.rs
index 2a23ddd..77ff627 100644
--- a/crates/gecko/src/flipper/gx/vertex.rs
+++ b/crates/gecko/src/flipper/gx/vertex.rs
@@ -153,6 +153,7 @@ impl GraphicsProcessor {
boxed.ambient_color = self.cached_ambient_color;
boxed.material_color = self.cached_material_color;
boxed.lights = self.cached_lights;
+ boxed.active_texcoords = (self.xf_mem[crate::flipper::gx::constants::XF_NUM_TEXGENS] as u8).min(8);
boxed.frame_dirty = self.frame_state_dirty;
self.frame_state_dirty = false;
renderer.exec(GxAction::Draw(boxed));
diff --git a/crates/gecko/src/host.rs b/crates/gecko/src/host.rs
index d30af3a..9282c2d 100644
--- a/crates/gecko/src/host.rs
+++ b/crates/gecko/src/host.rs
@@ -160,6 +160,7 @@ pub struct DrawData {
pub primitive: Primitive,
pub base_vertex: u32,
pub vertex_count: u32,
+ pub active_texcoords: u8,
pub modelview: [[f32; 4]; 4],
// TEV combiner state
pub tev_color_env: [u32; 16],
diff --git a/crates/mcp/src/sink.rs b/crates/mcp/src/sink.rs
index 87ead58..be52188 100644
--- a/crates/mcp/src/sink.rs
+++ b/crates/mcp/src/sink.rs
@@ -73,10 +73,12 @@ impl RenderSink for McpSink {
}
_ => {}
}
- self.gx
- .lock()
- .unwrap()
- .process_action_with_external_scratch(&self.device, &self.queue, &action, &mut self.scratch);
+ self.gx.lock().unwrap().process_action_with_external_scratch(
+ &self.device,
+ &self.queue,
+ &action,
+ &mut self.scratch,
+ );
}
fn vertex_scratch(&mut self) -> &mut Vec<DrawVertex> {
diff --git a/crates/screenshotter/src/main.rs b/crates/screenshotter/src/main.rs
index ce9d21e..3cfd9e0 100644
--- a/crates/screenshotter/src/main.rs
+++ b/crates/screenshotter/src/main.rs
@@ -22,10 +22,12 @@ struct SyncSink {
impl RenderSink for SyncSink {
fn exec(&mut self, action: GxAction) {
- self.gx
- .lock()
- .unwrap()
- .process_action_with_external_scratch(&self.device, &self.queue, &action, &mut self.scratch);
+ self.gx.lock().unwrap().process_action_with_external_scratch(
+ &self.device,
+ &self.queue,
+ &action,
+ &mut self.scratch,
+ );
}
fn vertex_scratch(&mut self) -> &mut Vec<gecko::host::DrawVertex> {