Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

triple threaded architecture and improved textures

Layleb613f0a8ec91
diff --git a/crates/backend-wgpu/src/action.rs b/crates/backend-wgpu/src/action.rs
index 7f3681f..d130009 100644
--- a/crates/backend-wgpu/src/action.rs
+++ b/crates/backend-wgpu/src/action.rs
@@ -1,6 +1,6 @@
+use crate::GpuVertex;
use crate::pipeline::PipelineKey;
use crate::{BindGroupCacheKey, DrawUniforms, FrameUniforms, GxRenderer, SamplerKey, helpers};
-use crate::{GpuVertex, align_up};
use encase::{ShaderType as _, UniformBuffer};
use gecko::flipper::gx::regs::{MagFilter, MinFilter, WrapMode};
use gecko::host::{DrawData, GxAction};
@@ -42,310 +42,229 @@ impl GxRenderer {
}
}
- /// Process a batch of [`GxAction`] values, rendering draw calls into the
- /// internal EFB and handling EFB copies / XFB presentation.
- pub fn render_actions(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, actions: &[GxAction]) {
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
-
+ /// 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.
+ 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_encase_size = DrawUniforms::min_size().get() as usize;
- let frame_stride = align_up(
- FrameUniforms::min_size().get(),
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
- let frame_encase_size = FrameUniforms::min_size().get() as usize;
- let mut frame_uniform_bytes: Vec<u8> = Vec::new();
-
- // Per-draw snapshots of pipeline key + bind group key (captured at draw time
- // from the current tracked state).
- let mut draw_pipeline_keys: Vec<PipelineKey> = Vec::new();
- let mut draw_bg_keys: Vec<BindGroupCacheKey> = Vec::new();
- // Per-draw viewport/scissor snapshots (captured from tracked state at draw time).
- let mut draw_viewports: Vec<gecko::flipper::gx::draw::Viewport> = Vec::new();
- let mut draw_scissors: Vec<gecko::flipper::gx::draw::Scissor> = Vec::new();
-
- for action in actions {
- match action {
- GxAction::SetProjection { matrix, .. } => {
- self.current_projection = Mat4::from_cols_array_2d(matrix);
- }
- GxAction::SetViewport(vp) => {
- self.current_viewport = *vp;
- }
- GxAction::SetScissor(sc) => {
- self.current_scissor = *sc;
- }
- GxAction::SetDepthMode(zm) => {
- self.current_zmode = *zm;
- }
- GxAction::SetBlendMode(bm) => {
- self.current_blend_mode = *bm;
- }
- GxAction::SetAlphaCompare(ac) => {
- self.current_alpha_compare = *ac;
- }
- GxAction::LoadTexture {
- id,
- width,
- height,
- rgba,
- } => {
- let tex = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("gx_tex"),
- size: wgpu::Extent3d {
- width: *width,
- height: *height,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
- queue.write_texture(
- tex.as_image_copy(),
- rgba,
- wgpu::TexelCopyBufferLayout {
- offset: 0,
- bytes_per_row: Some(*width * 4),
- rows_per_image: None,
- },
- wgpu::Extent3d {
- width: *width,
- height: *height,
- depth_or_array_layers: 1,
- },
- );
- let view = tex.create_view(&Default::default());
- // Invalidate bind groups that referenced the old texture.
- let tid = *id;
- self.bind_group_cache
- .retain(|key, _| !key.tex_keys.iter().any(|k| *k == Some(tid)));
- self.texture_cache.insert(*id, (tex, view));
- }
- GxAction::SetTexture {
- slot,
- id,
- wrap_s,
- wrap_t,
- mag_filter,
- min_filter,
- } => {
- self.current_texture_ids[*slot] = Some(*id);
- let sampler_key: SamplerKey = (*wrap_s, *wrap_t, *mag_filter, *min_filter);
- self.current_sampler_keys[*slot] = Some(sampler_key);
- self.ensure_sampler(device, &sampler_key);
- }
- GxAction::SetCullMode(mode) => {
- self.current_cull_mode = *mode;
- }
+ let frame_stride = self.frame_stride;
+ let frame_encase_size = self.frame_encase_size;
- GxAction::Draw(draw) => {
- // Ensure pipeline for current tracked blend/depth state.
- let pipeline_key = self.current_pipeline_key();
- if !self.pipeline_cache.contains_key(&pipeline_key) {
- let pipeline = self.create_pipeline(device, &pipeline_key);
- self.pipeline_cache.insert(pipeline_key, pipeline);
- }
-
- // Triangulate.
- let prev_len = self.scratch_vertices.len();
- triangulate_draw_data(draw, &mut self.scratch_vertices);
- let added = self.scratch_vertices.len() - prev_len;
- if added == 0 {
- continue;
- }
+ match action {
+ GxAction::SetProjection { matrix, .. } => {
+ self.current_projection = Mat4::from_cols_array_2d(matrix);
+ }
+ GxAction::SetViewport(vp) => {
+ self.current_viewport = *vp;
+ }
+ GxAction::SetScissor(sc) => {
+ self.current_scissor = *sc;
+ }
+ GxAction::SetDepthMode(zm) => {
+ self.current_zmode = *zm;
+ }
+ GxAction::SetBlendMode(bm) => {
+ self.current_blend_mode = *bm;
+ }
+ GxAction::SetAlphaCompare(ac) => {
+ self.current_alpha_compare = *ac;
+ }
+ GxAction::LoadTexture {
+ id,
+ width,
+ height,
+ rgba,
+ } => {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("gx_tex"),
+ size: wgpu::Extent3d {
+ width: *width,
+ height: *height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+ queue.write_texture(
+ tex.as_image_copy(),
+ rgba,
+ wgpu::TexelCopyBufferLayout {
+ offset: 0,
+ bytes_per_row: Some(*width * 4),
+ rows_per_image: None,
+ },
+ wgpu::Extent3d {
+ width: *width,
+ height: *height,
+ depth_or_array_layers: 1,
+ },
+ );
+ let view = tex.create_view(&Default::default());
+ // Invalidate bind groups that referenced the old texture.
+ let tid = *id;
+ self.bind_group_cache
+ .retain(|key, _| !key.tex_keys.iter().any(|k| *k == Some(tid)));
+ self.texture_cache.insert(*id, (tex, view));
+ }
+ GxAction::SetTexture {
+ slot,
+ id,
+ wrap_s,
+ wrap_t,
+ mag_filter,
+ min_filter,
+ } => {
+ self.current_texture_ids[*slot] = Some(*id);
+ let sampler_key: SamplerKey = (*wrap_s, *wrap_t, *mag_filter, *min_filter);
+ self.current_sampler_keys[*slot] = Some(sampler_key);
+ self.ensure_sampler(device, &sampler_key);
+ }
+ GxAction::SetCullMode(mode) => {
+ self.current_cull_mode = *mode;
+ }
- // Build per-draw uniform (MVP) using tracked projection.
- let modelview = Mat4::from_cols_array_2d(&draw.modelview);
- let mvp = self.current_projection * modelview;
- let draw_uniform = DrawUniforms { mvp };
-
- let start = self.scratch_draws.len() * draw_stride;
- self.scratch_uniform_bytes.resize(start + draw_stride, 0);
- let mut draw_buf =
- UniformBuffer::new(&mut self.scratch_uniform_bytes[start..start + draw_encase_size]);
- draw_buf.write(&draw_uniform).unwrap();
-
- // Build per-draw frame uniform (TEV + lighting from DrawData,
- // alpha compare from tracked state).
- let alpha_cmp = self.current_alpha_compare;
- let frame_uniform = FrameUniforms {
- tev_color_regs: draw.tev_color_regs.map(Vec4::from),
- tev_konst_colors: draw.tev_konst_colors.map(Vec4::from),
- tev_color_env: pack_u32_slice_to_uvec4x4(&draw.tev_color_env),
- tev_alpha_env: pack_u32_slice_to_uvec4x4(&draw.tev_alpha_env),
- tev_orders: pack_u32_slice_to_uvec4x4(&draw.tev_orders),
- num_tev_stages: draw.num_tev_stages as u32,
- alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
- alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
- alpha_comp0: alpha_cmp.comp0() as u32,
- alpha_comp1: alpha_cmp.comp1() as u32,
- alpha_op: alpha_cmp.op() as u32,
- light_colors: draw.lights.each_ref().map(|l| Vec4::from(l.color)),
- light_cosatt: draw.lights.each_ref().map(|l| Vec4::from(l.cosatt)),
- light_distatt: draw.lights.each_ref().map(|l| Vec4::from(l.distatt)),
- light_pos: draw.lights.each_ref().map(|l| Vec4::from(l.position)),
- light_dir: draw.lights.each_ref().map(|l| Vec4::from(l.direction)),
- color_ctrl0: draw.color_ctrl[0].raw(),
- alpha_ctrl0: draw.alpha_ctrl[0].raw(),
- color_ctrl1: draw.color_ctrl[1].raw(),
- alpha_ctrl1: draw.alpha_ctrl[1].raw(),
- ambient_color0: Vec4::from(draw.ambient_color[0]),
- ambient_color1: Vec4::from(draw.ambient_color[1]),
- material_color0: Vec4::from(draw.material_color[0]),
- material_color1: Vec4::from(draw.material_color[1]),
- };
-
- let fstart = self.scratch_draws.len() * frame_stride;
- frame_uniform_bytes.resize(fstart + frame_stride, 0);
- let mut frame_buf =
- UniformBuffer::new(&mut frame_uniform_bytes[fstart..fstart + frame_encase_size]);
- frame_buf.write(&frame_uniform).unwrap();
-
- // Snapshot tracked state for this draw.
- draw_pipeline_keys.push(pipeline_key);
- draw_bg_keys.push(self.current_bind_group_key());
- draw_viewports.push(self.current_viewport);
- draw_scissors.push(self.current_scissor);
-
- self.scratch_draws.push((prev_len as u32, added as u32));
+ GxAction::Draw(draw) => {
+ // Ensure pipeline for current tracked blend/depth state.
+ let pipeline_key = self.current_pipeline_key();
+ if !self.pipeline_cache.contains_key(&pipeline_key) {
+ let pipeline = self.create_pipeline(device, &pipeline_key);
+ self.pipeline_cache.insert(pipeline_key, pipeline);
}
- GxAction::CopyEfb(copy) => {
- // Flush pending draws before the copy.
- if !self.scratch_draws.is_empty() {
- self.upload_buffers(device, queue, &frame_uniform_bytes);
- self.execute_action_render_pass(
- device,
- queue,
- &draw_pipeline_keys,
- &draw_bg_keys,
- &draw_viewports,
- &draw_scissors,
- );
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
- frame_uniform_bytes.clear();
- draw_pipeline_keys.clear();
- draw_bg_keys.clear();
- draw_viewports.clear();
- draw_scissors.clear();
- }
-
- self.execute_efb_copy(device, queue, copy);
+ // Triangulate.
+ let prev_len = self.scratch_vertices.len();
+ triangulate_draw_data(draw, &mut self.scratch_vertices);
+ let added = self.scratch_vertices.len() - prev_len;
+ if added == 0 {
+ return;
}
- GxAction::CopyXfb {
- id,
- src_x,
- src_y,
- src_w,
- src_h,
- clear,
- clear_color,
- clear_z,
- } => {
- if !self.scratch_draws.is_empty() {
- self.upload_buffers(device, queue, &frame_uniform_bytes);
- self.execute_action_render_pass(
- device,
- queue,
- &draw_pipeline_keys,
- &draw_bg_keys,
- &draw_viewports,
- &draw_scissors,
- );
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
- frame_uniform_bytes.clear();
- draw_pipeline_keys.clear();
- draw_bg_keys.clear();
- draw_viewports.clear();
- draw_scissors.clear();
- }
+ // Build per-draw uniform (MVP) using tracked projection.
+ let modelview = Mat4::from_cols_array_2d(&draw.modelview);
+ let mvp = self.current_projection * modelview;
+ let draw_uniform = DrawUniforms { mvp };
+
+ let start = self.scratch_draws.len() * draw_stride;
+ self.scratch_uniform_bytes.resize(start + draw_stride, 0);
+ let mut draw_buf = UniformBuffer::new(&mut self.scratch_uniform_bytes[start..start + draw_encase_size]);
+ draw_buf.write(&draw_uniform).unwrap();
+
+ // Build per-draw frame uniform (TEV + lighting from DrawData,
+ // alpha compare from tracked state).
+ let alpha_cmp = self.current_alpha_compare;
+ let frame_uniform = FrameUniforms {
+ tev_color_regs: draw.tev_color_regs.map(Vec4::from),
+ tev_konst_colors: draw.tev_konst_colors.map(Vec4::from),
+ tev_color_env: pack_u32_slice_to_uvec4x4(&draw.tev_color_env),
+ tev_alpha_env: pack_u32_slice_to_uvec4x4(&draw.tev_alpha_env),
+ tev_orders: pack_u32_slice_to_uvec4x4(&draw.tev_orders),
+ num_tev_stages: draw.num_tev_stages as u32,
+ alpha_ref0: alpha_cmp.ref0() as f32 / 255.0,
+ alpha_ref1: alpha_cmp.ref1() as f32 / 255.0,
+ alpha_comp0: alpha_cmp.comp0() as u32,
+ alpha_comp1: alpha_cmp.comp1() as u32,
+ alpha_op: alpha_cmp.op() as u32,
+ light_colors: draw.lights.each_ref().map(|l| Vec4::from(l.color)),
+ light_cosatt: draw.lights.each_ref().map(|l| Vec4::from(l.cosatt)),
+ light_distatt: draw.lights.each_ref().map(|l| Vec4::from(l.distatt)),
+ light_pos: draw.lights.each_ref().map(|l| Vec4::from(l.position)),
+ light_dir: draw.lights.each_ref().map(|l| Vec4::from(l.direction)),
+ color_ctrl0: draw.color_ctrl[0].raw(),
+ alpha_ctrl0: draw.alpha_ctrl[0].raw(),
+ color_ctrl1: draw.color_ctrl[1].raw(),
+ alpha_ctrl1: draw.alpha_ctrl[1].raw(),
+ ambient_color0: Vec4::from(draw.ambient_color[0]),
+ ambient_color1: Vec4::from(draw.ambient_color[1]),
+ material_color0: Vec4::from(draw.material_color[0]),
+ material_color1: Vec4::from(draw.material_color[1]),
+ };
+
+ let fstart = self.scratch_draws.len() * frame_stride;
+ self.frame_uniform_bytes.resize(fstart + frame_stride, 0);
+ let mut frame_buf =
+ UniformBuffer::new(&mut self.frame_uniform_bytes[fstart..fstart + frame_encase_size]);
+ frame_buf.write(&frame_uniform).unwrap();
+
+ // Snapshot tracked state for this draw.
+ self.draw_pipeline_keys.push(pipeline_key);
+ self.draw_bg_keys.push(self.current_bind_group_key());
+ self.draw_viewports.push(self.current_viewport);
+ self.draw_scissors.push(self.current_scissor);
+
+ self.scratch_draws.push((prev_len as u32, added as u32));
+ }
- self.execute_copy_xfb(
- device,
- queue,
- *id,
- *src_x,
- *src_y,
- *src_w,
- *src_h,
- *clear,
- *clear_color,
- *clear_z,
- );
- }
+ GxAction::CopyEfb(copy) => {
+ self.flush_pending_draws(device, queue);
+ self.execute_efb_copy(device, queue, copy);
+ }
- GxAction::PresentXfb { width, height, parts } => {
- // Flush any trailing draws.
- if !self.scratch_draws.is_empty() {
- self.upload_buffers(device, queue, &frame_uniform_bytes);
- self.execute_action_render_pass(
- device,
- queue,
- &draw_pipeline_keys,
- &draw_bg_keys,
- &draw_viewports,
- &draw_scissors,
- );
- self.scratch_vertices.clear();
- self.scratch_draws.clear();
- self.scratch_uniform_bytes.clear();
- frame_uniform_bytes.clear();
- draw_pipeline_keys.clear();
- draw_bg_keys.clear();
- draw_viewports.clear();
- draw_scissors.clear();
- }
+ GxAction::CopyXfb {
+ id,
+ src_x,
+ src_y,
+ src_w,
+ src_h,
+ clear,
+ clear_color,
+ clear_z,
+ } => {
+ self.flush_pending_draws(device, queue);
+ self.execute_copy_xfb(
+ device,
+ queue,
+ *id,
+ *src_x,
+ *src_y,
+ *src_w,
+ *src_h,
+ *clear,
+ *clear_color,
+ *clear_z,
+ );
+ }
- self.execute_present_xfb(device, queue, *width, *height, parts);
- }
+ GxAction::PresentXfb { width, height, parts } => {
+ self.flush_pending_draws(device, queue);
+ self.execute_present_xfb(device, queue, *width, *height, parts);
}
}
+ }
- // Flush remaining draws.
- if !self.scratch_draws.is_empty() {
- self.upload_buffers(device, queue, &frame_uniform_bytes);
- self.execute_action_render_pass(
- device,
- queue,
- &draw_pipeline_keys,
- &draw_bg_keys,
- &draw_viewports,
- &draw_scissors,
- );
+ /// Flush accumulated draw calls into a render pass.
+ pub fn flush_pending_draws(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
+ if self.scratch_draws.is_empty() {
+ return;
}
+ let fub = std::mem::take(&mut self.frame_uniform_bytes);
+ self.upload_buffers(device, queue, &fub);
+ self.frame_uniform_bytes = fub;
+
+ self.execute_action_render_pass(device, queue);
+
+ self.scratch_vertices.clear();
+ self.scratch_draws.clear();
+ self.scratch_uniform_bytes.clear();
+ self.frame_uniform_bytes.clear();
+ self.draw_pipeline_keys.clear();
+ self.draw_bg_keys.clear();
+ self.draw_viewports.clear();
+ self.draw_scissors.clear();
}
- /// Render pass for streamed action draws.
- fn execute_action_render_pass(
- &mut self,
- device: &wgpu::Device,
- queue: &wgpu::Queue,
- pipeline_keys: &[PipelineKey],
- bg_keys: &[BindGroupCacheKey],
- viewports: &[gecko::flipper::gx::draw::Viewport],
- scissors: &[gecko::flipper::gx::draw::Scissor],
- ) {
+ fn execute_action_render_pass(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
let target_width = crate::EFB_WIDTH;
let target_height = crate::EFB_HEIGHT;
let fallback_sampler_key = (WrapMode::Clamp, WrapMode::Clamp, MagFilter::Linear, MinFilter::Linear);
- let frame_stride = align_up(
- FrameUniforms::min_size().get(),
- device.limits().min_uniform_buffer_offset_alignment as u64,
- ) as usize;
+ let frame_stride = self.frame_stride;
// Pre-build bind groups from tracked texture snapshots.
- for bg_key in bg_keys {
+ for bg_key in &self.draw_bg_keys {
self.bind_group_cache.entry(bg_key.clone()).or_insert_with(|| {
let mut tex_views: [&wgpu::TextureView; 8] = [&self.fallback_view; 8];
let mut tex_samplers: [&wgpu::Sampler; 8] = [&self.sampler_cache[&fallback_sampler_key]; 8];
@@ -439,18 +358,18 @@ impl GxRenderer {
rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
for (index, (first_vertex, vertex_count)) in self.scratch_draws.iter().copied().enumerate() {
- let pipeline_key = &pipeline_keys[index];
+ let pipeline_key = &self.draw_pipeline_keys[index];
let pipeline = &self.pipeline_cache[pipeline_key];
rpass.set_pipeline(pipeline);
- let bg_key = &bg_keys[index];
+ let bg_key = &self.draw_bg_keys[index];
let bind_group = &self.bind_group_cache[bg_key];
let frame_offset = (index * frame_stride) as u32;
let draw_offset = (index as u64 * self.draw_uniform_stride) as u32;
rpass.set_bind_group(0, bind_group, &[frame_offset, draw_offset]);
- let vp = &viewports[index];
+ let vp = &self.draw_viewports[index];
let max_dim = target_width.max(target_height) as f32;
let vp_w = vp.w.clamp(1.0, max_dim);
let vp_h = vp.h.clamp(1.0, max_dim);
@@ -458,7 +377,7 @@ impl GxRenderer {
rpass.set_viewport(vp.x, vp.y, vp_w, vp_h, vp.min_depth, vp.max_depth);
}
- let sc = &scissors[index];
+ let sc = &self.draw_scissors[index];
let sc_w = sc.w.max(1).min(target_width.saturating_sub(sc.x));
let sc_h = sc.h.max(1).min(target_height.saturating_sub(sc.y));
rpass.set_scissor_rect(sc.x, sc.y, sc_w, sc_h);
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index 20f5c0a..b187144 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -110,6 +110,15 @@ pub struct GxRenderer {
pub(crate) scratch_draws: Vec<(u32, u32)>,
pub(crate) scratch_uniform_bytes: Vec<u8>,
pub(crate) bind_group_cache: HashMap<BindGroupCacheKey, wgpu::BindGroup>,
+ // Per-frame draw accumulation (persists across process_action calls,
+ // flushed by flush_pending_draws).
+ pub(crate) frame_uniform_bytes: Vec<u8>,
+ pub(crate) draw_pipeline_keys: Vec<PipelineKey>,
+ pub(crate) draw_bg_keys: Vec<BindGroupCacheKey>,
+ pub(crate) draw_viewports: Vec<Viewport>,
+ pub(crate) draw_scissors: Vec<Scissor>,
+ pub(crate) frame_stride: usize,
+ pub(crate) frame_encase_size: usize,
// Tracked GX state (updated by state-change actions)
pub(crate) current_projection: Mat4,
pub(crate) current_viewport: Viewport,
@@ -120,10 +129,6 @@ pub struct GxRenderer {
pub(crate) current_cull_mode: CullMode,
pub(crate) current_texture_ids: [Option<TextureId>; 8],
pub(crate) current_sampler_keys: [Option<SamplerKey>; 8],
- // Blit pipeline (EFB -> swapchain)
- pub(crate) blit_pipeline: wgpu::RenderPipeline,
- pub(crate) blit_bind_group_layout: wgpu::BindGroupLayout,
- pub(crate) blit_sampler: wgpu::Sampler,
// XFB output texture: composited from per-copy snapshots by PresentXfb.
pub(crate) xfb_texture: wgpu::Texture,
pub(crate) xfb_view: wgpu::TextureView,
@@ -337,72 +342,6 @@ impl GxRenderer {
});
let xfb_view = xfb_texture.create_view(&Default::default());
- // Blit pipeline EFB -> swapchain shit
- let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
- label: Some("efb_blit_shader"),
- source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_blit.wgsl").into()),
- });
- let blit_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
- label: Some("efb_blit_bg_layout"),
- entries: &[
- wgpu::BindGroupLayoutEntry {
- binding: 0,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Texture {
- sample_type: wgpu::TextureSampleType::Float { filterable: true },
- view_dimension: wgpu::TextureViewDimension::D2,
- multisampled: false,
- },
- count: None,
- },
- wgpu::BindGroupLayoutEntry {
- binding: 1,
- visibility: wgpu::ShaderStages::FRAGMENT,
- ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
- count: None,
- },
- ],
- });
- let blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
- label: None,
- bind_group_layouts: &[&blit_bind_group_layout],
- immediate_size: 0,
- });
- let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
- label: Some("efb_blit_pipeline"),
- layout: Some(&blit_layout),
- vertex: wgpu::VertexState {
- module: &blit_shader,
- entry_point: Some("vs_main"),
- buffers: &[],
- compilation_options: Default::default(),
- },
- fragment: Some(wgpu::FragmentState {
- module: &blit_shader,
- entry_point: Some("fs_main"),
- targets: &[Some(wgpu::ColorTargetState {
- format: surface_format,
- blend: None,
- write_mask: wgpu::ColorWrites::ALL,
- })],
- compilation_options: Default::default(),
- }),
- primitive: wgpu::PrimitiveState {
- topology: wgpu::PrimitiveTopology::TriangleList,
- ..Default::default()
- },
- depth_stencil: None,
- multisample: wgpu::MultisampleState::default(),
- multiview_mask: None,
- cache: None,
- });
- let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
- label: Some("efb_blit_sampler"),
- mag_filter: wgpu::FilterMode::Linear,
- min_filter: wgpu::FilterMode::Linear,
- ..Default::default()
- });
-
let efb_clear = clear::EfbClear::new(
device,
surface_format,
@@ -438,6 +377,16 @@ impl GxRenderer {
scratch_draws: Vec::new(),
scratch_uniform_bytes: Vec::new(),
bind_group_cache: HashMap::new(),
+ frame_uniform_bytes: Vec::new(),
+ draw_pipeline_keys: Vec::new(),
+ draw_bg_keys: Vec::new(),
+ draw_viewports: Vec::new(),
+ draw_scissors: Vec::new(),
+ frame_stride: align_up(
+ FrameUniforms::min_size().get(),
+ device.limits().min_uniform_buffer_offset_alignment as u64,
+ ) as usize,
+ frame_encase_size: FrameUniforms::min_size().get() as usize,
current_projection: Mat4::IDENTITY,
current_viewport: Viewport::default(),
current_scissor: Scissor::default(),
@@ -449,9 +398,6 @@ impl GxRenderer {
.with_comp1(CompareFunc::Always),
current_texture_ids: Default::default(),
current_sampler_keys: Default::default(),
- blit_pipeline,
- blit_bind_group_layout,
- blit_sampler,
xfb_texture,
xfb_view,
xfb_has_content: false,
diff --git a/crates/backend-wgpu/src/render.rs b/crates/backend-wgpu/src/render.rs
index ceee07d..f56297a 100644
--- a/crates/backend-wgpu/src/render.rs
+++ b/crates/backend-wgpu/src/render.rs
@@ -245,55 +245,6 @@ impl GxRenderer {
self.xfb_has_content = true;
}
- /// Blit the composited XFB output to the swapchain target. Falls back
- /// to the live EFB if no XFB content has been produced yet.
- pub fn blit_to_target(&self, device: &wgpu::Device, queue: &wgpu::Queue, target: &wgpu::TextureView) {
- let source_view = if self.xfb_has_content {
- &self.xfb_view
- } else {
- &self.efb_view
- };
- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
- label: Some("efb_blit_bg"),
- layout: &self.blit_bind_group_layout,
- entries: &[
- wgpu::BindGroupEntry {
- binding: 0,
- resource: wgpu::BindingResource::TextureView(source_view),
- },
- wgpu::BindGroupEntry {
- binding: 1,
- resource: wgpu::BindingResource::Sampler(&self.blit_sampler),
- },
- ],
- });
-
- let mut encoder = device.create_command_encoder(&Default::default());
- {
- let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
- label: Some("efb_blit"),
- color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: target,
- resolve_target: None,
- ops: wgpu::Operations {
- load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
- store: wgpu::StoreOp::Store,
- },
- depth_slice: None,
- })],
- depth_stencil_attachment: None,
- occlusion_query_set: None,
- timestamp_writes: None,
- multiview_mask: None,
- });
- rpass.set_pipeline(&self.blit_pipeline);
- rpass.set_bind_group(0, &bind_group, &[]);
- rpass.draw(0..3, 0..1);
- }
-
- queue.submit([encoder.finish()]);
- }
-
fn ensure_draw_capacity(&mut self, device: &wgpu::Device, count: usize) {
if count <= self.draw_uniform_capacity {
return;
diff --git a/crates/backend-wgpu/src/sink.rs b/crates/backend-wgpu/src/sink.rs
index 1f84dbf..484d541 100644
--- a/crates/backend-wgpu/src/sink.rs
+++ b/crates/backend-wgpu/src/sink.rs
@@ -1,43 +1,185 @@
+use crate::GxRenderer;
use crossbeam_channel::{Receiver, Sender, bounded};
use gecko::host::{GxAction, RenderSink};
+use std::sync::{Arc, Mutex};
-/// Capacity of the action channel. Must be large enough to hold at least
-/// two full frames of actions without dropping. Complex scenes (IPL cube
-/// menu) can emit 4000+ draw calls per frame.
-const CHANNEL_CAPACITY: usize = 65536;
+const CHANNEL_CAPACITY: usize = 8192;
-pub struct Renderer {
- tx: Sender<GxAction>,
+/// Holds the XFB output texture view that the worker updates and the main
+/// thread reads for blitting.
+pub struct Shared {
+ pub output: Mutex<wgpu::TextureView>,
}
-pub struct ActionReceiver {
- rx: Receiver<GxAction>,
+fn worker(mut gx: GxRenderer, device: wgpu::Device, queue: wgpu::Queue, shared: Arc<Shared>, rx: Receiver<GxAction>) {
+ while let Ok(action) = rx.recv() {
+ gx.process_action(&device, &queue, &action);
+
+ // After a PresentXfb, update the shared output so the main thread
+ // picks up the latest composited frame on its next blit.
+ if matches!(action, GxAction::PresentXfb { .. }) {
+ let mut output = shared.output.lock().unwrap();
+ *output = gx.xfb_view.clone();
+ }
+ }
}
-pub fn channel() -> (Renderer, ActionReceiver) {
- let (tx, rx) = bounded(CHANNEL_CAPACITY);
- (Renderer { tx }, ActionReceiver { rx })
+#[derive(Clone)]
+pub struct Renderer {
+ tx: Sender<GxAction>,
+ shared: Arc<Shared>,
+ device: wgpu::Device,
+ blit_pipeline: wgpu::RenderPipeline,
+ blit_bind_group_layout: wgpu::BindGroupLayout,
+ blit_sampler: wgpu::Sampler,
}
-impl RenderSink for Renderer {
- fn exec(&mut self, action: GxAction) {
- // If the channel is full we drop the action rather than blocking the
- // CPU thread. In practice, the main thread should drain fast enough.
- let _ = self.tx.try_send(action);
+impl Renderer {
+ /// Create the renderer, spawning the worker thread. The caller must
+ /// provide a wgpu device and queue.
+ pub fn new(device: wgpu::Device, queue: wgpu::Queue, surface_format: wgpu::TextureFormat) -> Self {
+ let gx = GxRenderer::new(&device, &queue, surface_format);
+
+ // Initial shared output: the XFB view (black until first PresentXfb).
+ let shared = Arc::new(Shared {
+ output: Mutex::new(gx.xfb_view.clone()),
+ });
+
+ // Build the blit pipeline on the main-thread side.
+ let blit_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("efb_blit_shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/efb_blit.wgsl").into()),
+ });
+ let blit_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("blit_bgl"),
+ entries: &[
+ wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
+ wgpu::BindGroupLayoutEntry {
+ binding: 1,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+ let blit_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&blit_bind_group_layout],
+ immediate_size: 0,
+ });
+ let blit_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("blit_pipeline"),
+ layout: Some(&blit_layout),
+ vertex: wgpu::VertexState {
+ module: &blit_shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &blit_shader,
+ entry_point: Some("fs_main"),
+ targets: &[Some(wgpu::ColorTargetState {
+ format: surface_format,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState {
+ topology: wgpu::PrimitiveTopology::TriangleList,
+ ..Default::default()
+ },
+ depth_stencil: None,
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
+ let blit_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
+ label: Some("blit_sampler"),
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ });
+
+ let (tx, rx) = bounded(CHANNEL_CAPACITY);
+
+ // Spawn the worker.
+ let worker_shared = shared.clone();
+ let worker_device = device.clone();
+ let worker_queue = queue.clone();
+ std::thread::Builder::new()
+ .name("gx-renderer".into())
+ .spawn(move || worker(gx, worker_device, worker_queue, worker_shared, rx))
+ .expect("failed to spawn renderer worker");
+
+ Renderer {
+ tx,
+ shared,
+ device,
+ blit_pipeline,
+ blit_bind_group_layout,
+ blit_sampler,
+ }
}
-}
-impl ActionReceiver {
- /// Drain all pending actions into the provided buffer.
- pub fn drain(&self, buf: &mut Vec<GxAction>) {
- while let Ok(action) = self.rx.try_recv() {
- buf.push(action);
+ /// Blit the latest XFB output to the given render target. Called by the
+ /// main thread on each redraw.
+ pub fn blit(&self, queue: &wgpu::Queue, target: &wgpu::TextureView) {
+ let output = self.shared.output.lock().unwrap();
+ let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("blit_bg"),
+ layout: &self.blit_bind_group_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(&output),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::Sampler(&self.blit_sampler),
+ },
+ ],
+ });
+ drop(output);
+
+ let mut encoder = self.device.create_command_encoder(&Default::default());
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("xfb_blit"),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ depth_slice: None,
+ })],
+ depth_stencil_attachment: None,
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_pipeline(&self.blit_pipeline);
+ rpass.set_bind_group(0, &bind_group, &[]);
+ rpass.draw(0..3, 0..1);
}
+ queue.submit([encoder.finish()]);
}
+}
- /// Returns `true` when the emulator-side sender has been dropped.
- pub fn is_disconnected(&self) -> bool {
- // try_recv returning Disconnected means all senders are gone.
- matches!(self.rx.try_recv(), Err(crossbeam_channel::TryRecvError::Disconnected))
+impl RenderSink for Renderer {
+ fn exec(&mut self, action: GxAction) {
+ let _ = self.tx.send(action);
}
}
diff --git a/crates/dbglib/src/windows/gx.rs b/crates/dbglib/src/windows/gx.rs
index ee60e2a..4dad587 100644
--- a/crates/dbglib/src/windows/gx.rs
+++ b/crates/dbglib/src/windows/gx.rs
@@ -4,7 +4,7 @@ use gecko::flipper::gx::draw::TextureDescriptor;
use gecko::mmio::Mmio;
fn texture_preview(ui: &mut egui::Ui, tex: &TextureDescriptor, ram: &[u8]) {
- let rgba = backend_wgpu::texture::decode_to_rgba(ram, tex);
+ let rgba = gecko::flipper::gx::texture::decode_to_rgba(ram, tex);
let size = [tex.width as usize, tex.height as usize];
let image = egui::ColorImage::from_rgba_unmultiplied(size, &rgba);
let handle = ui.ctx().load_texture(
diff --git a/crates/gecko/src/flipper/gx/bp.rs b/crates/gecko/src/flipper/gx/bp.rs
index 12d1629..e2ec90f 100644
--- a/crates/gecko/src/flipper/gx/bp.rs
+++ b/crates/gecko/src/flipper/gx/bp.rs
@@ -183,7 +183,7 @@ impl GraphicsProcessor {
id,
width,
height,
- rgba: texture::decode_to_rgba(ram, &desc)
+ rgba: texture::decode_to_rgba(ram, &desc),
});
}
diff --git a/crates/gecko/src/flipper/gx/texture.rs b/crates/gecko/src/flipper/gx/texture.rs
index 75a0210..d4c01bc 100644
--- a/crates/gecko/src/flipper/gx/texture.rs
+++ b/crates/gecko/src/flipper/gx/texture.rs
@@ -41,251 +41,223 @@ pub fn raw_data_size(width: u32, height: u32, format: TextureFormat) -> usize {
(blocks_x * blocks_y * block_bytes) as usize
}
-#[inline(always)]
-fn put_pixel(rgba: &mut [u8], stride: usize, x: usize, y: usize, r: u8, g: u8, b: u8, a: u8) {
- let offset = (y * stride + x) * 4;
- rgba[offset] = r;
- rgba[offset + 1] = g;
- rgba[offset + 2] = b;
- rgba[offset + 3] = a;
-}
-
-#[inline(always)]
-fn expand_to_8bit(value: u16, max: u16) -> u8 {
- (value * 255 / max) as u8
-}
-
-#[inline(always)]
-fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
- let red_5bit = (packed >> 11) & 0x1F;
- let green_6bit = (packed >> 5) & 0x3F;
- let blue_5bit = packed & 0x1F;
- [
- expand_to_8bit(red_5bit, 31),
- expand_to_8bit(green_6bit, 63),
- expand_to_8bit(blue_5bit, 31),
- 255,
- ]
-}
-
-fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 8;
- const BLOCK_H: usize = 8;
- const BLOCK_BYTES: usize = 32;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
-
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
-
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+fn decode_i4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 8;
+ const BB: usize = 32;
+
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) / 2;
- if byte_offset >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let byte = read_u8_unchecked(src, blk + (ty * BW + tx) / 2);
+ let nibble = if tx & 1 == 0 { byte >> 4 } else { byte & 0x0F };
+ let i = expand_4_to_8(nibble);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, i]);
}
-
- let is_left_pixel = tile_x % 2 == 0;
- let nibble = if is_left_pixel {
- ram[byte_offset] >> 4
- } else {
- ram[byte_offset] & 0x0F
- };
-
- let intensity = expand_to_8bit(nibble as u16, 15);
- put_pixel(
- rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, intensity,
- );
}
}
}
}
}
-fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 8;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 32;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
-
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+fn decode_i8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 4;
+ const BB: usize = 32;
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let byte_offset = block_start + tile_y * BLOCK_W + tile_x;
- if byte_offset >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let i = read_u8_unchecked(src, blk + ty * BW + tx);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, i]);
}
-
- let intensity = ram[byte_offset];
- put_pixel(
- rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, intensity,
- );
}
}
}
}
}
-fn decode_ia4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 8;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 32;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
-
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+fn decode_ia4(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 8;
+ const BH: usize = 4;
+ const BB: usize = 32;
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let byte_offset = block_start + tile_y * BLOCK_W + tile_x;
- if byte_offset >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let packed = read_u8_unchecked(src, blk + ty * BW + tx);
+ let a = expand_4_to_8(packed >> 4);
+ let i = expand_4_to_8(packed & 0x0F);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, a]);
}
-
- let packed = ram[byte_offset];
- let alpha = expand_to_8bit((packed >> 4) as u16, 15);
- let intensity = expand_to_8bit((packed & 0x0F) as u16, 15);
- put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, alpha);
}
}
}
}
}
-fn decode_ia8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 4;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 32;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
+fn decode_ia8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
- if byte_offset + 1 >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let off = blk + (ty * BW + tx) * 2;
+ let a = read_u8_unchecked(src, off);
+ let i = read_u8_unchecked(src, off + 1);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [i, i, i, a]);
}
-
- let alpha = ram[byte_offset];
- let intensity = ram[byte_offset + 1];
- put_pixel(rgba, width, pixel_x, pixel_y, intensity, intensity, intensity, alpha);
}
}
}
}
}
-fn decode_rgb565(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 4;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 32;
+fn decode_rgb565(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
-
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
-
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
- if byte_offset + 1 >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let packed = read_be_u16_unchecked(src, blk + (ty * BW + tx) * 2);
+ let pixel = self::rgb565_to_rgba(packed);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, pixel);
}
-
- let [r, g, b, a] = rgb565_to_rgba(u16::from_be_bytes([ram[byte_offset], ram[byte_offset + 1]]));
- put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
}
}
}
}
}
-fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 4;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 32;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
-
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
-
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 32;
- let byte_offset = block_start + (tile_y * BLOCK_W + tile_x) * 2;
- if byte_offset + 1 >= ram.len() {
- continue;
- }
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let packed = u16::from_be_bytes([ram[byte_offset], ram[byte_offset + 1]]);
- let has_no_alpha = packed & 0x8000 != 0;
-
- if has_no_alpha {
- let r = expand_to_8bit((packed >> 10) & 0x1F, 31);
- let g = expand_to_8bit((packed >> 5) & 0x1F, 31);
- let b = expand_to_8bit(packed & 0x1F, 31);
- put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, 255);
- } else {
- let a = expand_to_8bit((packed >> 12) & 0x7, 7);
- let r = expand_to_8bit((packed >> 8) & 0xF, 15);
- let g = expand_to_8bit((packed >> 4) & 0xF, 15);
- let b = expand_to_8bit(packed & 0xF, 15);
- put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let packed = read_be_u16_unchecked(src, blk + (ty * BW + tx) * 2);
+ let pixel = if packed & 0x8000 != 0 {
+ let r = expand_5_to_8(((packed >> 10) & 0x1F) as u8);
+ let g = expand_5_to_8(((packed >> 5) & 0x1F) as u8);
+ let b = expand_5_to_8((packed & 0x1F) as u8);
+ [r, g, b, 255]
+ } else {
+ let a = expand_3_to_8(((packed >> 12) & 0x7) as u8);
+ let r = expand_4_to_8(((packed >> 8) & 0xF) as u8);
+ let g = expand_4_to_8(((packed >> 4) & 0xF) as u8);
+ let b = expand_4_to_8((packed & 0xF) as u8);
+ [r, g, b, a]
+ };
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, pixel);
}
}
}
@@ -293,83 +265,88 @@ fn decode_rgb5a3(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: u
}
}
-fn decode_rgba8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const BLOCK_W: usize = 4;
- const BLOCK_H: usize = 4;
- const BLOCK_BYTES: usize = 64;
-
- let blocks_x = width.div_ceil(BLOCK_W);
- let blocks_y = height.div_ceil(BLOCK_H);
+fn decode_rgba8(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const BW: usize = 4;
+ const BH: usize = 4;
+ const BB: usize = 64;
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let block_start = desc.ram_addr + (block_y * blocks_x + block_x) * BLOCK_BYTES;
-
- for tile_y in 0..BLOCK_H {
- for tile_x in 0..BLOCK_W {
- let pixel_x = block_x * BLOCK_W + tile_x;
- let pixel_y = block_y * BLOCK_H + tile_y;
- if pixel_x >= width || pixel_y >= height {
- continue;
- }
+ let bcx = w.div_ceil(BW);
+ let bcy = h.div_ceil(BH);
+ if desc.ram_addr + bcx * bcy * BB > ram.len() {
+ return;
+ }
- let texel_index = tile_y * BLOCK_W + tile_x;
- let ar_offset = block_start + texel_index * 2;
- let gb_offset = block_start + 32 + texel_index * 2;
- if gb_offset + 1 >= ram.len() {
- continue;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
+
+ for by in 0..bcy {
+ let base_y = by * BH;
+ let th = BH.min(h - base_y);
+ for bx in 0..bcx {
+ let base_x = bx * BW;
+ let tw = BW.min(w - base_x);
+ let blk = desc.ram_addr + (by * bcx + bx) * BB;
+
+ for ty in 0..th {
+ for tx in 0..tw {
+ unsafe {
+ let ti = ty * BW + tx;
+ let ar = blk + ti * 2;
+ let gb = blk + 32 + ti * 2;
+ let a = read_u8_unchecked(src, ar);
+ let r = read_u8_unchecked(src, ar + 1);
+ let g = read_u8_unchecked(src, gb);
+ let b = read_u8_unchecked(src, gb + 1);
+ write_pixel(dst, ((base_y + ty) * w + base_x + tx) * 4, [r, g, b, a]);
}
-
- let alpha = ram[ar_offset];
- let red = ram[ar_offset + 1];
- let green = ram[gb_offset];
- let blue = ram[gb_offset + 1];
- put_pixel(rgba, width, pixel_x, pixel_y, red, green, blue, alpha);
}
}
}
}
}
-fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usize, height: usize) {
- const MACRO_W: usize = 8;
- const MACRO_H: usize = 8;
- const MACRO_BYTES: usize = 32;
- const SUB_BLOCK_BYTES: usize = 8;
+fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], w: usize, h: usize) {
+ const MW: usize = 8;
+ const MH: usize = 8;
+ const MB: usize = 32;
+ const SB: usize = 8;
- let blocks_x = width.div_ceil(MACRO_W);
- let blocks_y = height.div_ceil(MACRO_H);
+ let bcx = w.div_ceil(MW);
+ let bcy = h.div_ceil(MH);
+ if desc.ram_addr + bcx * bcy * MB > ram.len() {
+ return;
+ }
- for block_y in 0..blocks_y {
- for block_x in 0..blocks_x {
- let macro_start = desc.ram_addr + (block_y * blocks_x + block_x) * MACRO_BYTES;
+ let src = ram.as_ptr();
+ let dst = rgba.as_mut_ptr();
- for sub_index in 0..4usize {
- let sub_start = macro_start + sub_index * SUB_BLOCK_BYTES;
- let sub_x_offset = (sub_index % 2) * 4;
- let sub_y_offset = (sub_index / 2) * 4;
+ for by in 0..bcy {
+ let macro_y = by * MH;
+ for bx in 0..bcx {
+ let macro_x = bx * MW;
+ let macro_off = desc.ram_addr + (by * bcx + bx) * MB;
- if sub_start + 7 >= ram.len() {
+ for si in 0..4usize {
+ let sub_off = macro_off + si * SB;
+ let sub_x = macro_x + (si & 1) * 4;
+ let sub_y = macro_y + (si >> 1) * 4;
+ if sub_x >= w || sub_y >= h {
continue;
}
-
- let color0 = u16::from_be_bytes([ram[sub_start], ram[sub_start + 1]]);
- let color1 = u16::from_be_bytes([ram[sub_start + 2], ram[sub_start + 3]]);
- let palette = build_dxt1_palette(color0, color1);
-
- for row in 0..4usize {
- let index_byte = ram[sub_start + 4 + row];
- for col in 0..4usize {
- let pixel_x = block_x * MACRO_W + sub_x_offset + col;
- let pixel_y = block_y * MACRO_H + sub_y_offset + row;
- if pixel_x >= width || pixel_y >= height {
- continue;
+ let tw = 4usize.min(w - sub_x);
+ let th = 4usize.min(h - sub_y);
+
+ unsafe {
+ let c0 = read_be_u16_unchecked(src, sub_off);
+ let c1 = read_be_u16_unchecked(src, sub_off + 2);
+ let palette = self::build_dxt1_palette(c0, c1);
+
+ for row in 0..th {
+ let idx = read_u8_unchecked(src, sub_off + 4 + row);
+ for col in 0..tw {
+ let pi = ((idx >> ((3 - col) * 2)) & 0x03) as usize;
+ write_pixel(dst, ((sub_y + row) * w + sub_x + col) * 4, palette[pi]);
}
-
- let shift = (3 - col) * 2;
- let palette_index = ((index_byte >> shift) & 0x03) as usize;
- let [r, g, b, a] = palette[palette_index];
- put_pixel(rgba, width, pixel_x, pixel_y, r, g, b, a);
}
}
}
@@ -377,25 +354,78 @@ fn decode_cmpr(ram: &[u8], desc: &TextureDescriptor, rgba: &mut [u8], width: usi
}
}
-fn build_dxt1_palette(color0: u16, color1: u16) -> [[u8; 4]; 4] {
- let [r0, g0, b0, _] = rgb565_to_rgba(color0);
- let [r1, g1, b1, _] = rgb565_to_rgba(color1);
+#[inline(always)]
+fn build_dxt1_palette(c0: u16, c1: u16) -> [[u8; 4]; 4] {
+ let [r0, g0, b0, _] = self::rgb565_to_rgba(c0);
+ let [r1, g1, b1, _] = self::rgb565_to_rgba(c1);
+
+ let mut p = [[0u8; 4]; 4];
+ p[0] = [r0, g0, b0, 255];
+ p[1] = [r1, g1, b1, 255];
+
+ if c0 > c1 {
+ p[2] = [
+ ((r0 as u16 * 2 + r1 as u16) / 3) as u8,
+ ((g0 as u16 * 2 + g1 as u16) / 3) as u8,
+ ((b0 as u16 * 2 + b1 as u16) / 3) as u8,
+ 255,
+ ];
+ p[3] = [
+ ((r0 as u16 + r1 as u16 * 2) / 3) as u8,
+ ((g0 as u16 + g1 as u16 * 2) / 3) as u8,
+ ((b0 as u16 + b1 as u16 * 2) / 3) as u8,
+ 255,
+ ];
+ } else {
+ let avg_r = ((r0 as u16 + r1 as u16) / 2) as u8;
+ let avg_g = ((g0 as u16 + g1 as u16) / 2) as u8;
+ let avg_b = ((b0 as u16 + b1 as u16) / 2) as u8;
+ p[2] = [avg_r, avg_g, avg_b, 255];
+ p[3] = [avg_r, avg_g, avg_b, 0];
+ }
- let blend = |a: u8, b: u8, weight_a: u16, weight_b: u16| -> u8 {
- ((a as u16 * weight_a + b as u16 * weight_b) / (weight_a + weight_b)) as u8
- };
+ p
+}
- let mut palette = [[0u8; 4]; 4];
- palette[0] = [r0, g0, b0, 255];
- palette[1] = [r1, g1, b1, 255];
+#[inline(always)]
+fn expand_3_to_8(v: u8) -> u8 {
+ (v << 5) | (v << 2) | (v >> 1)
+}
- if color0 > color1 {
- palette[2] = [blend(r0, r1, 2, 1), blend(g0, g1, 2, 1), blend(b0, b1, 2, 1), 255];
- palette[3] = [blend(r0, r1, 1, 2), blend(g0, g1, 1, 2), blend(b0, b1, 1, 2), 255];
- } else {
- palette[2] = [blend(r0, r1, 1, 1), blend(g0, g1, 1, 1), blend(b0, b1, 1, 1), 255];
- palette[3] = [0, 0, 0, 0];
- }
+#[inline(always)]
+fn expand_4_to_8(v: u8) -> u8 {
+ (v << 4) | v
+}
+
+#[inline(always)]
+fn expand_5_to_8(v: u8) -> u8 {
+ (v << 3) | (v >> 2)
+}
- palette
+#[inline(always)]
+fn expand_6_to_8(v: u8) -> u8 {
+ (v << 2) | (v >> 4)
+}
+
+#[inline(always)]
+fn rgb565_to_rgba(packed: u16) -> [u8; 4] {
+ let r = ((packed >> 11) & 0x1F) as u8;
+ let g = ((packed >> 5) & 0x3F) as u8;
+ let b = (packed & 0x1F) as u8;
+ [expand_5_to_8(r), expand_6_to_8(g), expand_5_to_8(b), 255]
+}
+
+#[inline(always)]
+unsafe fn write_pixel(dst: *mut u8, offset: usize, pixel: [u8; 4]) {
+ unsafe { std::ptr::write(dst.add(offset).cast::<[u8; 4]>(), pixel) };
+}
+
+#[inline(always)]
+unsafe fn read_u8_unchecked(src: *const u8, offset: usize) -> u8 {
+ unsafe { *src.add(offset) }
+}
+
+#[inline(always)]
+unsafe fn read_be_u16_unchecked(src: *const u8, offset: usize) -> u16 {
+ unsafe { u16::from_be_bytes([*src.add(offset), *src.add(offset + 1)]) }
}
diff --git a/crates/tinyapp/src/app.rs b/crates/tinyapp/src/app.rs
index 0c26c12..3031adb 100644
--- a/crates/tinyapp/src/app.rs
+++ b/crates/tinyapp/src/app.rs
@@ -5,7 +5,6 @@ use std::time::Instant;
use crossbeam_channel::Receiver;
use egui::ViewportId;
use gecko::flipper::si::pad::PadStatus;
-use gecko::host::GxAction;
use winit::application::ApplicationHandler;
use winit::event::WindowEvent;
use winit::event_loop::ActiveEventLoop;
@@ -20,10 +19,8 @@ pub struct State {
surface_config: wgpu::SurfaceConfiguration,
device: wgpu::Device,
queue: wgpu::Queue,
- gx_renderer: backend_wgpu::GxRenderer,
- action_rx: backend_wgpu::sink::ActionReceiver,
- action_buf: Vec<GxAction>,
- // egui overlay
+ renderer: backend_wgpu::sink::Renderer,
+
egui_ctx: egui::Context,
egui_renderer: egui_wgpu::Renderer,
egui_winit: egui_winit::State,
@@ -36,48 +33,15 @@ pub struct State {
impl State {
pub fn new(
window: Arc<Window>,
- present_mode: wgpu::PresentMode,
- action_rx: backend_wgpu::sink::ActionReceiver,
+ device: wgpu::Device,
+ queue: wgpu::Queue,
+ surface: wgpu::Surface<'static>,
+ surface_config: wgpu::SurfaceConfiguration,
+ renderer: backend_wgpu::sink::Renderer,
) -> Self {
- let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
- backends: wgpu::Backends::all(),
- ..Default::default()
- });
-
- let surface = instance.create_surface(window.clone()).unwrap();
-
- let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
- power_preference: wgpu::PowerPreference::default(),
- compatible_surface: Some(&surface),
- force_fallback_adapter: false,
- }))
- .unwrap();
-
- let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).unwrap();
-
- let size = window.inner_size();
- let surface_caps = surface.get_capabilities(&adapter);
-
- let gx_renderer = backend_wgpu::GxRenderer::new(&device, &queue, wgpu::TextureFormat::Bgra8Unorm);
-
- let surface_config = wgpu::SurfaceConfiguration {
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
- format: wgpu::TextureFormat::Bgra8Unorm,
- width: size.width.max(1),
- height: size.height.max(1),
- present_mode,
- alpha_mode: surface_caps.alpha_modes[0],
- view_formats: vec![],
- desired_maximum_frame_latency: 2,
- };
- surface.configure(&device, &surface_config);
-
let egui_ctx = egui::Context::default();
- let egui_renderer = egui_wgpu::Renderer::new(
- &device,
- wgpu::TextureFormat::Bgra8Unorm,
- egui_wgpu::RendererOptions::default(),
- );
+ let egui_renderer =
+ egui_wgpu::Renderer::new(&device, surface_config.format, egui_wgpu::RendererOptions::default());
let egui_winit = egui_winit::State::new(egui_ctx.clone(), ViewportId::ROOT, window.as_ref(), None, None, None);
State {
@@ -85,9 +49,7 @@ impl State {
surface_config,
device,
queue,
- gx_renderer,
- action_rx,
- action_buf: Vec::new(),
+ renderer,
egui_ctx,
egui_renderer,
egui_winit,
@@ -110,7 +72,7 @@ impl State {
fn render(&mut self, frame_rx: &Receiver<FrameMessage>, window: &Window) {
let mut msg: Option<FrameMessage> = None;
while let Ok(newer) = frame_rx.try_recv() {
- msg = Some(newer); // drain
+ msg = Some(newer);
}
let Some(msg) = msg else { return };
@@ -136,18 +98,8 @@ impl State {
};
let view = frame.texture.create_view(&Default::default());
- self.action_buf.clear();
- self.action_rx.drain(&mut self.action_buf);
-
- // Drive the GX renderer with any queued actions (draws into its EFB
- // and updates the snapshot on CopyEfb).
- if !self.action_buf.is_empty() {
- self.gx_renderer
- .render_actions(&self.device, &self.queue, &self.action_buf);
- }
-
- // Blit the latest EFB snapshot to the swapchain.
- self.gx_renderer.blit_to_target(&self.device, &self.queue, &view);
+ // Blit the latest XFB output from the renderer worker to the swapchain.
+ self.renderer.blit(&self.queue, &view);
// egui overlay
let raw_input = self.egui_winit.take_egui_input(window);
@@ -231,17 +183,22 @@ impl State {
}
}
-// ---------------------------------------------------------------------------
-// Winit application handler
-// ---------------------------------------------------------------------------
-
pub struct App {
pub frame_rx: Receiver<FrameMessage>,
- pub action_rx: Option<backend_wgpu::sink::ActionReceiver>,
pub input: Arc<Mutex<PadStatus>>,
pub window: Option<Arc<Window>>,
pub state: Option<State>,
pub present_mode: wgpu::PresentMode,
+ pub init: Option<AppInit>,
+}
+
+pub struct AppInit {
+ pub instance: wgpu::Instance,
+ pub adapter: wgpu::Adapter,
+ pub device: wgpu::Device,
+ pub queue: wgpu::Queue,
+ pub renderer: backend_wgpu::sink::Renderer,
+ pub surface_format: wgpu::TextureFormat,
}
impl ApplicationHandler for App {
@@ -252,8 +209,34 @@ impl ApplicationHandler for App {
.unwrap(),
);
- let action_rx = self.action_rx.take().expect("action_rx consumed twice");
- let state = State::new(window.clone(), self.present_mode, action_rx);
+ let Some(init) = self.init.take() else {
+ self.window = Some(window);
+ return;
+ };
+
+ let surface = init.instance.create_surface(window.clone()).unwrap();
+ let size = window.inner_size();
+ let surface_caps = surface.get_capabilities(&init.adapter);
+ let surface_config = wgpu::SurfaceConfiguration {
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
+ format: init.surface_format,
+ width: size.width.max(1),
+ height: size.height.max(1),
+ present_mode: self.present_mode,
+ alpha_mode: surface_caps.alpha_modes[0],
+ view_formats: vec![],
+ desired_maximum_frame_latency: 2,
+ };
+ surface.configure(&init.device, &surface_config);
+
+ let state = State::new(
+ window.clone(),
+ init.device,
+ init.queue,
+ surface,
+ surface_config,
+ init.renderer,
+ );
window.request_redraw();
self.window = Some(window);
self.state = Some(state);
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index 4ab2e63..c09e9bc 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -101,10 +101,28 @@ fn main() {
..PadStatus::default()
});
- // Create the action-stream channel and install the renderer sink on the
- // emulator so GX actions flow through automatically.
- let (renderer, action_rx) = backend_wgpu::sink::channel();
- emulator.render_sink = Box::new(renderer);
+ let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
+ backends: wgpu::Backends::all(),
+ ..Default::default()
+ });
+
+ let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
+ power_preference: wgpu::PowerPreference::default(),
+ compatible_surface: None,
+ force_fallback_adapter: false,
+ }))
+ .expect("no compatible wgpu adapter");
+
+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default()))
+ .expect("failed to acquire wgpu device");
+
+ let surface_format = wgpu::TextureFormat::Bgra8Unorm;
+
+ // Create the renderer (spawns the worker thread internally).
+ let renderer = backend_wgpu::sink::Renderer::new(device.clone(), queue.clone(), surface_format);
+
+ // Install the renderer as the emulator's render sink.
+ emulator.render_sink = Box::new(renderer.clone());
let input = Arc::new(Mutex::new(*emulator.primary_controller_mut()));
@@ -118,13 +136,21 @@ fn main() {
.name("emu".into())
.spawn(move || thread::emu_thread(emulator, frame_tx, emu_input, proxy))
.expect("failed to spawn emulator thread");
+
let mut app = app::App {
frame_rx,
- action_rx: Some(action_rx),
input,
window: None,
state: None,
present_mode,
+ init: Some(app::AppInit {
+ instance,
+ adapter,
+ device,
+ queue,
+ renderer,
+ surface_format,
+ }),
};
event_loop.run_app(&mut app).unwrap();
}