Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

triangle.dol works!

Laylee81d393242cd
diff --git a/Cargo.lock b/Cargo.lock
index d44a0c9..891fdcb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -175,6 +175,8 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
name = "backend-wgpu"
version = "0.1.0"
dependencies = [
+ "bytemuck",
+ "gekko",
"wgpu",
]
@@ -1904,6 +1906,7 @@ dependencies = [
name = "tinyapp"
version = "0.1.0"
dependencies = [
+ "backend-wgpu",
"gekko",
"image",
"pollster",
diff --git a/crates/backend-wgpu/Cargo.toml b/crates/backend-wgpu/Cargo.toml
index be6c024..d19ddf2 100644
--- a/crates/backend-wgpu/Cargo.toml
+++ b/crates/backend-wgpu/Cargo.toml
@@ -5,3 +5,5 @@ edition = "2024"
[dependencies]
wgpu = "28.0.0"
+bytemuck = { version = "1", features = ["derive"] }
+gekko = { path = "../gekko" }
diff --git a/crates/backend-wgpu/src/gx.wgsl b/crates/backend-wgpu/src/gx.wgsl
new file mode 100644
index 0000000..93c8646
--- /dev/null
+++ b/crates/backend-wgpu/src/gx.wgsl
@@ -0,0 +1,31 @@
+struct Uniforms {
+ mvp: mat4x4<f32>,
+};
+
+@group(0) @binding(0)
+var<uniform> uniforms: Uniforms;
+
+struct VsIn {
+ @location(0) position: vec3<f32>,
+ @location(1) color: vec4<f32>,
+};
+
+struct VsOut {
+ @builtin(position) clip_pos: vec4<f32>,
+ @location(0) color: vec4<f32>,
+};
+
+@vertex
+fn vs_main(in: VsIn) -> VsOut {
+ var out: VsOut;
+ out.clip_pos = uniforms.mvp * vec4<f32>(in.position, 1.0);
+ // Remap depth: GameCube/OpenGL uses [-1,1], wgpu uses [0,1]
+ out.clip_pos.z = out.clip_pos.z * 0.5 + out.clip_pos.w * 0.5;
+ out.color = in.color;
+ return out;
+}
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ return in.color;
+}
diff --git a/crates/backend-wgpu/src/lib.rs b/crates/backend-wgpu/src/lib.rs
index b93cf3f..f0ceaf0 100644
--- a/crates/backend-wgpu/src/lib.rs
+++ b/crates/backend-wgpu/src/lib.rs
@@ -1,14 +1,248 @@
-pub fn add(left: u64, right: u64) -> u64 {
- left + right
+use gekko::flipper::gx::draw::{DrawCall, DrawCommands, Primitive};
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct GpuVertex {
+ position: [f32; 3],
+ color: [f32; 4],
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
+struct Uniforms {
+ mvp: [[f32; 4]; 4],
+}
+
+const SHADER: &str = include_str!("gx.wgsl");
+
+pub struct GxRenderer {
+ pipeline: wgpu::RenderPipeline,
+ bind_group: wgpu::BindGroup,
+ uniform_buffer: wgpu::Buffer,
+ vertex_buffer: wgpu::Buffer,
+ vertex_capacity: usize,
+ depth_texture: wgpu::Texture,
+ depth_view: wgpu::TextureView,
+}
+
+impl GxRenderer {
+ pub fn new(device: &wgpu::Device, surface_format: wgpu::TextureFormat, width: u32, height: u32) -> Self {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("gx_shader"),
+ source: wgpu::ShaderSource::Wgsl(SHADER.into()),
+ });
+
+ let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: None,
+ entries: &[wgpu::BindGroupLayoutEntry {
+ binding: 0,
+ visibility: wgpu::ShaderStages::VERTEX,
+ ty: wgpu::BindingType::Buffer {
+ ty: wgpu::BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: None,
+ },
+ count: None,
+ }],
+ });
+
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&bind_group_layout],
+ immediate_size: 0,
+ });
+
+ let vertex_layout = wgpu::VertexBufferLayout {
+ array_stride: std::mem::size_of::<GpuVertex>() as u64,
+ step_mode: wgpu::VertexStepMode::Vertex,
+ attributes: &[
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x3,
+ offset: 0,
+ shader_location: 0,
+ },
+ wgpu::VertexAttribute {
+ format: wgpu::VertexFormat::Float32x4,
+ offset: 12,
+ shader_location: 1,
+ },
+ ],
+ };
+
+ let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some("gx_pipeline"),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[vertex_layout],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &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,
+ front_face: wgpu::FrontFace::Cw,
+ cull_mode: None,
+ ..Default::default()
+ },
+ depth_stencil: Some(wgpu::DepthStencilState {
+ format: wgpu::TextureFormat::Depth24Plus,
+ depth_write_enabled: true,
+ depth_compare: wgpu::CompareFunction::LessEqual,
+ stencil: wgpu::StencilState::default(),
+ bias: wgpu::DepthBiasState::default(),
+ }),
+ multisample: wgpu::MultisampleState::default(),
+ multiview_mask: None,
+ cache: None,
+ });
+
+ let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("gx_uniforms"),
+ size: std::mem::size_of::<Uniforms>() as u64,
+ usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: None,
+ layout: &bind_group_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: uniform_buffer.as_entire_binding(),
+ }],
+ });
+
+ 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 (depth_texture, depth_view) = create_depth_texture(device, width, height);
+
+ GxRenderer {
+ pipeline,
+ bind_group,
+ uniform_buffer,
+ vertex_buffer,
+ vertex_capacity: initial_capacity,
+ depth_texture,
+ depth_view,
+ }
+ }
+
+ pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
+ let (tex, view) = create_depth_texture(device, width, height);
+ self.depth_texture = tex;
+ self.depth_view = view;
+ }
+
+ pub fn render(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ commands: &DrawCommands,
+ target: &wgpu::TextureView,
+ ) {
+ let mvp = commands.projection * commands.modelview;
+ queue.write_buffer(&self.uniform_buffer, 0, bytemuck::bytes_of(&Uniforms { mvp: mvp.0 }));
+
+ let vertices = triangulate(&commands.commands);
+ if vertices.is_empty() {
+ return;
+ }
+
+ if vertices.len() > self.vertex_capacity {
+ self.vertex_capacity = 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,
+ mapped_at_creation: false,
+ });
+ }
+
+ queue.write_buffer(&self.vertex_buffer, 0, bytemuck::cast_slice(&vertices));
+
+ let mut encoder = device.create_command_encoder(&Default::default());
+ {
+ let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some("gx_render_pass"),
+ 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: Some(wgpu::RenderPassDepthStencilAttachment {
+ view: &self.depth_view,
+ depth_ops: Some(wgpu::Operations {
+ load: wgpu::LoadOp::Clear(1.0),
+ store: wgpu::StoreOp::Store,
+ }),
+ stencil_ops: None,
+ }),
+ occlusion_query_set: None,
+ timestamp_writes: None,
+ multiview_mask: None,
+ });
+ rpass.set_pipeline(&self.pipeline);
+ rpass.set_bind_group(0, &self.bind_group, &[]);
+ rpass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+ rpass.draw(0..vertices.len() as u32, 0..1);
+ }
+
+ queue.submit([encoder.finish()]);
+ }
}
-#[cfg(test)]
-mod tests {
- use super::*;
+fn create_depth_texture(device: &wgpu::Device, w: u32, h: u32) -> (wgpu::Texture, wgpu::TextureView) {
+ let tex = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("gx_depth"),
+ size: wgpu::Extent3d {
+ width: w.max(1),
+ height: h.max(1),
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Depth24Plus,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
+ view_formats: &[],
+ });
+ let view = tex.create_view(&Default::default());
+ (tex, view)
+}
- #[test]
- fn it_works() {
- let result = add(2, 2);
- assert_eq!(result, 4);
+fn triangulate(draw_calls: &[DrawCall]) -> Vec<GpuVertex> {
+ let mut out = Vec::new();
+ for dc in draw_calls {
+ match dc.primitive {
+ Primitive::Triangles => {
+ for v in &dc.vertices {
+ out.push(GpuVertex {
+ position: v.position,
+ color: v.color0,
+ });
+ }
+ }
+ }
}
+ out
}
diff --git a/crates/gekko/src/flipper/gx.rs b/crates/gekko/src/flipper/gx.rs
index 08006ef..2b70c31 100644
--- a/crates/gekko/src/flipper/gx.rs
+++ b/crates/gekko/src/flipper/gx.rs
@@ -225,12 +225,12 @@ impl Gx {
fn rebuild_modelview(&mut self) {
let b = XF_MODELVIEW_BASE;
- self.draw_commands.modelview = [
+ self.draw_commands.modelview = draw::Matrix4([
[self.xf_f32(b), self.xf_f32(b + 4), self.xf_f32(b + 8), 0.0],
[self.xf_f32(b + 1), self.xf_f32(b + 5), self.xf_f32(b + 9), 0.0],
[self.xf_f32(b + 2), self.xf_f32(b + 6), self.xf_f32(b + 10), 0.0],
[self.xf_f32(b + 3), self.xf_f32(b + 7), self.xf_f32(b + 11), 1.0],
- ];
+ ]);
}
fn rebuild_projection(&mut self) {
@@ -245,20 +245,20 @@ impl Gx {
self.draw_commands.projection = if proj_type == 0 {
// Perspective
- [
+ draw::Matrix4([
[pm1, 0.0, 0.0, 0.0],
[0.0, pm3, 0.0, 0.0],
[pm2, pm4, pm5, -1.0],
[0.0, 0.0, pm6, 0.0],
- ]
+ ])
} else {
// Orthographic
- [
+ draw::Matrix4([
[pm1, 0.0, 0.0, 0.0],
[0.0, pm3, 0.0, 0.0],
[0.0, 0.0, pm5, 0.0],
[pm2, pm4, pm6, 1.0],
- ]
+ ])
};
}
diff --git a/crates/gekko/src/flipper/gx/draw.rs b/crates/gekko/src/flipper/gx/draw.rs
index 032f56b..8be5f77 100644
--- a/crates/gekko/src/flipper/gx/draw.rs
+++ b/crates/gekko/src/flipper/gx/draw.rs
@@ -28,11 +28,36 @@ pub struct DrawCall {
pub vertices: Vec<Vertex>,
}
-pub type Matrix4 = [[f32; 4]; 4];
+#[derive(Debug, Clone, Copy)]
+pub struct Matrix4(pub [[f32; 4]; 4]);
+
+impl Default for Matrix4 {
+ fn default() -> Self {
+ Matrix4([[0.0; 4]; 4])
+ }
+}
+
+impl std::ops::Mul for Matrix4 {
+ type Output = Matrix4;
+
+ fn mul(self, rhs: Matrix4) -> Matrix4 {
+ let (a, b) = (&self.0, &rhs.0);
+ let mut out = [[0.0f32; 4]; 4];
+ for col in 0..4 {
+ for row in 0..4 {
+ out[col][row] = a[0][row] * b[col][0]
+ + a[1][row] * b[col][1]
+ + a[2][row] * b[col][2]
+ + a[3][row] * b[col][3];
+ }
+ }
+ Matrix4(out)
+ }
+}
#[derive(Default)]
pub struct DrawCommands {
- pub modelview: Matrix4, // where is this triangle relative to the camera?
- pub projection: Matrix4, // how is the 3D scene projected onto the 2D screen?
- pub commands: Vec<DrawCall>, // the actual draw calls to execute
+ pub modelview: Matrix4,
+ pub projection: Matrix4,
+ pub commands: Vec<DrawCall>,
}
\ No newline at end of file
diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.toml
index 15121c1..ac723ad 100644
--- a/crates/tinyapp/Cargo.toml
+++ b/crates/tinyapp/Cargo.toml
@@ -6,6 +6,7 @@ edition = "2024"
[dependencies]
gekko = { path = "../gekko" }
image = { path = "../image" }
+backend-wgpu = { path = "../backend-wgpu" }
wgpu = "28.0.0"
winit = "0.30"
pollster = "0.4"
diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rs
index 8627b1f..ebb5d54 100644
--- a/crates/tinyapp/src/main.rs
+++ b/crates/tinyapp/src/main.rs
@@ -9,38 +9,7 @@ use winit::{
window::{Window, WindowId},
};
-const SHADER: &str = r#"
-struct VsOut {
- @builtin(position) pos: vec4<f32>,
- @location(0) uv: vec2<f32>,
-}
-
-@vertex
-fn vs_main(@builtin(vertex_index) i: u32) -> VsOut {
- var pos = array<vec2<f32>, 3>(
- vec2<f32>(-1.0, 1.0),
- vec2<f32>( 3.0, 1.0),
- vec2<f32>(-1.0, -3.0),
- );
- var uv = array<vec2<f32>, 3>(
- vec2<f32>(0.0, 0.0),
- vec2<f32>(2.0, 0.0),
- vec2<f32>(0.0, 2.0),
- );
- var out: VsOut;
- out.pos = vec4<f32>(pos[i], 0.0, 1.0);
- out.uv = uv[i];
- return out;
-}
-
-@group(0) @binding(0) var xfb_tex: texture_2d<f32>;
-@group(0) @binding(1) var xfb_sam: sampler;
-
-@fragment
-fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
- return textureSample(xfb_tex, xfb_sam, in.uv);
-}
-"#;
+const SHADER: &str = include_str!("xfb.wgsl");
struct State {
surface: wgpu::Surface<'static>,
@@ -53,6 +22,7 @@ struct State {
bind_group: wgpu::BindGroup,
tex_width: u32,
tex_height: u32,
+ gx_renderer: backend_wgpu::GxRenderer,
}
impl State {
@@ -74,8 +44,7 @@ impl State {
}))
.unwrap();
- let (device, queue) =
- pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor::default())).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);
@@ -159,6 +128,7 @@ impl State {
});
let (texture, bind_group) = create_xfb_texture(&device, &bind_group_layout, w, h);
+ let gx_renderer = backend_wgpu::GxRenderer::new(&device, surface_format, w, h);
State {
surface,
@@ -171,6 +141,7 @@ impl State {
bind_group,
tex_width: w,
tex_height: h,
+ gx_renderer,
}
}
@@ -181,10 +152,37 @@ impl State {
self.surface_config.width = width;
self.surface_config.height = height;
self.surface.configure(&self.device, &self.surface_config);
+ self.gx_renderer.resize(&self.device, width, height);
}
fn render(&mut self, emulator: &mut Gekko) {
emulator.run_until_vsync();
+
+ let frame = match self.surface.get_current_texture() {
+ Ok(f) => f,
+ Err(e) => {
+ eprintln!("surface error: {e}");
+ return;
+ }
+ };
+ let view = frame.texture.create_view(&Default::default());
+
+ if !emulator.gx.draw_commands.commands.is_empty() {
+ self.render_gx(emulator, &view);
+ } else {
+ self.render_xfb(emulator, &view);
+ }
+
+ frame.present();
+ }
+
+ fn render_gx(&mut self, emulator: &mut Gekko, view: &wgpu::TextureView) {
+ self.gx_renderer
+ .render(&self.device, &self.queue, &emulator.gx.draw_commands, view);
+ emulator.gx.draw_commands.commands.clear();
+ }
+
+ fn render_xfb(&mut self, emulator: &Gekko, view: &wgpu::TextureView) {
let pixels = emulator.render_xfb();
let (w, h) = emulator.frame_size();
let (w, h) = (w as u32, h as u32);
@@ -222,21 +220,12 @@ impl State {
},
);
- let frame = match self.surface.get_current_texture() {
- Ok(f) => f,
- Err(e) => {
- eprintln!("surface error: {e}");
- return;
- }
- };
- let view = frame.texture.create_view(&Default::default());
-
let mut encoder = self.device.create_command_encoder(&Default::default());
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &view,
+ view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
@@ -255,7 +244,6 @@ impl State {
}
self.queue.submit([encoder.finish()]);
- frame.present();
}
}
diff --git a/crates/tinyapp/src/xfb.wgsl b/crates/tinyapp/src/xfb.wgsl
new file mode 100644
index 0000000..697ce0e
--- /dev/null
+++ b/crates/tinyapp/src/xfb.wgsl
@@ -0,0 +1,30 @@
+struct VsOut {
+ @builtin(position) pos: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+}
+
+@vertex
+fn vs_main(@builtin(vertex_index) i: u32) -> VsOut {
+ var pos = array<vec2<f32>, 3>(
+ vec2<f32>(-1.0, 1.0),
+ vec2<f32>( 3.0, 1.0),
+ vec2<f32>(-1.0, -3.0),
+ );
+ var uv = array<vec2<f32>, 3>(
+ vec2<f32>(0.0, 0.0),
+ vec2<f32>(2.0, 0.0),
+ vec2<f32>(0.0, 2.0),
+ );
+ var out: VsOut;
+ out.pos = vec4<f32>(pos[i], 0.0, 1.0);
+ out.uv = uv[i];
+ return out;
+}
+
+@group(0) @binding(0) var xfb_tex: texture_2d<f32>;
+@group(0) @binding(1) var xfb_sam: sampler;
+
+@fragment
+fn fs_main(in: VsOut) -> @location(0) vec4<f32> {
+ return textureSample(xfb_tex, xfb_sam, in.uv);
+}