SlideShare a Scribd company logo
Build Gameboy Emulator in Rust and
WebAssembly
Author: Yodalee
<lc85301@gmail.com>
Outline
1. Inside Gameboy
2. Gameboy Emulator in Rust
3. Migrate Rust to WebAssembly
Star Me on Github!
Source Code
https://github.com/yodalee/ruGameboy
Note: (Traditional Chinese)
https://yodalee.me/tags/gameboy/
Inside Gameboy
Gameboy
4MHz 8-bit Sharp LR35902
32KB Cartridge
8KB SRAM
8KB Video RAM
160x144 LCD screen
CPU Register
D15..D8 D7..D0
A F
B C
D E
H L
D15..D0
SP (stack pointer)
PC (program counter)
Flag Register
Z N H C 0 0 0 0
Z - Zero Flag
N - Subtract Flag
H - Half Carry Flag
C - Carry Flag
0 - Not used, always zero
CPU Instruction
4MHz CPU based on Intel 8080 and Z80.
245 instructions and another 256 extended (CB) instructions
Memory Layout
Start Size Description
0x0000 32 KB Cartridge ROM
0x8000 6 KB GPU Tile Content
0x9800 2 KB GPU Background Index
0xC000 8KB RAM
0xFE00 160 Bytes GPU Foreground Index
GPU Tile
1 tile = 8x8 = 64 pixels.
256
256
2 bits/pixel
1 tile = 16 bytes
Virtual Screen = 1024 Tiles
GPU Background
...
VRAM 0x8000-0xA000 (8K)
1. 0x8000-0x9000 or 0x8800-0x9800 => 4KB / 16B = 256 Tiles
2. 0x9800-0x9C00 or 0x9C00-A000 => 1KB = Tiles index
0x9800 - 0x9C00
Tile Index Table
From 0xFE00 to 0xFE9F = 160 bytes
4 bytes per Sprite => 40 Sprite
Sprite Size = 1 Tile = 8x8
GPU Sprite Foreground
Byte 0 Offset X
Byte 1 Offset Y
Byte 2 Tile Index
Byte 3 Flags: x flip, y flip, etc.
Note the width:
8 pixels
Line 0
Line 1
Line 2
Line 143
HBlank
VBlank
GPU Timing
160
144
Mode Cycle
Scanline Sprite 80
Scanline BG 172
HBlank 204
VBlank 4560 (10 lines)
Total 70224
4 MHz clock
70224 cycles ~= 0.0176s ~= 60 Hz
Gameboy Emulator in Rust
Emulator Architecture
GPU Cartridge RAM ….
Bus Register
VM
CPU
Display Buffer
Implement Register
F register All Register Interface
pub struct
FlagRegister {
pub zero: bool,
pub subtract: bool,
pub half_carry: bool,
pub carry: bool
}
pub struct Register {
pub a: u8,
pub b: u8,
pub c: u8,
pub d: u8,
pub e: u8,
pub f: FlagRegister,
pub h: u8,
pub l: u8,
}
impl Register {
fn get_hl() -> u16 {
(self.h as u16) << 8 | self.l as u16
}
fn set_hl(&mut self, value: u16) {
self.h = ((value >> 8) & 0xff) as u8;
self.l = (value & 0xff) as u8;
}
//...
}
Encode Instruction to Enum
Register X,Y Move Register X to Y Byte to Instruction
enum Target
{
A,
B,
C,
...
}
enum Instruction {
NOP
LDRR(Target, Target)
ADD(Target)
...
}
impl Instruction {
fn from_byte(u8) -> Instruction {
0x00 => Instruction::NOP,
0x01 => //…
0x02 => //…
//…
}
}
Implement CPU
CPU Step
pub struct Cpu {
regs: Register,
sp: u16,
pub pc: u16,
pub bus: Bus,
}
let byte = self.load(self.pc);
self.pc + 1;
let inst = Instruction::from_byte(byte);
match inst {
Instruction::JPHL => self.pc = self.regs.get_hl(),
Instruction::LDRR(source, target) => {
match (&source, &target) {
(&Target::C, &Target::B) => self.regs.b = self.regs.c,
//...
Implement Bus
Device Load/Store
pub trait Device {
fn load(&self, addr: u16) ->
Result<u8, ()>;
fn store(&mut self, addr: u16,
value: u8) -> Result<(), ()>;
}
impl Bus {
fn load(&self, addr: u16) -> Result<u8, ()> {
match addr {
CATRIDGE_START ..= CATRIDGE_END =>
self.cartridge.load(addr),
VRAM_START ..= VRAM_END =>
self.gpu.load(addr),
RAM_START ..= RAM_END =>
self.ram.load(addr),
//...
Implement Gpu
Sprite Gpu Render
struct Sprite {
tile_idx: u8,
x: isize,
y: isize,
// flag...
}
struct Gpu {
sprite: [Sprite:40]
vram: Vec<u8>,
oam: Vec<u8>,
//...
}
impl Device for Gpu {
//...
fn build_background(&mut self, buffer: &mut
Vec<u32>) {
for row in 0..HEIGHT {
for col in 0..WIDTH {
let tile_addr = row * 32 + col;
let tile_idx = self.vram[tile_addr];
let pixels = self.get_tile(tile_idx);
buffer.splice(start..end, pixels.iter()...);
VM
Screen built with minifb.
Loop:
1. run CPU until VBlank
2. Render Screen.
Let GPU fill display buffer Vec<u32>
Migrate Rust to WebAssembly
Rust x WebAssembly
https://rustwasm.github.io/book/
Tool needed:
1. rustup install
wasm32-unknown-unknown
2. wasm-pack
3. cargo-generate
4. npm
Migration Step
1. cargo generate --git https://github.com/rustwasm/wasm-pack-template
2. Expose Interface to Javascript
3. wasm-pack build
4. Import WebAssembly from Javascript
Done
https://github.com/yodalee/
wasm_gameboy
Expose Interface to Javascript
Magic Word
#[wasm_bindgen]
wasm_bindgen
// rust
#[wasm_bindgen]
pub struct Gameboy {
cartridge: Vec<u8>,
vm: Option<Vm>
}
// javascript
import Gameboy from "wasmgb"
Gameboy.new()
wasm_bindgen
// rust
#[wasm_bindgen]
impl Gameboy {
pub fn get_buffer(&self) -> *const u32 {
self.vm.buffer.as_ptr()
}
}
// javascript
import memory from "wasmgb_bg"
const buffer = gameboy.get_buffer();
const pixels = new
Uint32Array(memory.buffer, buffer,
width*height);
Import WebAssembly from Javascript
<body>
<input type="file" id="file-uploader"/>
<canvas id="gameboy-canvas"></canvas>
<pre id="gameboy-log"></pre>
<script src="./bootstrap.js"></script>
</body>
Import WebAssembly from Javascript
reader.onload = function() {
const cartridge = gameboy.get_cartridge();
var bytes = new Uint8Array(reader.result);
const m_cartridge = new Uint8Array(memory.buffer, cartridge, 0x8000);
// set cartridge
for (let idx = 0; idx < 0x8000; idx++) {
m_cartridge[idx] = bytes[idx];
}
gameboy.set_cartridge();
Import WebAssembly from Javascript
const renderLoop = () => {
drawPixels();
gameboy.step();
}
const drawPixels = () => {
const buffer = gameboy.get_buffer();
const pixels = new Uint32Array(memory.buffer, buffer, width * height);
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
if (pixels[row * width + col] == WHITE) { //...
Done
Conclusion
Future Work
Features to implement:
● Right now only Tetris can work (゚д゚;)
● Implement Sound
Problem to solve:
● How to emulate program in correct timing?
● How to debug efficiently?
Conclusion
1. We learn how to build emulator by building it.
2. A Rust program can be migrated to WebAssembly really quick.
Thanks for Listening

More Related Content

What's hot

Linux PCI device driver
Linux PCI device driverLinux PCI device driver
Linux PCI device driver
艾鍗科技
 
QEMU and Raspberry Pi. Instant Embedded Development
QEMU and Raspberry Pi. Instant Embedded DevelopmentQEMU and Raspberry Pi. Instant Embedded Development
QEMU and Raspberry Pi. Instant Embedded Development
GlobalLogic Ukraine
 
The Yocto Project
The Yocto ProjectThe Yocto Project
The Yocto Project
rossburton
 
Project ACRN hypervisor introduction
Project ACRN hypervisor introduction Project ACRN hypervisor introduction
Project ACRN hypervisor introduction
Project ACRN
 
Linux SD/MMC device driver
Linux SD/MMC device driverLinux SD/MMC device driver
Linux SD/MMC device driver
艾鍗科技
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
Zhen Wei
 
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULEWIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
Eng.Manfred Kibona
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Tegra 186のu-boot & Linux
Tegra 186のu-boot & LinuxTegra 186のu-boot & Linux
Tegra 186のu-boot & Linux
Mr. Vengineer
 
Présentation FPGA
Présentation FPGAPrésentation FPGA
Présentation FPGA
Yann Sionneau
 
Gorush: A push notification server written in Go
Gorush: A push notification server written in GoGorush: A push notification server written in Go
Gorush: A push notification server written in Go
Bo-Yi Wu
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratch
linuxlab_conf
 
Introduction to CMake
Introduction to CMakeIntroduction to CMake
Introduction to CMake
Dimitrios Platis
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
Kernel TLV
 

What's hot (14)

Linux PCI device driver
Linux PCI device driverLinux PCI device driver
Linux PCI device driver
 
QEMU and Raspberry Pi. Instant Embedded Development
QEMU and Raspberry Pi. Instant Embedded DevelopmentQEMU and Raspberry Pi. Instant Embedded Development
QEMU and Raspberry Pi. Instant Embedded Development
 
The Yocto Project
The Yocto ProjectThe Yocto Project
The Yocto Project
 
Project ACRN hypervisor introduction
Project ACRN hypervisor introduction Project ACRN hypervisor introduction
Project ACRN hypervisor introduction
 
Linux SD/MMC device driver
Linux SD/MMC device driverLinux SD/MMC device driver
Linux SD/MMC device driver
 
from Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Worksfrom Binary to Binary: How Qemu Works
from Binary to Binary: How Qemu Works
 
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULEWIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
WIRELESS HOME AUTOMATION USING PIC MICROCONTROLLER BASED ON RF-MODULE
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Tegra 186のu-boot & Linux
Tegra 186のu-boot & LinuxTegra 186のu-boot & Linux
Tegra 186のu-boot & Linux
 
Présentation FPGA
Présentation FPGAPrésentation FPGA
Présentation FPGA
 
Gorush: A push notification server written in Go
Gorush: A push notification server written in GoGorush: A push notification server written in Go
Gorush: A push notification server written in Go
 
Jagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratchJagan Teki - U-boot from scratch
Jagan Teki - U-boot from scratch
 
Introduction to CMake
Introduction to CMakeIntroduction to CMake
Introduction to CMake
 
Building Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCCBuilding Network Functions with eBPF & BCC
Building Network Functions with eBPF & BCC
 

Similar to Gameboy emulator in rust and web assembly

Introduction to .NET Micro Framework Development
Introduction to .NET Micro Framework DevelopmentIntroduction to .NET Micro Framework Development
Introduction to .NET Micro Framework Development
christopherfairbairn
 
Raspberry Pi tutorial
Raspberry Pi tutorialRaspberry Pi tutorial
Raspberry Pi tutorial
艾鍗科技
 
There is more to C
There is more to CThere is more to C
There is more to C
Juraj Michálek
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
Satpal Parmar
 
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
Felipe Prado
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Jian-Hong Pan
 
Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023
Igalia
 
Revelation pyconuk2016
Revelation pyconuk2016Revelation pyconuk2016
Revelation pyconuk2016
Sarah Mount
 
Exploiting buffer overflows
Exploiting buffer overflowsExploiting buffer overflows
Exploiting buffer overflows
Paul Dutot IEng MIET MBCS CITP OSCP CSTM
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications development
OOO "Program Verification Systems"
 
Shrink to grow
Shrink to growShrink to grow
Shrink to grow
Daniel Bovensiepen
 
Basic Linux kernel
Basic Linux kernelBasic Linux kernel
Basic Linux kernel
Morteza Nourelahi Alamdari
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
RuggedBoardGroup
 
Debugging node in prod
Debugging node in prodDebugging node in prod
Debugging node in prod
Yunong Xiao
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
Study on Android Emulator
Study on Android EmulatorStudy on Android Emulator
Study on Android Emulator
Samael Wang
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Plugins
amiable_indian
 
Qemu Pcie
Qemu PcieQemu Pcie
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
Andrey Karpov
 
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
ryancox
 

Similar to Gameboy emulator in rust and web assembly (20)

Introduction to .NET Micro Framework Development
Introduction to .NET Micro Framework DevelopmentIntroduction to .NET Micro Framework Development
Introduction to .NET Micro Framework Development
 
Raspberry Pi tutorial
Raspberry Pi tutorialRaspberry Pi tutorial
Raspberry Pi tutorial
 
There is more to C
There is more to CThere is more to C
There is more to C
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
DEF CON 27 - HUBER AND ROSKOSCH - im on your phone listening attacking voip c...
 
Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021Let's trace Linux Lernel with KGDB @ COSCUP 2021
Let's trace Linux Lernel with KGDB @ COSCUP 2021
 
Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023Debugging GPU faults: QoL tools for your driver – XDC 2023
Debugging GPU faults: QoL tools for your driver – XDC 2023
 
Revelation pyconuk2016
Revelation pyconuk2016Revelation pyconuk2016
Revelation pyconuk2016
 
Exploiting buffer overflows
Exploiting buffer overflowsExploiting buffer overflows
Exploiting buffer overflows
 
PVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications developmentPVS-Studio, a solution for resource intensive applications development
PVS-Studio, a solution for resource intensive applications development
 
Shrink to grow
Shrink to growShrink to grow
Shrink to grow
 
Basic Linux kernel
Basic Linux kernelBasic Linux kernel
Basic Linux kernel
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
Debugging node in prod
Debugging node in prodDebugging node in prod
Debugging node in prod
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Study on Android Emulator
Study on Android EmulatorStudy on Android Emulator
Study on Android Emulator
 
Writing Metasploit Plugins
Writing Metasploit PluginsWriting Metasploit Plugins
Writing Metasploit Plugins
 
Qemu Pcie
Qemu PcieQemu Pcie
Qemu Pcie
 
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
PVS-Studio 5.00, a solution for developers of modern resource-intensive appl...
 
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
Developing Applications for Beagle Bone Black, Raspberry Pi and SoC Single Bo...
 

More from Yodalee

COSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdfCOSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdf
Yodalee
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
Yodalee
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst Framework
Yodalee
 
Build Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube ClockBuild Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube Clock
Yodalee
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetris
Yodalee
 
Office word skills
Office word skillsOffice word skills
Office word skills
Yodalee
 
Git: basic to advanced
Git: basic to advancedGit: basic to advanced
Git: basic to advanced
Yodalee
 

More from Yodalee (7)

COSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdfCOSCUP2023 RSA256 Verilator.pdf
COSCUP2023 RSA256 Verilator.pdf
 
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdfrrxv6 Build a Riscv xv6 Kernel in Rust.pdf
rrxv6 Build a Riscv xv6 Kernel in Rust.pdf
 
Make A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst FrameworkMake A Shoot ‘Em Up Game with Amethyst Framework
Make A Shoot ‘Em Up Game with Amethyst Framework
 
Build Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube ClockBuild Yourself a Nixie Tube Clock
Build Yourself a Nixie Tube Clock
 
Introduction to nand2 tetris
Introduction to nand2 tetrisIntroduction to nand2 tetris
Introduction to nand2 tetris
 
Office word skills
Office word skillsOffice word skills
Office word skills
 
Git: basic to advanced
Git: basic to advancedGit: basic to advanced
Git: basic to advanced
 

Recently uploaded

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
Kamal Acharya
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
zwunae
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 

Recently uploaded (20)

Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Water billing management system project report.pdf
Water billing management system project report.pdfWater billing management system project report.pdf
Water billing management system project report.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
一比一原版(UMich毕业证)密歇根大学|安娜堡分校毕业证成绩单专业办理
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 

Gameboy emulator in rust and web assembly

  • 1. Build Gameboy Emulator in Rust and WebAssembly Author: Yodalee <lc85301@gmail.com>
  • 2. Outline 1. Inside Gameboy 2. Gameboy Emulator in Rust 3. Migrate Rust to WebAssembly
  • 3. Star Me on Github! Source Code https://github.com/yodalee/ruGameboy Note: (Traditional Chinese) https://yodalee.me/tags/gameboy/
  • 5. Gameboy 4MHz 8-bit Sharp LR35902 32KB Cartridge 8KB SRAM 8KB Video RAM 160x144 LCD screen
  • 6. CPU Register D15..D8 D7..D0 A F B C D E H L D15..D0 SP (stack pointer) PC (program counter) Flag Register Z N H C 0 0 0 0 Z - Zero Flag N - Subtract Flag H - Half Carry Flag C - Carry Flag 0 - Not used, always zero
  • 7. CPU Instruction 4MHz CPU based on Intel 8080 and Z80. 245 instructions and another 256 extended (CB) instructions
  • 8. Memory Layout Start Size Description 0x0000 32 KB Cartridge ROM 0x8000 6 KB GPU Tile Content 0x9800 2 KB GPU Background Index 0xC000 8KB RAM 0xFE00 160 Bytes GPU Foreground Index
  • 9. GPU Tile 1 tile = 8x8 = 64 pixels. 256 256 2 bits/pixel 1 tile = 16 bytes Virtual Screen = 1024 Tiles
  • 10. GPU Background ... VRAM 0x8000-0xA000 (8K) 1. 0x8000-0x9000 or 0x8800-0x9800 => 4KB / 16B = 256 Tiles 2. 0x9800-0x9C00 or 0x9C00-A000 => 1KB = Tiles index 0x9800 - 0x9C00 Tile Index Table
  • 11. From 0xFE00 to 0xFE9F = 160 bytes 4 bytes per Sprite => 40 Sprite Sprite Size = 1 Tile = 8x8 GPU Sprite Foreground Byte 0 Offset X Byte 1 Offset Y Byte 2 Tile Index Byte 3 Flags: x flip, y flip, etc. Note the width: 8 pixels
  • 12. Line 0 Line 1 Line 2 Line 143 HBlank VBlank GPU Timing 160 144 Mode Cycle Scanline Sprite 80 Scanline BG 172 HBlank 204 VBlank 4560 (10 lines) Total 70224 4 MHz clock 70224 cycles ~= 0.0176s ~= 60 Hz
  • 14. Emulator Architecture GPU Cartridge RAM …. Bus Register VM CPU Display Buffer
  • 15. Implement Register F register All Register Interface pub struct FlagRegister { pub zero: bool, pub subtract: bool, pub half_carry: bool, pub carry: bool } pub struct Register { pub a: u8, pub b: u8, pub c: u8, pub d: u8, pub e: u8, pub f: FlagRegister, pub h: u8, pub l: u8, } impl Register { fn get_hl() -> u16 { (self.h as u16) << 8 | self.l as u16 } fn set_hl(&mut self, value: u16) { self.h = ((value >> 8) & 0xff) as u8; self.l = (value & 0xff) as u8; } //... }
  • 16. Encode Instruction to Enum Register X,Y Move Register X to Y Byte to Instruction enum Target { A, B, C, ... } enum Instruction { NOP LDRR(Target, Target) ADD(Target) ... } impl Instruction { fn from_byte(u8) -> Instruction { 0x00 => Instruction::NOP, 0x01 => //… 0x02 => //… //… } }
  • 17. Implement CPU CPU Step pub struct Cpu { regs: Register, sp: u16, pub pc: u16, pub bus: Bus, } let byte = self.load(self.pc); self.pc + 1; let inst = Instruction::from_byte(byte); match inst { Instruction::JPHL => self.pc = self.regs.get_hl(), Instruction::LDRR(source, target) => { match (&source, &target) { (&Target::C, &Target::B) => self.regs.b = self.regs.c, //...
  • 18. Implement Bus Device Load/Store pub trait Device { fn load(&self, addr: u16) -> Result<u8, ()>; fn store(&mut self, addr: u16, value: u8) -> Result<(), ()>; } impl Bus { fn load(&self, addr: u16) -> Result<u8, ()> { match addr { CATRIDGE_START ..= CATRIDGE_END => self.cartridge.load(addr), VRAM_START ..= VRAM_END => self.gpu.load(addr), RAM_START ..= RAM_END => self.ram.load(addr), //...
  • 19. Implement Gpu Sprite Gpu Render struct Sprite { tile_idx: u8, x: isize, y: isize, // flag... } struct Gpu { sprite: [Sprite:40] vram: Vec<u8>, oam: Vec<u8>, //... } impl Device for Gpu { //... fn build_background(&mut self, buffer: &mut Vec<u32>) { for row in 0..HEIGHT { for col in 0..WIDTH { let tile_addr = row * 32 + col; let tile_idx = self.vram[tile_addr]; let pixels = self.get_tile(tile_idx); buffer.splice(start..end, pixels.iter()...);
  • 20. VM Screen built with minifb. Loop: 1. run CPU until VBlank 2. Render Screen. Let GPU fill display buffer Vec<u32>
  • 21. Migrate Rust to WebAssembly
  • 22. Rust x WebAssembly https://rustwasm.github.io/book/ Tool needed: 1. rustup install wasm32-unknown-unknown 2. wasm-pack 3. cargo-generate 4. npm
  • 23. Migration Step 1. cargo generate --git https://github.com/rustwasm/wasm-pack-template 2. Expose Interface to Javascript 3. wasm-pack build 4. Import WebAssembly from Javascript Done https://github.com/yodalee/ wasm_gameboy
  • 24. Expose Interface to Javascript Magic Word #[wasm_bindgen]
  • 25. wasm_bindgen // rust #[wasm_bindgen] pub struct Gameboy { cartridge: Vec<u8>, vm: Option<Vm> } // javascript import Gameboy from "wasmgb" Gameboy.new()
  • 26. wasm_bindgen // rust #[wasm_bindgen] impl Gameboy { pub fn get_buffer(&self) -> *const u32 { self.vm.buffer.as_ptr() } } // javascript import memory from "wasmgb_bg" const buffer = gameboy.get_buffer(); const pixels = new Uint32Array(memory.buffer, buffer, width*height);
  • 27. Import WebAssembly from Javascript <body> <input type="file" id="file-uploader"/> <canvas id="gameboy-canvas"></canvas> <pre id="gameboy-log"></pre> <script src="./bootstrap.js"></script> </body>
  • 28. Import WebAssembly from Javascript reader.onload = function() { const cartridge = gameboy.get_cartridge(); var bytes = new Uint8Array(reader.result); const m_cartridge = new Uint8Array(memory.buffer, cartridge, 0x8000); // set cartridge for (let idx = 0; idx < 0x8000; idx++) { m_cartridge[idx] = bytes[idx]; } gameboy.set_cartridge();
  • 29. Import WebAssembly from Javascript const renderLoop = () => { drawPixels(); gameboy.step(); } const drawPixels = () => { const buffer = gameboy.get_buffer(); const pixels = new Uint32Array(memory.buffer, buffer, width * height); for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { if (pixels[row * width + col] == WHITE) { //...
  • 30. Done
  • 32. Future Work Features to implement: ● Right now only Tetris can work (゚д゚;) ● Implement Sound Problem to solve: ● How to emulate program in correct timing? ● How to debug efficiently?
  • 33. Conclusion 1. We learn how to build emulator by building it. 2. A Rust program can be migrated to WebAssembly really quick.