Compare commits

...

24 Commits

Author SHA1 Message Date
Rekai Nyangadzayi Musuka 8b1fd64c16 fix: 8-bit writes to WIN PPU registers
Advance Wars depends on these registers similar to Mario Kart's 8-bit
writes to Affine Background registers:
2022-09-17 20:40:54 -03:00
Rekai Nyangadzayi Musuka af84aca633 chore: refactor window 2022-09-17 20:40:54 -03:00
Rekai Nyangadzayi Musuka 6700706472 chore: crude background window impl (no affine) 2022-09-17 20:40:54 -03:00
Rekai Nyangadzayi Musuka a17cbd9b68 chore: rename function (misspelt until now somehow) 2022-09-17 20:40:54 -03:00
Rekai Nyangadzayi Musuka d3efa432fa Merge pull request 'Implement RTC' (#1) from rtc into main
Reviewed-on: #1
2022-09-17 23:36:34 +00:00
Rekai Nyangadzayi Musuka 50adb5fbac feat: add option to force-enable RTC 2022-09-17 20:27:17 -03:00
Rekai Nyangadzayi Musuka 19d78b9292 feat: auto-detect RTC in commercial ROMS 2022-09-17 20:23:49 -03:00
Rekai Nyangadzayi Musuka a2e702c366 fix: account for lateness in RTC scheduler event 2022-09-17 09:07:31 -03:00
Rekai Nyangadzayi Musuka 12c138364d fix: RTC day is 6 bits wide, not 3 2022-09-16 10:59:41 -03:00
Rekai Nyangadzayi Musuka 7783c11fac feat: put RTC Sync on Scheduler
TODO: Database to see what games have what GPIO devices
2022-09-16 10:39:02 -03:00
Rekai Nyangadzayi Musuka 3fc3366c8a chore: import datetime library + default time for RTC 2022-09-16 10:39:02 -03:00
Rekai Nyangadzayi Musuka d6b182f245 fix: ignore RTC Time/DateTime writes
this falls in-line with better emulators
2022-09-16 10:39:02 -03:00
Rekai Nyangadzayi Musuka 3857c44e68 chore: use Clock.Writer for Command parsing, delete Clock.Command 2022-09-16 10:39:02 -03:00
Rekai Nyangadzayi Musuka 089c5fa025 feat: implement RTC Read/Writes 2022-09-16 10:39:02 -03:00
Rekai Nyangadzayi Musuka c977f3f965 feat: implement force irqs for GPIO/RTC 2022-09-16 10:38:51 -03:00
Rekai Nyangadzayi Musuka 92417025e9 fix: properly resovle stack UAF 2022-09-16 02:10:41 -03:00
Rekai Nyangadzayi Musuka 1c52c0bf91 chore: shorten `orelse @panic` to `.?` 2022-09-16 02:10:41 -03:00
Rekai Nyangadzayi Musuka 617f7f4690 fix: update GpioData extern union
u4's are no longer supported in extern unions :\
2022-09-16 02:10:41 -03:00
Rekai Nyangadzayi Musuka 434a0dfac9 tmp: incomplete impl of GPIO + RTC 2022-09-16 02:10:41 -03:00
Rekai Nyangadzayi Musuka 4ec8dab460 chore: Guilty Gear X expects these I/O Registers 2022-09-14 11:38:26 -03:00
Rekai Nyangadzayi Musuka 59c9ff910e feat: implement open bus for unmapped i/o 2022-09-12 23:18:29 -03:00
Rekai Nyangadzayi Musuka 0027d3f8a3 chore: comment open bus impl 2022-09-11 07:38:55 -03:00
Rekai Nyangadzayi Musuka 9f45888910 chore: update dependencies 2022-09-11 06:59:10 -03:00
Rekai Nyangadzayi Musuka bf442d5a40 chore: Update README.md 2022-09-10 07:34:52 -03:00
16 changed files with 814 additions and 163 deletions

3
.gitmodules vendored
View File

@ -7,3 +7,6 @@
[submodule "lib/known-folders"] [submodule "lib/known-folders"]
path = lib/known-folders path = lib/known-folders
url = https://github.com/ziglibs/known-folders url = https://github.com/ziglibs/known-folders
[submodule "lib/zig-datetime"]
path = lib/zig-datetime
url = https://github.com/frmdstryr/zig-datetime

View File

@ -1,5 +1,5 @@
# ZBA (working title) # ZBA (working title)
An in-progress Gameboy Advance Emulator written in Zig ⚡! An in-progress Game Boy Advance Emulator written in Zig ⚡!
## Tests ## Tests
- [ ] [jsmolka's GBA Test Collection](https://github.com/jsmolka/gba-tests) - [ ] [jsmolka's GBA Test Collection](https://github.com/jsmolka/gba-tests)
@ -10,8 +10,7 @@ An in-progress Gameboy Advance Emulator written in Zig ⚡!
- [x] `bios.gba` - [x] `bios.gba`
- [ ] `nes.gba` - [ ] `nes.gba`
- [ ] [DenSinH's GBA ROMs](https://github.com/DenSinH/GBARoms) - [ ] [DenSinH's GBA ROMs](https://github.com/DenSinH/GBARoms)
- [x] `eeprom-test` - [x] `eeprom-test` and `flash-test`
- [x] `flash-test`
- [x] `midikey2freq` - [x] `midikey2freq`
- [ ] `swi-tests-random` - [ ] `swi-tests-random`
- [ ] [destoer's GBA Tests](https://github.com/destoer/gba_tests) - [ ] [destoer's GBA Tests](https://github.com/destoer/gba_tests)
@ -36,14 +35,14 @@ An in-progress Gameboy Advance Emulator written in Zig ⚡!
* [ARM7TDMI Data Sheet](https://www.dca.fee.unicamp.br/cursos/EA871/references/ARM/ARM7TDMIDataSheet.pdf) * [ARM7TDMI Data Sheet](https://www.dca.fee.unicamp.br/cursos/EA871/references/ARM/ARM7TDMIDataSheet.pdf)
## Compiling ## Compiling
Most recently built on Zig [0.10.0-dev.2978+803376708](https://github.com/ziglang/zig/tree/803376708) Most recently built on Zig [0.10.0-dev.3900+ab4b26d8a](https://github.com/ziglang/zig/tree/ab4b26d8a)
### Dependencies ### Dependencies
* [SDL.zig](https://github.com/MasterQ32/SDL.zig) * [SDL.zig](https://github.com/MasterQ32/SDL.zig)
* [SDL2](https://www.libsdl.org/download-2.0.php) * [SDL2](https://www.libsdl.org/download-2.0.php)
* [zig-clap](https://github.com/Hejsil/zig-clap) * [zig-clap](https://github.com/Hejsil/zig-clap)
* [known-folders](https://github.com/ziglibs/known-folders) * [known-folders](https://github.com/ziglibs/known-folders)
* [`bitfields.zig`](https://github.com/FlorenceOS/Florence/blob/f6044db788d35d43d66c1d7e58ef1e3c79f10d6f/lib/util/bitfields.zig) * [`bitfields.zig`](https://github.com/FlorenceOS/Florence/blob/aaa5a9e568197ad24780ec9adb421217530d4466/lib/util/bitfields.zig)
`bitfields.zig` from [FlorenceOS](https://github.com/FlorenceOS) is included under `lib/util/bitfield.zig`. `bitfields.zig` from [FlorenceOS](https://github.com/FlorenceOS) is included under `lib/util/bitfield.zig`.

View File

@ -13,10 +13,12 @@ pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions(); const mode = b.standardReleaseOptions();
const exe = b.addExecutable("zba", "src/main.zig"); const exe = b.addExecutable("zba", "src/main.zig");
// Known Folders (%APPDATA%, XDG, etc.) // Known Folders (%APPDATA%, XDG, etc.)
exe.addPackagePath("known_folders", "lib/known-folders/known-folders.zig"); exe.addPackagePath("known_folders", "lib/known-folders/known-folders.zig");
// DateTime Library
exe.addPackagePath("datetime", "lib/zig-datetime/src/main.zig");
// Bitfield type from FlorenceOS: https://github.com/FlorenceOS/ // Bitfield type from FlorenceOS: https://github.com/FlorenceOS/
// exe.addPackage(.{ .name = "bitfield", .path = .{ .path = "lib/util/bitfield.zig" } }); // exe.addPackage(.{ .name = "bitfield", .path = .{ .path = "lib/util/bitfield.zig" } });
exe.addPackagePath("bitfield", "lib/util/bitfield.zig"); exe.addPackagePath("bitfield", "lib/util/bitfield.zig");

@ -1 +1 @@
Subproject commit d66925011971fbe221fc2a7f7cb4cd8c181d9ba3 Subproject commit 76ec54bf1d13170f1a9998063eecf8087856541a

1
lib/zig-datetime Submodule

@ -0,0 +1 @@
Subproject commit 5ec1c36cf3791b3c6c5b330357bdb6feb93979ba

View File

@ -51,7 +51,7 @@ sched: *Scheduler,
pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void { pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void {
self.* = .{ self.* = .{
.pak = try GamePak.init(allocator, paths.rom, paths.save), .pak = try GamePak.init(allocator, cpu, paths.rom, paths.save),
.bios = try Bios.init(allocator, paths.bios), .bios = try Bios.init(allocator, paths.bios),
.ppu = try Ppu.init(allocator, sched), .ppu = try Ppu.init(allocator, sched),
.apu = Apu.init(sched), .apu = Apu.init(sched),
@ -88,7 +88,7 @@ pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T {
}, },
0x02 => self.ewram.read(T, aligned_addr), 0x02 => self.ewram.read(T, aligned_addr),
0x03 => self.iwram.read(T, aligned_addr), 0x03 => self.iwram.read(T, aligned_addr),
0x04 => io.read(self, T, aligned_addr), 0x04 => self.readIo(T, address),
// Internal Display Memory // Internal Display Memory
0x05 => self.ppu.palette.read(T, aligned_addr), 0x05 => self.ppu.palette.read(T, aligned_addr),
@ -113,31 +113,46 @@ pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T {
}; };
} }
fn readIo(self: *const Self, comptime T: type, unaligned_address: u32) T {
const maybe_value = io.read(self, T, forceAlign(T, unaligned_address));
return if (maybe_value) |value| value else self.readOpenBus(T, unaligned_address);
}
fn readOpenBus(self: *const Self, comptime T: type, address: u32) T { fn readOpenBus(self: *const Self, comptime T: type, address: u32) T {
const r15 = self.cpu.?.r[15]; const r15 = self.cpu.?.r[15];
const word = if (self.cpu.?.cpsr.t.read()) blk: { const word = blk: {
// If u32 Open Bus, read recently fetched opcode (PC + 8)
if (!self.cpu.?.cpsr.t.read()) break :blk self.dbgRead(u32, r15 + 4);
const page = @truncate(u8, r15 >> 24); const page = @truncate(u8, r15 >> 24);
switch (page) { switch (page) {
// EWRAM, PALRAM, VRAM, and Game ROM (16-bit) // EWRAM, PALRAM, VRAM, and Game ROM (16-bit)
0x02, 0x05, 0x06, 0x08...0x0D => { 0x02, 0x05, 0x06, 0x08...0x0D => {
// (PC + 4)
const halfword = self.dbgRead(u16, r15 + 2); const halfword = self.dbgRead(u16, r15 + 2);
break :blk @as(u32, halfword) << 16 | halfword; break :blk @as(u32, halfword) << 16 | halfword;
}, },
// BIOS or OAM (32-bit) // BIOS or OAM (32-bit)
0x00, 0x07 => { 0x00, 0x07 => {
// Aligned: (PC + 6) | (PC + 4)
// Unaligned: (PC + 4) | (PC + 2)
const offset: u32 = if (address & 3 == 0b00) 2 else 0; const offset: u32 = if (address & 3 == 0b00) 2 else 0;
break :blk @as(u32, self.dbgRead(u16, (r15 + 2) + offset)) << 16 | self.dbgRead(u16, r15 + offset);
break :blk @as(u32, self.dbgRead(u16, r15 + 2 + offset)) << 16 | self.dbgRead(u16, r15 + offset);
}, },
// IWRAM (16-bit but special) // IWRAM (16-bit but special)
0x03 => { 0x03 => {
// Aligned: (PC + 2) | (PC + 4)
// Unaligned: (PC + 4) | (PC + 2)
const offset: u32 = if (address & 3 == 0b00) 2 else 0; const offset: u32 = if (address & 3 == 0b00) 2 else 0;
break :blk @as(u32, self.dbgRead(u16, (r15 + 2) - offset)) << 16 | self.dbgRead(u16, r15 + offset);
break :blk @as(u32, self.dbgRead(u16, r15 + 2 - offset)) << 16 | self.dbgRead(u16, r15 + offset);
}, },
else => unreachable, else => unreachable,
} }
} else self.dbgRead(u32, r15 + 4); };
return @truncate(T, rotr(u32, word, 8 * (address & 3))); return @truncate(T, rotr(u32, word, 8 * (address & 3)));
} }
@ -158,7 +173,7 @@ pub fn read(self: *Self, comptime T: type, address: u32) T {
}, },
0x02 => self.ewram.read(T, aligned_addr), 0x02 => self.ewram.read(T, aligned_addr),
0x03 => self.iwram.read(T, aligned_addr), 0x03 => self.iwram.read(T, aligned_addr),
0x04 => io.read(self, T, aligned_addr), 0x04 => self.readIo(T, address),
// Internal Display Memory // Internal Display Memory
0x05 => self.ppu.palette.read(T, aligned_addr), 0x05 => self.ppu.palette.read(T, aligned_addr),

View File

@ -1,6 +1,7 @@
const std = @import("std"); const std = @import("std");
const SDL = @import("sdl2"); const SDL = @import("sdl2");
const io = @import("bus/io.zig"); const io = @import("bus/io.zig");
const util = @import("util.zig");
const Arm7tdmi = @import("cpu.zig").Arm7tdmi; const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const Scheduler = @import("scheduler.zig").Scheduler; const Scheduler = @import("scheduler.zig").Scheduler;
@ -9,13 +10,11 @@ const SoundFifo = std.fifo.LinearFifo(u8, .{ .Static = 0x20 });
const AudioDeviceId = SDL.SDL_AudioDeviceID; const AudioDeviceId = SDL.SDL_AudioDeviceID;
const intToBytes = @import("util.zig").intToBytes; const intToBytes = @import("util.zig").intToBytes;
const readUndefined = @import("util.zig").readUndefined;
const writeUndefined = @import("util.zig").writeUndefined;
const log = std.log.scoped(.APU); const log = std.log.scoped(.APU);
pub const host_sample_rate = 1 << 15; pub const host_sample_rate = 1 << 15;
pub fn read(comptime T: type, apu: *const Apu, addr: u32) T { pub fn read(comptime T: type, apu: *const Apu, addr: u32) ?T {
const byte = @truncate(u8, addr); const byte = @truncate(u8, addr);
return switch (T) { return switch (T) {
@ -38,7 +37,7 @@ pub fn read(comptime T: type, apu: *const Apu, addr: u32) T {
0x84 => apu.getSoundCntX(), 0x84 => apu.getSoundCntX(),
0x88 => apu.bias.raw, // SOUNDBIAS 0x88 => apu.bias.raw, // SOUNDBIAS
0x90...0x9F => apu.ch3.wave_dev.read(T, apu.ch3.select, addr), 0x90...0x9F => apu.ch3.wave_dev.read(T, apu.ch3.select, addr),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u8 => switch (byte) { u8 => switch (byte) {
0x60 => apu.ch1.getSoundCntL(), // NR10 0x60 => apu.ch1.getSoundCntL(), // NR10
@ -52,9 +51,9 @@ pub fn read(comptime T: type, apu: *const Apu, addr: u32) T {
0x81 => @truncate(u8, apu.psg_cnt.raw >> 8), // NR51 0x81 => @truncate(u8, apu.psg_cnt.raw >> 8), // NR51
0x84 => apu.getSoundCntX(), 0x84 => apu.getSoundCntX(),
0x89 => @truncate(u8, apu.bias.raw >> 8), // SOUNDBIAS_H 0x89 => @truncate(u8, apu.bias.raw >> 8), // SOUNDBIAS_H
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u32 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), u32 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("APU: Unsupported read width"), else => @compileError("APU: Unsupported read width"),
}; };
} }
@ -78,7 +77,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value), 0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
0xA0 => apu.chA.push(value), // FIFO_A 0xA0 => apu.chA.push(value), // FIFO_A
0xA4 => apu.chB.push(value), // FIFO_B 0xA4 => apu.chB.push(value), // FIFO_B
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u16 => switch (byte) { u16 => switch (byte) {
0x60 => apu.ch1.setSoundCntL(@truncate(u8, value)), // SOUND1CNT_L 0x60 => apu.ch1.setSoundCntL(@truncate(u8, value)), // SOUND1CNT_L
@ -101,7 +100,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x88 => apu.bias.raw = value, // SOUNDBIAS 0x88 => apu.bias.raw = value, // SOUNDBIAS
// WAVE_RAM // WAVE_RAM
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value), 0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u8 => switch (byte) { u8 => switch (byte) {
0x60 => apu.ch1.setSoundCntL(value), 0x60 => apu.ch1.setSoundCntL(value),
@ -133,7 +132,7 @@ pub fn write(comptime T: type, apu: *Apu, addr: u32, value: T) void {
0x84 => apu.setSoundCntX(value >> 7 & 1 == 1), // NR52 0x84 => apu.setSoundCntX(value >> 7 & 1 == 1), // NR52
0x89 => apu.setSoundBiasH(value), 0x89 => apu.setSoundBiasH(value),
0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value), 0x90...0x9F => apu.ch3.wave_dev.write(T, apu.ch3.select, addr, value),
else => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
else => @compileError("APU: Unsupported write width"), else => @compileError("APU: Unsupported write width"),
} }

View File

@ -1,7 +1,13 @@
const std = @import("std"); const std = @import("std");
const DateTime = @import("datetime").datetime.Datetime;
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const Bit = @import("bitfield").Bit;
const Bitfield = @import("bitfield").Bitfield;
const Backup = @import("backup.zig").Backup; const Backup = @import("backup.zig").Backup;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const force_rtc = @import("../emu.zig").force_rtc;
const log = std.log.scoped(.GamePak); const log = std.log.scoped(.GamePak);
const Self = @This(); const Self = @This();
@ -10,31 +16,48 @@ title: [12]u8,
buf: []u8, buf: []u8,
allocator: Allocator, allocator: Allocator,
backup: Backup, backup: Backup,
gpio: *Gpio,
pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { pub fn init(allocator: Allocator, cpu: *Arm7tdmi, rom_path: []const u8, save_path: ?[]const u8) !Self {
const file = try std.fs.cwd().openFile(rom_path, .{}); const file = try std.fs.cwd().openFile(rom_path, .{});
defer file.close(); defer file.close();
const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos()); const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos());
const title = parseTitle(file_buf); const title = file_buf[0xA0..0xAC].*;
const kind = Backup.guessKind(file_buf) orelse .None; const kind = Backup.guessKind(file_buf);
const device = if (force_rtc) .Rtc else guessDevice(file_buf);
const pak = Self{ logHeader(file_buf, &title);
return .{
.buf = file_buf, .buf = file_buf,
.allocator = allocator, .allocator = allocator,
.title = title, .title = title,
.backup = try Backup.init(allocator, kind, title, save_path), .backup = try Backup.init(allocator, kind, title, save_path),
.gpio = try Gpio.init(allocator, cpu, device),
}; };
pak.parseHeader();
return pak;
} }
fn parseHeader(self: *const Self) void { /// Searches the ROM to see if it can determine whether the ROM it's searching uses
const title = parseTitle(self.buf); /// any GPIO device, like a RTC for example.
const code = self.buf[0xAC..0xB0]; fn guessDevice(buf: []const u8) Gpio.Device.Kind {
const maker = self.buf[0xB0..0xB2]; // Try to Guess if ROM uses RTC
const version = self.buf[0xBC]; const needle = "RTC_V"; // I was told SIIRTC_V, though Pokemen Firered (USA) is a false negative
var i: usize = 0;
while ((i + needle.len) < buf.len) : (i += 1) {
if (std.mem.eql(u8, needle, buf[i..(i + needle.len)])) return .Rtc;
}
// TODO: Detect other GPIO devices
return .None;
}
fn logHeader(buf: []const u8, title: *const [12]u8) void {
const code = buf[0xAC..0xB0];
const maker = buf[0xB0..0xB2];
const version = buf[0xBC];
log.info("Title: {s}", .{title}); log.info("Title: {s}", .{title});
if (version != 0) log.info("Version: {}", .{version}); if (version != 0) log.info("Version: {}", .{version});
@ -42,10 +65,6 @@ fn parseHeader(self: *const Self) void {
if (lookupMaker(maker)) |c| log.info("Maker: {s}", .{c}) else log.info("Maker Code: {s}", .{maker}); if (lookupMaker(maker)) |c| log.info("Maker: {s}", .{c}) else log.info("Maker Code: {s}", .{maker});
} }
fn parseTitle(buf: []u8) [12]u8 {
return buf[0xA0..0xAC].*;
}
fn lookupMaker(slice: *const [2]u8) ?[]const u8 { fn lookupMaker(slice: *const [2]u8) ?[]const u8 {
const id = @as(u16, slice[1]) << 8 | @as(u16, slice[0]); const id = @as(u16, slice[1]) << 8 | @as(u16, slice[0]);
return switch (id) { return switch (id) {
@ -60,6 +79,8 @@ inline fn isLarge(self: *const Self) bool {
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {
self.backup.deinit(); self.backup.deinit();
self.gpio.deinit(self.allocator);
self.allocator.destroy(self.gpio);
self.allocator.free(self.buf); self.allocator.free(self.buf);
self.* = undefined; self.* = undefined;
} }
@ -83,6 +104,35 @@ pub fn read(self: *Self, comptime T: type, address: u32) T {
} }
} }
if (self.gpio.cnt == 1) {
// GPIO Can be read from
// We assume that this will only be true when a ROM actually does want something from GPIO
switch (T) {
u32 => switch (address) {
// TODO: Do I even need to implement these?
0x0800_00C4 => std.debug.panic("Handle 32-bit GPIO Data/Direction Reads", .{}),
0x0800_00C6 => std.debug.panic("Handle 32-bit GPIO Direction/Control Reads", .{}),
0x0800_00C8 => std.debug.panic("Handle 32-bit GPIO Control Reads", .{}),
else => {},
},
u16 => switch (address) {
// FIXME: What do 16-bit GPIO Reads look like?
0x0800_00C4 => return self.gpio.read(.Data),
0x0800_00C6 => return self.gpio.read(.Direction),
0x0800_00C8 => return self.gpio.read(.Control),
else => {},
},
u8 => switch (address) {
0x0800_00C4 => return self.gpio.read(.Data),
0x0800_00C6 => return self.gpio.read(.Direction),
0x0800_00C8 => return self.gpio.read(.Control),
else => {},
},
else => @compileError("GamePak[GPIO]: Unsupported read width"),
}
}
return switch (T) { return switch (T) {
u32 => (@as(T, self.get(addr + 3)) << 24) | (@as(T, self.get(addr + 2)) << 16) | (@as(T, self.get(addr + 1)) << 8) | (@as(T, self.get(addr))), u32 => (@as(T, self.get(addr + 3)) << 24) | (@as(T, self.get(addr + 2)) << 16) | (@as(T, self.get(addr + 1)) << 8) | (@as(T, self.get(addr))),
u16 => (@as(T, self.get(addr + 1)) << 8) | @as(T, self.get(addr)), u16 => (@as(T, self.get(addr + 1)) << 8) | @as(T, self.get(addr)),
@ -141,17 +191,23 @@ pub fn write(self: *Self, comptime T: type, word_count: u16, address: u32, value
switch (T) { switch (T) {
u32 => switch (address) { u32 => switch (address) {
0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data and Direction", .{ T, value }), 0x0800_00C4 => {
0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction and Control", .{ T, value }), self.gpio.write(.Data, @truncate(u4, value));
else => {}, self.gpio.write(.Direction, @truncate(u4, value >> 16));
},
0x0800_00C6 => {
self.gpio.write(.Direction, @truncate(u4, value));
self.gpio.write(.Control, @truncate(u1, value >> 16));
},
else => log.err("Wrote {} 0x{X:0>8} to 0x{X:0>8}, Unhandled", .{ T, value, address }),
}, },
u16 => switch (address) { u16 => switch (address) {
0x0800_00C4 => log.debug("Wrote {} 0x{X:} to I/O Port Data", .{ T, value }), 0x0800_00C4 => self.gpio.write(.Data, @truncate(u4, value)),
0x0800_00C6 => log.debug("Wrote {} 0x{X:} to I/O Port Direction", .{ T, value }), 0x0800_00C6 => self.gpio.write(.Direction, @truncate(u4, value)),
0x0800_00C8 => log.debug("Wrote {} 0x{X:} to I/O Port Control", .{ T, value }), 0x0800_00C8 => self.gpio.write(.Control, @truncate(u1, value)),
else => {}, else => log.err("Wrote {} 0x{X:0>4} to 0x{X:0>8}, Unhandled", .{ T, value, address }),
}, },
u8 => log.debug("Wrote {} 0x{X:} to 0x{X:0>8}, Ignored.", .{ T, value, address }), u8 => log.debug("Wrote {} 0x{X:0>2} to 0x{X:0>8}, Ignored.", .{ T, value, address }),
else => @compileError("GamePak: Unsupported write width"), else => @compileError("GamePak: Unsupported write width"),
} }
} }
@ -183,3 +239,463 @@ test "OOB Access" {
std.debug.assert(pak.get(4) == 0x02); // 0x0002 std.debug.assert(pak.get(4) == 0x02); // 0x0002
std.debug.assert(pak.get(5) == 0x00); std.debug.assert(pak.get(5) == 0x00);
} }
/// GPIO Register Implementation
const Gpio = struct {
const This = @This();
data: u4,
direction: u4,
cnt: u1,
device: Device,
const Device = struct {
ptr: ?*anyopaque,
kind: Kind, // TODO: Make comptime known?
const Kind = enum { Rtc, None };
fn step(self: *Device, value: u4) u4 {
return switch (self.kind) {
.Rtc => blk: {
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.ptr.?));
break :blk clock.step(Clock.Data{ .raw = value });
},
.None => value,
};
}
fn init(kind: Kind, ptr: ?*anyopaque) Device {
return .{ .kind = kind, .ptr = ptr };
}
};
const Register = enum {
Data,
Direction,
Control,
};
fn init(allocator: Allocator, cpu: *Arm7tdmi, kind: Device.Kind) !*This {
log.info("Device: {}", .{kind});
const self = try allocator.create(This);
self.* = .{
.data = 0b0000,
.direction = 0b1111, // TODO: What is GPIO DIrection set to by default?
.cnt = 0b0,
.device = switch (kind) {
.Rtc => blk: {
const clock = try allocator.create(Clock);
clock.init(cpu, self);
break :blk Device{ .kind = kind, .ptr = clock };
},
.None => Device{ .kind = kind, .ptr = null },
},
};
return self;
}
fn deinit(self: *This, allocator: Allocator) void {
switch (self.device.kind) {
.Rtc => {
allocator.destroy(@ptrCast(*Clock, @alignCast(@alignOf(*Clock), self.device.ptr.?)));
},
.None => {},
}
self.* = undefined;
}
fn write(self: *This, comptime reg: Register, value: if (reg == .Control) u1 else u4) void {
switch (reg) {
.Data => {
const masked_value = value & self.direction;
// The value which is actually stored in the GPIO register
// might be modified by the device implementing the GPIO interface e.g. RTC reads
self.data = self.device.step(masked_value);
},
.Direction => self.direction = value,
.Control => self.cnt = value,
}
}
fn read(self: *const This, comptime reg: Register) if (reg == .Control) u1 else u4 {
if (self.cnt == 0) return 0;
return switch (reg) {
.Data => self.data & ~self.direction,
.Direction => self.direction,
.Control => self.cnt,
};
}
};
/// GBA Real Time Clock
pub const Clock = struct {
const This = @This();
writer: Writer,
reader: Reader,
state: State,
cnt: Control,
year: u8,
month: u5,
day: u6,
weekday: u3,
hour: u6,
minute: u7,
second: u7,
cpu: *Arm7tdmi,
gpio: *const Gpio,
const Register = enum {
Control,
DateTime,
Time,
};
const State = union(enum) {
Idle,
Command,
Write: Register,
Read: Register,
};
const Reader = struct {
i: u4,
count: u8,
/// Reads a bit from RTC registers. Which bit it reads is dependent on
///
/// 1. The RTC State Machine, whitch tells us which register we're accessing
/// 2. A `count`, which keeps track of which byte is currently being read
/// 3. An index, which keeps track of which bit of the byte determined by `count` is being read
fn read(self: *Reader, clock: *const Clock, register: Register) u1 {
const idx = @intCast(u3, self.i);
defer self.i += 1;
// FIXME: What do I do about the unused bits?
return switch (register) {
.Control => @truncate(u1, switch (self.count) {
0 => clock.cnt.raw >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 1 byte)", .{ self.count, register }),
}),
.DateTime => @truncate(u1, switch (self.count) {
// Date
0 => clock.year >> idx,
1 => @as(u8, clock.month) >> idx,
2 => @as(u8, clock.day) >> idx,
3 => @as(u8, clock.weekday) >> idx,
// Time
4 => @as(u8, clock.hour) >> idx,
5 => @as(u8, clock.minute) >> idx,
6 => @as(u8, clock.second) >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 7 bytes)", .{ self.count, register }),
}),
.Time => @truncate(u1, switch (self.count) {
0 => @as(u8, clock.hour) >> idx,
1 => @as(u8, clock.minute) >> idx,
2 => @as(u8, clock.second) >> idx,
else => std.debug.panic("Tried to read from byte #{} of {} (hint: there's only 3 bytes)", .{ self.count, register }),
}),
};
}
/// Is true when a Reader has read a u8's worth of bits
fn finished(self: *const Reader) bool {
return self.i >= 8;
}
/// Resets the index used to shift bits out of RTC registers
/// and `count`, which is used to keep track of which byte we're reading
/// is incremeneted
fn lap(self: *Reader) void {
self.i = 0;
self.count += 1;
}
/// Resets the state of a `Reader` in preparation for a future
/// read command
fn reset(self: *Reader) void {
self.i = 0;
self.count = 0;
}
};
const Writer = struct {
buf: u8,
i: u4,
/// The Number of bytes written since last reset
count: u8,
/// Append a bit to the internal bit buffer (aka an integer)
fn push(self: *Writer, value: u1) void {
const idx = @intCast(u3, self.i);
self.buf = (self.buf & ~(@as(u8, 1) << idx)) | @as(u8, value) << idx;
self.i += 1;
}
/// Takes the contents of the internal buffer and writes it to an RTC register
/// Where it writes to is dependent on:
///
/// 1. The RTC State Machine, whitch tells us which register we're accessing
/// 2. A `count`, which keeps track of which byte is currently being read
fn write(self: *const Writer, clock: *Clock, register: Register) void {
// FIXME: What do do about unused bits?
switch (register) {
.Control => switch (self.count) {
0 => clock.cnt.raw = (clock.cnt.raw & 0x80) | (self.buf & 0x7F), // Bit 7 read-only
else => std.debug.panic("Tried to write to byte #{} of {} (hint: there's only 1 byte)", .{ self.count, register }),
},
.DateTime, .Time => log.debug("RTC: Ignoring {} write", .{register}),
}
}
/// Is true when 8 bits have been shifted into the internal buffer
fn finished(self: *const Writer) bool {
return self.i >= 8;
}
/// Resets the internal buffer
/// resets the index used to shift bits into the internal buffer
/// increments `count` (which keeps track of byte offsets) by one
fn lap(self: *Writer) void {
self.buf = 0;
self.i = 0;
self.count += 1;
}
/// Resets `Writer` to a clean state in preparation for a future write command
fn reset(self: *Writer) void {
self.buf = 0;
self.i = 0;
self.count = 0;
}
};
const Data = extern union {
sck: Bit(u8, 0),
sio: Bit(u8, 1),
cs: Bit(u8, 2),
raw: u8,
};
const Control = extern union {
/// Unknown, value should be preserved though
unk: Bit(u8, 1),
/// Per-minute IRQ
/// If set, fire a Gamepak IRQ every 30s,
irq: Bit(u8, 3),
/// 12/24 Hour Bit
/// If set, 12h mode
/// If cleared, 24h mode
mode: Bit(u8, 6),
/// Read-Only, bit cleared on read
/// If is set, means that there has been a failure / time has been lost
off: Bit(u8, 7),
raw: u8,
};
fn init(ptr: *This, cpu: *Arm7tdmi, gpio: *const Gpio) void {
ptr.* = .{
.writer = .{ .buf = 0, .i = 0, .count = 0 },
.reader = .{ .i = 0, .count = 0 },
.state = .Idle,
.cnt = .{ .raw = 0 },
.year = 0x01,
.month = 0x6,
.day = 0x13,
.weekday = 0x3,
.hour = 0x23,
.minute = 0x59,
.second = 0x59,
.cpu = cpu,
.gpio = gpio, // Can't use Arm7tdmi ptr b/c not initialized yet
};
cpu.sched.push(.RealTimeClock, 1 << 24); // Every Second
}
pub fn updateTime(self: *This, late: u64) void {
self.cpu.sched.push(.RealTimeClock, (1 << 24) -| late); // Reschedule
const now = DateTime.now();
self.year = toBcd(u8, @intCast(u8, now.date.year - 2000));
self.month = toBcd(u5, now.date.month);
self.day = toBcd(u6, now.date.day);
self.weekday = toBcd(u3, (now.date.weekday() + 1) % 7); // API is Monday = 0, Sunday = 6. We want Sunday = 0, Saturday = 6
self.hour = toBcd(u6, now.time.hour);
self.minute = toBcd(u7, now.time.minute);
self.second = toBcd(u7, now.time.second);
}
fn step(self: *This, value: Data) u4 {
const cache: Data = .{ .raw = self.gpio.data };
return switch (self.state) {
.Idle => blk: {
// FIXME: Maybe check incoming value to see if SCK is also high?
if (cache.sck.read()) {
if (!cache.cs.read() and value.cs.read()) {
log.debug("RTC: Entering Command Mode", .{});
self.state = .Command;
}
}
break :blk @truncate(u4, value.raw);
},
.Command => blk: {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
// If SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) {
self.writer.push(@boolToInt(value.sio.read()));
if (self.writer.finished()) {
self.state = self.processCommand(self.writer.buf);
self.writer.reset();
log.debug("RTC: Switching to {}", .{self.state});
}
}
break :blk @truncate(u4, value.raw);
},
.Write => |register| blk: {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
// If SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) {
self.writer.push(@boolToInt(value.sio.read()));
const register_width: u32 = switch (register) {
.Control => 1,
.DateTime => 7,
.Time => 3,
};
if (self.writer.finished()) {
self.writer.write(self, register); // write inner buffer to RTC register
self.writer.lap();
if (self.writer.count == register_width) {
self.writer.reset();
self.state = .Idle;
}
}
}
break :blk @truncate(u4, value.raw);
},
.Read => |register| blk: {
if (!value.cs.read()) log.err("RTC: Expected CS to be set during {}, however CS was cleared", .{self.state});
var ret = value;
// if SCK rises, sample SIO
if (!cache.sck.read() and value.sck.read()) {
ret.sio.write(self.reader.read(self, register) == 0b1);
const register_width: u32 = switch (register) {
.Control => 1,
.DateTime => 7,
.Time => 3,
};
if (self.reader.finished()) {
self.reader.lap();
if (self.reader.count == register_width) {
self.reader.reset();
self.state = .Idle;
}
}
}
break :blk @truncate(u4, ret.raw);
},
};
}
fn reset(self: *This) void {
// mGBA and NBA only zero the control register. We will do the same
log.debug("RTC: Reset (control register was zeroed)", .{});
self.cnt.raw = 0;
}
fn irq(self: *This) void {
// TODO: Confirm that this is the right behaviour
log.debug("RTC: Force GamePak IRQ", .{});
self.cpu.bus.io.irq.game_pak.set();
self.cpu.handleInterrupt();
}
fn processCommand(self: *This, raw_command: u8) State {
const command = blk: {
// If High Nybble is 0x6, no need to switch the endianness
if (raw_command >> 4 & 0xF == 0x6) break :blk raw_command;
// Turns out reversing the order of bits isn't trivial at all
// https://stackoverflow.com/questions/2602823/in-c-c-whats-the-simplest-way-to-reverse-the-order-of-bits-in-a-byte
var ret = raw_command;
ret = (ret & 0xF0) >> 4 | (ret & 0x0F) << 4;
ret = (ret & 0xCC) >> 2 | (ret & 0x33) << 2;
ret = (ret & 0xAA) >> 1 | (ret & 0x55) << 1;
break :blk ret;
};
log.debug("RTC: Handling Command 0x{X:0>2} [0b{b:0>8}]", .{ command, command });
const is_write = command & 1 == 0;
const rtc_register = @truncate(u3, command >> 1 & 0x7);
if (is_write) {
return switch (rtc_register) {
0 => blk: {
self.reset();
break :blk .Idle;
},
1 => .{ .Write = .Control },
2 => .{ .Write = .DateTime },
3 => .{ .Write = .Time },
6 => blk: {
self.irq();
break :blk .Idle;
},
4, 5, 7 => .Idle,
};
} else {
return switch (rtc_register) {
1 => .{ .Read = .Control },
2 => .{ .Read = .DateTime },
3 => .{ .Read = .Time },
0, 4, 5, 6, 7 => .Idle, // Do Nothing
};
}
}
};
fn toBcd(comptime T: type, value: u8) T {
var input = value;
var ret: u8 = 0;
var shift: u3 = 0;
while (input > 0) {
ret |= (input % 10) << (shift << 2);
shift += 1;
input /= 10;
}
return @truncate(T, ret);
}

View File

@ -61,7 +61,7 @@ pub const Backup = struct {
return backup; return backup;
} }
pub fn guessKind(rom: []const u8) ?Kind { pub fn guessKind(rom: []const u8) Kind {
for (backup_kinds) |needle| { for (backup_kinds) |needle| {
const needle_len = needle.str.len; const needle_len = needle.str.len;
@ -71,7 +71,7 @@ pub const Backup = struct {
} }
} }
return null; return .None;
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: *Self) void {

View File

@ -1,11 +1,10 @@
const std = @import("std"); const std = @import("std");
const util = @import("../util.zig");
const DmaControl = @import("io.zig").DmaControl; const DmaControl = @import("io.zig").DmaControl;
const Bus = @import("../Bus.zig"); const Bus = @import("../Bus.zig");
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi; const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
pub const DmaTuple = std.meta.Tuple(&[_]type{ DmaController(0), DmaController(1), DmaController(2), DmaController(3) }); pub const DmaTuple = std.meta.Tuple(&[_]type{ DmaController(0), DmaController(1), DmaController(2), DmaController(3) });
const log = std.log.scoped(.DmaTransfer); const log = std.log.scoped(.DmaTransfer);
@ -13,7 +12,7 @@ pub fn create() DmaTuple {
return .{ DmaController(0).init(), DmaController(1).init(), DmaController(2).init(), DmaController(3).init() }; return .{ DmaController(0).init(), DmaController(1).init(), DmaController(2).init(), DmaController(3).init() };
} }
pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) T { pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) ?T {
const byte = @truncate(u8, addr); const byte = @truncate(u8, addr);
return switch (T) { return switch (T) {
@ -22,16 +21,16 @@ pub fn read(comptime T: type, dma: *const DmaTuple, addr: u32) T {
0xC4 => @as(T, dma.*[1].cnt.raw) << 16, 0xC4 => @as(T, dma.*[1].cnt.raw) << 16,
0xD0 => @as(T, dma.*[2].cnt.raw) << 16, 0xD0 => @as(T, dma.*[2].cnt.raw) << 16,
0xDC => @as(T, dma.*[3].cnt.raw) << 16, 0xDC => @as(T, dma.*[3].cnt.raw) << 16,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u16 => switch (byte) { u16 => switch (byte) {
0xBA => dma.*[0].cnt.raw, 0xBA => dma.*[0].cnt.raw,
0xC6 => dma.*[1].cnt.raw, 0xC6 => dma.*[1].cnt.raw,
0xD2 => dma.*[2].cnt.raw, 0xD2 => dma.*[2].cnt.raw,
0xDE => dma.*[3].cnt.raw, 0xDE => dma.*[3].cnt.raw,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u8 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), u8 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("DMA: Unsupported read width"), else => @compileError("DMA: Unsupported read width"),
}; };
} }
@ -53,7 +52,7 @@ pub fn write(comptime T: type, dma: *DmaTuple, addr: u32, value: T) void {
0xD4 => dma.*[3].setSad(value), 0xD4 => dma.*[3].setSad(value),
0xD8 => dma.*[3].setDad(value), 0xD8 => dma.*[3].setDad(value),
0xDC => dma.*[3].setCnt(value), 0xDC => dma.*[3].setCnt(value),
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u16 => switch (byte) { u16 => switch (byte) {
0xB0 => dma.*[0].setSad(setU32L(dma.*[0].sad, value)), 0xB0 => dma.*[0].setSad(setU32L(dma.*[0].sad, value)),
@ -83,9 +82,9 @@ pub fn write(comptime T: type, dma: *DmaTuple, addr: u32, value: T) void {
0xDA => dma.*[3].setDad(setU32H(dma.*[3].dad, value)), 0xDA => dma.*[3].setDad(setU32H(dma.*[3].dad, value)),
0xDC => dma.*[3].setCntL(value), 0xDC => dma.*[3].setCntL(value),
0xDE => dma.*[3].setCntH(value), 0xDE => dma.*[3].setCntH(value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u8 => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }), u8 => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
else => @compileError("DMA: Unsupported write width"), else => @compileError("DMA: Unsupported write width"),
} }
} }

View File

@ -1,5 +1,9 @@
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const timer = @import("timer.zig");
const dma = @import("dma.zig");
const apu = @import("../apu.zig");
const util = @import("../util.zig");
const Bit = @import("bitfield").Bit; const Bit = @import("bitfield").Bit;
const Bitfield = @import("bitfield").Bitfield; const Bitfield = @import("bitfield").Bitfield;
@ -7,12 +11,6 @@ const Bus = @import("../Bus.zig");
const DmaController = @import("dma.zig").DmaController; const DmaController = @import("dma.zig").DmaController;
const Scheduler = @import("../scheduler.zig").Scheduler; const Scheduler = @import("../scheduler.zig").Scheduler;
const timer = @import("timer.zig");
const dma = @import("dma.zig");
const apu = @import("../apu.zig");
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
const log = std.log.scoped(.@"I/O"); const log = std.log.scoped(.@"I/O");
pub const Io = struct { pub const Io = struct {
@ -43,7 +41,7 @@ pub const Io = struct {
} }
}; };
pub fn read(bus: *const Bus, comptime T: type, address: u32) T { pub fn read(bus: *const Bus, comptime T: type, address: u32) ?T {
return switch (T) { return switch (T) {
u32 => switch (address) { u32 => switch (address) {
// Display // Display
@ -58,18 +56,18 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0100...0x0400_010C => timer.read(T, &bus.tim, address), 0x0400_0100...0x0400_010C => timer.read(T, &bus.tim, address),
// Serial Communication 1 // Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT and SIOMLT_SEND", .{T}), 0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT and SIOMLT_SEND", .{T}),
// Keypad Input // Keypad Input
0x0400_0130 => readTodo("Read {} from KEYINPUT", .{T}), 0x0400_0130 => util.io.read.todo(log, "Read {} from KEYINPUT", .{T}),
// Serial Communication 2 // Serial Communication 2
0x0400_0150 => readTodo("Read {} from JOY_RECV", .{T}), 0x0400_0150 => util.io.read.todo(log, "Read {} from JOY_RECV", .{T}),
// Interrupts // Interrupts
0x0400_0200 => @as(T, bus.io.irq.raw) << 16 | bus.io.ie.raw, 0x0400_0200 => @as(T, bus.io.irq.raw) << 16 | bus.io.ie.raw,
0x0400_0208 => @boolToInt(bus.io.ime), 0x0400_0208 => @boolToInt(bus.io.ime),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
}, },
u16 => switch (address) { u16 => switch (address) {
// Display // Display
@ -80,8 +78,10 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_000A => bus.ppu.bg[1].cnt.raw, 0x0400_000A => bus.ppu.bg[1].cnt.raw,
0x0400_000C => bus.ppu.bg[2].cnt.raw, 0x0400_000C => bus.ppu.bg[2].cnt.raw,
0x0400_000E => bus.ppu.bg[3].cnt.raw, 0x0400_000E => bus.ppu.bg[3].cnt.raw,
0x0400_004C => readTodo("Read {} from MOSAIC", .{T}), 0x0400_004C => util.io.read.todo(log, "Read {} from MOSAIC", .{T}),
0x0400_0050 => bus.ppu.bldcnt.raw, 0x0400_0050 => bus.ppu.bldcnt.raw,
0x0400_0052 => bus.ppu.bldalpha.raw,
0x0400_0054 => bus.ppu.bldy.raw,
// Sound // Sound
0x0400_0060...0x0400_009E => apu.read(T, &bus.apu, address), 0x0400_0060...0x0400_009E => apu.read(T, &bus.apu, address),
@ -93,20 +93,20 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0100...0x0400_010E => timer.read(T, &bus.tim, address), 0x0400_0100...0x0400_010E => timer.read(T, &bus.tim, address),
// Serial Communication 1 // Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT", .{T}), 0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT", .{T}),
// Keypad Input // Keypad Input
0x0400_0130 => bus.io.keyinput.raw, 0x0400_0130 => bus.io.keyinput.raw,
// Serial Communication 2 // Serial Communication 2
0x0400_0134 => readTodo("Read {} from RCNT", .{T}), 0x0400_0134 => util.io.read.todo(log, "Read {} from RCNT", .{T}),
// Interrupts // Interrupts
0x0400_0200 => bus.io.ie.raw, 0x0400_0200 => bus.io.ie.raw,
0x0400_0202 => bus.io.irq.raw, 0x0400_0202 => bus.io.irq.raw,
0x0400_0204 => readTodo("Read {} from WAITCNT", .{T}), 0x0400_0204 => util.io.read.todo(log, "Read {} from WAITCNT", .{T}),
0x0400_0208 => @boolToInt(bus.io.ime), 0x0400_0208 => @boolToInt(bus.io.ime),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
}, },
u8 => return switch (address) { u8 => return switch (address) {
// Display // Display
@ -123,18 +123,18 @@ pub fn read(bus: *const Bus, comptime T: type, address: u32) T {
0x0400_0060...0x0400_00A7 => apu.read(T, &bus.apu, address), 0x0400_0060...0x0400_00A7 => apu.read(T, &bus.apu, address),
// Serial Communication 1 // Serial Communication 1
0x0400_0128 => readTodo("Read {} from SIOCNT_L", .{T}), 0x0400_0128 => util.io.read.todo(log, "Read {} from SIOCNT_L", .{T}),
// Keypad Input // Keypad Input
0x0400_0130 => readTodo("read {} from KEYINPUT_L", .{T}), 0x0400_0130 => util.io.read.todo(log, "read {} from KEYINPUT_L", .{T}),
// Serial Communication 2 // Serial Communication 2
0x0400_0135 => readTodo("Read {} from RCNT_H", .{T}), 0x0400_0135 => util.io.read.todo(log, "Read {} from RCNT_H", .{T}),
// Interrupts // Interrupts
0x0400_0200 => @truncate(T, bus.io.ie.raw), 0x0400_0200 => @truncate(T, bus.io.ie.raw),
0x0400_0300 => @enumToInt(bus.io.postflg), 0x0400_0300 => @enumToInt(bus.io.postflg),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, address }),
}, },
else => @compileError("I/O: Unsupported read width"), else => @compileError("I/O: Unsupported read width"),
}; };
@ -210,7 +210,7 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0204 => log.debug("Wrote 0x{X:0>8} to WAITCNT", .{value}), 0x0400_0204 => log.debug("Wrote 0x{X:0>8} to WAITCNT", .{value}),
0x0400_0208 => bus.io.ime = value & 1 == 1, 0x0400_0208 => bus.io.ime = value & 1 == 1,
0x0400_020C...0x0400_021C => {}, // Unused 0x0400_020C...0x0400_021C => {}, // Unused
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, address }), else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, address }),
}, },
u16 => switch (address) { u16 => switch (address) {
// Display // Display
@ -292,7 +292,7 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0204 => log.debug("Wrote 0x{X:0>4} to WAITCNT", .{value}), 0x0400_0204 => log.debug("Wrote 0x{X:0>4} to WAITCNT", .{value}),
0x0400_0208 => bus.io.ime = value & 1 == 1, 0x0400_0208 => bus.io.ime = value & 1 == 1,
0x0400_0206, 0x0400_020A => {}, // Not Used 0x0400_0206, 0x0400_020A => {}, // Not Used
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, address }), else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, address }),
}, },
u8 => switch (address) { u8 => switch (address) {
// Display // Display
@ -302,6 +302,14 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0009 => bus.ppu.bg[0].cnt.raw = (@as(u16, value) << 8) | (bus.ppu.bg[0].cnt.raw & 0xFF), 0x0400_0009 => bus.ppu.bg[0].cnt.raw = (@as(u16, value) << 8) | (bus.ppu.bg[0].cnt.raw & 0xFF),
0x0400_000A => bus.ppu.bg[1].cnt.raw = (bus.ppu.bg[1].cnt.raw & 0xFF00) | value, 0x0400_000A => bus.ppu.bg[1].cnt.raw = (bus.ppu.bg[1].cnt.raw & 0xFF00) | value,
0x0400_000B => bus.ppu.bg[1].cnt.raw = (@as(u16, value) << 8) | (bus.ppu.bg[1].cnt.raw & 0xFF), 0x0400_000B => bus.ppu.bg[1].cnt.raw = (@as(u16, value) << 8) | (bus.ppu.bg[1].cnt.raw & 0xFF),
0x0400_0040 => bus.ppu.win.h[0].set(.Lo, value),
0x0400_0041 => bus.ppu.win.h[0].set(.Hi, value),
0x0400_0042 => bus.ppu.win.h[1].set(.Lo, value),
0x0400_0043 => bus.ppu.win.h[1].set(.Hi, value),
0x0400_0044 => bus.ppu.win.v[0].set(.Lo, value),
0x0400_0045 => bus.ppu.win.v[0].set(.Hi, value),
0x0400_0046 => bus.ppu.win.v[1].set(.Lo, value),
0x0400_0047 => bus.ppu.win.v[1].set(.Hi, value),
0x0400_0048 => bus.ppu.win.setInL(value), 0x0400_0048 => bus.ppu.win.setInL(value),
0x0400_0049 => bus.ppu.win.setInH(value), 0x0400_0049 => bus.ppu.win.setInH(value),
0x0400_004A => bus.ppu.win.setOutL(value), 0x0400_004A => bus.ppu.win.setOutL(value),
@ -325,17 +333,12 @@ pub fn write(bus: *Bus, comptime T: type, address: u32, value: T) void {
0x0400_0301 => bus.io.haltcnt = if (value >> 7 & 1 == 0) .Halt else std.debug.panic("TODO: Implement STOP", .{}), 0x0400_0301 => bus.io.haltcnt = if (value >> 7 & 1 == 0) .Halt else std.debug.panic("TODO: Implement STOP", .{}),
0x0400_0410 => log.debug("Wrote 0x{X:0>2} to the common yet undocumented 0x{X:0>8}", .{ value, address }), 0x0400_0410 => log.debug("Wrote 0x{X:0>2} to the common yet undocumented 0x{X:0>8}", .{ value, address }),
else => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, address }), else => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, address }),
}, },
else => @compileError("I/O: Unsupported write width"), else => @compileError("I/O: Unsupported write width"),
}; };
} }
fn readTodo(comptime format: []const u8, args: anytype) u8 {
log.debug(format, args);
return 0;
}
/// Read / Write /// Read / Write
pub const PostFlag = enum(u1) { pub const PostFlag = enum(u1) {
FirstBoot = 0, FirstBoot = 0,
@ -464,37 +467,57 @@ pub const BldY = extern union {
raw: u16, raw: u16,
}; };
const u8WriteKind = enum { Hi, Lo };
/// Write-only /// Write-only
pub const WinH = extern union { pub const WinH = extern union {
const Self = @This();
x2: Bitfield(u16, 0, 8), x2: Bitfield(u16, 0, 8),
x1: Bitfield(u16, 8, 8), x1: Bitfield(u16, 8, 8),
raw: u16, raw: u16,
pub fn set(self: *Self, comptime K: u8WriteKind, value: u8) void {
self.raw = switch (K) {
.Hi => (@as(u16, value) << 8) | self.raw & 0xFF,
.Lo => (self.raw & 0xFF00) | value,
};
}
}; };
/// Write-only /// Write-only
pub const WinV = extern union { pub const WinV = extern union {
const Self = @This();
y2: Bitfield(u16, 0, 8), y2: Bitfield(u16, 0, 8),
y1: Bitfield(u16, 8, 8), y1: Bitfield(u16, 8, 8),
raw: u16, raw: u16,
pub fn set(self: *Self, comptime K: u8WriteKind, value: u8) void {
self.raw = switch (K) {
.Hi => (@as(u16, value) << 8) | self.raw & 0xFF,
.Lo => (self.raw & 0xFF00) | value,
};
}
}; };
pub const WinIn = extern union { pub const WinIn = extern union {
w0_bg: Bitfield(u16, 0, 4), w0_bg: Bitfield(u16, 0, 4),
w0_obj: Bit(u16, 4), w0_obj: Bit(u16, 4),
w0_colour: Bit(u16, 5), w0_bld: Bit(u16, 5),
w1_bg: Bitfield(u16, 8, 4), w1_bg: Bitfield(u16, 8, 4),
w1_obj: Bit(u16, 12), w1_obj: Bit(u16, 12),
w1_colour: Bit(u16, 13), w1_bld: Bit(u16, 13),
raw: u16, raw: u16,
}; };
pub const WinOut = extern union { pub const WinOut = extern union {
out_bg: Bitfield(u16, 0, 4), out_bg: Bitfield(u16, 0, 4),
out_obj: Bit(u16, 4), out_obj: Bit(u16, 4),
out_colour: Bit(u16, 5), out_bld: Bit(u16, 5),
obj_bg: Bitfield(u16, 8, 4), obj_bg: Bitfield(u16, 8, 4),
obj_obj: Bit(u16, 12), obj_obj: Bit(u16, 12),
obj_colour: Bit(u16, 13), obj_bld: Bit(u16, 13),
raw: u16, raw: u16,
}; };

View File

@ -1,4 +1,5 @@
const std = @import("std"); const std = @import("std");
const util = @import("../util.zig");
const TimerControl = @import("io.zig").TimerControl; const TimerControl = @import("io.zig").TimerControl;
const Io = @import("io.zig").Io; const Io = @import("io.zig").Io;
@ -6,8 +7,6 @@ const Scheduler = @import("../scheduler.zig").Scheduler;
const Event = @import("../scheduler.zig").Event; const Event = @import("../scheduler.zig").Event;
const Arm7tdmi = @import("../cpu.zig").Arm7tdmi; const Arm7tdmi = @import("../cpu.zig").Arm7tdmi;
const readUndefined = @import("../util.zig").readUndefined;
const writeUndefined = @import("../util.zig").writeUndefined;
pub const TimerTuple = std.meta.Tuple(&[_]type{ Timer(0), Timer(1), Timer(2), Timer(3) }); pub const TimerTuple = std.meta.Tuple(&[_]type{ Timer(0), Timer(1), Timer(2), Timer(3) });
const log = std.log.scoped(.Timer); const log = std.log.scoped(.Timer);
@ -15,7 +14,7 @@ pub fn create(sched: *Scheduler) TimerTuple {
return .{ Timer(0).init(sched), Timer(1).init(sched), Timer(2).init(sched), Timer(3).init(sched) }; return .{ Timer(0).init(sched), Timer(1).init(sched), Timer(2).init(sched), Timer(3).init(sched) };
} }
pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T { pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) ?T {
const nybble = @truncate(u4, addr); const nybble = @truncate(u4, addr);
return switch (T) { return switch (T) {
@ -24,7 +23,7 @@ pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T {
0x4 => @as(T, tim.*[1].cnt.raw) << 16 | tim.*[1].getCntL(), 0x4 => @as(T, tim.*[1].cnt.raw) << 16 | tim.*[1].getCntL(),
0x8 => @as(T, tim.*[2].cnt.raw) << 16 | tim.*[2].getCntL(), 0x8 => @as(T, tim.*[2].cnt.raw) << 16 | tim.*[2].getCntL(),
0xC => @as(T, tim.*[3].cnt.raw) << 16 | tim.*[3].getCntL(), 0xC => @as(T, tim.*[3].cnt.raw) << 16 | tim.*[3].getCntL(),
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u16 => switch (nybble) { u16 => switch (nybble) {
0x0 => tim.*[0].getCntL(), 0x0 => tim.*[0].getCntL(),
@ -35,9 +34,9 @@ pub fn read(comptime T: type, tim: *const TimerTuple, addr: u32) T {
0xA => tim.*[2].cnt.raw, 0xA => tim.*[2].cnt.raw,
0xC => tim.*[3].getCntL(), 0xC => tim.*[3].getCntL(),
0xE => tim.*[3].cnt.raw, 0xE => tim.*[3].cnt.raw,
else => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), else => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
}, },
u8 => readUndefined(log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }), u8 => util.io.read.undef(T, log, "Tried to perform a {} read to 0x{X:0>8}", .{ T, addr }),
else => @compileError("TIM: Unsupported read width"), else => @compileError("TIM: Unsupported read width"),
}; };
} }
@ -51,7 +50,7 @@ pub fn write(comptime T: type, tim: *TimerTuple, addr: u32, value: T) void {
0x4 => tim.*[1].setCnt(value), 0x4 => tim.*[1].setCnt(value),
0x8 => tim.*[2].setCnt(value), 0x8 => tim.*[2].setCnt(value),
0xC => tim.*[3].setCnt(value), 0xC => tim.*[3].setCnt(value),
else => writeUndefined(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>8}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u16 => switch (nybble) { u16 => switch (nybble) {
0x0 => tim.*[0].setCntL(value), 0x0 => tim.*[0].setCntL(value),
@ -62,9 +61,9 @@ pub fn write(comptime T: type, tim: *TimerTuple, addr: u32, value: T) void {
0xA => tim.*[2].setCntH(value), 0xA => tim.*[2].setCntH(value),
0xC => tim.*[3].setCntL(value), 0xC => tim.*[3].setCntL(value),
0xE => tim.*[3].setCntH(value), 0xE => tim.*[3].setCntH(value),
else => writeUndefined(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }), else => util.io.write.undef(log, "Tried to write 0x{X:0>4}{} to 0x{X:0>8}", .{ value, T, addr }),
}, },
u8 => writeUndefined(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }), u8 => util.io.write.undef(log, "Tried to write 0x{X:0>2}{} to 0x{X:0>8}", .{ value, T, addr }),
else => @compileError("TIM: Unsupported write width"), else => @compileError("TIM: Unsupported write width"),
}; };
} }

View File

@ -13,10 +13,12 @@ const Atomic = std.atomic.Atomic;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
// TODO: Move these to a TOML File // TODO: Move these to a TOML File
const sync_audio = true; // Enable Audio Sync const sync_audio = false; // Enable Audio Sync
const sync_video: RunKind = .LimitedFPS; // Configure Video Sync const sync_video: RunKind = .LimitedFPS; // Configure Video Sync
pub const win_scale = 3; // 1x, 2x, 3x, etc. Window Scaling pub const win_scale = 3; // 1x, 2x, 3x, etc. Window Scaling
pub const cpu_logging = false; // Enable detailed CPU logging pub const cpu_logging = false; // Enable detailed CPU logging
pub const allow_unhandled_io = true; // Only relevant in Debug Builds
pub const force_rtc = false;
// 228 Lines which consist of 308 dots (which are 4 cycles long) // 228 Lines which consist of 308 dots (which are 4 cycles long)
const cycles_per_frame: u64 = 228 * (308 * 4); //280896 const cycles_per_frame: u64 = 228 * (308 * 4); //280896

View File

@ -277,16 +277,17 @@ pub const Ppu = struct {
aff_x += self.aff_bg[n - 2].pa; aff_x += self.aff_bg[n - 2].pa;
aff_y += self.aff_bg[n - 2].pc; aff_y += self.aff_bg[n - 2].pc;
if (!shouldDrawBackground(n, self.bldcnt, &self.scanline, i)) continue; const x = @bitCast(u32, ix);
const y = @bitCast(u32, iy);
const win_bounds = self.windowBounds(@truncate(u9, x), @truncate(u8, y));
if (!shouldDrawBackground(self, n, win_bounds, i)) continue;
if (self.bg[n].cnt.display_overflow.read()) { if (self.bg[n].cnt.display_overflow.read()) {
ix = if (ix > px_width) @rem(ix, px_width) else if (ix < 0) px_width + @rem(ix, px_width) else ix; ix = if (ix > px_width) @rem(ix, px_width) else if (ix < 0) px_width + @rem(ix, px_width) else ix;
iy = if (iy > px_height) @rem(iy, px_height) else if (iy < 0) px_height + @rem(iy, px_height) else iy; iy = if (iy > px_height) @rem(iy, px_height) else if (iy < 0) px_height + @rem(iy, px_height) else iy;
} else if (ix > px_width or iy > px_height or ix < 0 or iy < 0) continue; } else if (ix > px_width or iy > px_height or ix < 0 or iy < 0) continue;
const x = @bitCast(u32, ix);
const y = @bitCast(u32, iy);
const tile_id: u32 = self.vram.read(u8, screen_base + ((y / 8) * @bitCast(u32, tile_width) + (x / 8))); const tile_id: u32 = self.vram.read(u8, screen_base + ((y / 8) * @bitCast(u32, tile_width) + (x / 8)));
const row = y & 7; const row = y & 7;
const col = x & 7; const col = x & 7;
@ -296,7 +297,7 @@ pub const Ppu = struct {
if (pal_id != 0) { if (pal_id != 0) {
const bgr555 = self.palette.read(u16, pal_id * 2); const bgr555 = self.palette.read(u16, pal_id * 2);
copyToBackgroundBuffer(n, self.bldcnt, &self.scanline, i, bgr555); self.copyToBackgroundBuffer(n, win_bounds, i, bgr555);
} }
} }
@ -305,7 +306,7 @@ pub const Ppu = struct {
self.aff_bg[n - 2].y_latch.? += self.aff_bg[n - 2].pd; // PD is added to BGxY self.aff_bg[n - 2].y_latch.? += self.aff_bg[n - 2].pd; // PD is added to BGxY
} }
fn drawBackround(self: *Self, comptime n: u2) void { fn drawBackground(self: *Self, comptime n: u2) void {
// A Tile in a charblock is a byte, while a Screen Entry is a halfword // A Tile in a charblock is a byte, while a Screen Entry is a halfword
const char_base = 0x4000 * @as(u32, self.bg[n].cnt.char_base.read()); const char_base = 0x4000 * @as(u32, self.bg[n].cnt.char_base.read());
@ -325,10 +326,11 @@ pub const Ppu = struct {
var i: u32 = 0; var i: u32 = 0;
while (i < width) : (i += 1) { while (i < width) : (i += 1) {
if (!shouldDrawBackground(n, self.bldcnt, &self.scanline, i)) continue;
const x = hofs + i; const x = hofs + i;
const win_bounds = self.windowBounds(@truncate(u9, x), @truncate(u8, y));
if (!shouldDrawBackground(self, n, win_bounds, i)) continue;
// Grab the Screen Entry from VRAM // Grab the Screen Entry from VRAM
const entry_addr = screen_base + tilemapOffset(size, x, y); const entry_addr = screen_base + tilemapOffset(size, x, y);
const entry = @bitCast(ScreenEntry, self.vram.read(u16, entry_addr)); const entry = @bitCast(ScreenEntry, self.vram.read(u16, entry_addr));
@ -353,7 +355,7 @@ pub const Ppu = struct {
if (pal_id != 0) { if (pal_id != 0) {
const bgr555 = self.palette.read(u16, pal_id * 2); const bgr555 = self.palette.read(u16, pal_id * 2);
copyToBackgroundBuffer(n, self.bldcnt, &self.scanline, i, bgr555); self.copyToBackgroundBuffer(n, win_bounds, i, bgr555);
} }
} }
} }
@ -379,10 +381,10 @@ pub const Ppu = struct {
var layer: usize = 0; var layer: usize = 0;
while (layer < 4) : (layer += 1) { while (layer < 4) : (layer += 1) {
self.drawSprites(@truncate(u2, layer)); self.drawSprites(@truncate(u2, layer));
if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackround(0); if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackground(0);
if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackround(1); if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackground(1);
if (layer == self.bg[2].cnt.priority.read() and bg_enable >> 2 & 1 == 1) self.drawBackround(2); if (layer == self.bg[2].cnt.priority.read() and bg_enable >> 2 & 1 == 1) self.drawBackground(2);
if (layer == self.bg[3].cnt.priority.read() and bg_enable >> 3 & 1 == 1) self.drawBackround(3); if (layer == self.bg[3].cnt.priority.read() and bg_enable >> 3 & 1 == 1) self.drawBackground(3);
} }
// Copy Drawn Scanline to Frame Buffer // Copy Drawn Scanline to Frame Buffer
@ -407,8 +409,8 @@ pub const Ppu = struct {
var layer: usize = 0; var layer: usize = 0;
while (layer < 4) : (layer += 1) { while (layer < 4) : (layer += 1) {
self.drawSprites(@truncate(u2, layer)); self.drawSprites(@truncate(u2, layer));
if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackround(0); if (layer == self.bg[0].cnt.priority.read() and bg_enable & 1 == 1) self.drawBackground(0);
if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackround(1); if (layer == self.bg[1].cnt.priority.read() and bg_enable >> 1 & 1 == 1) self.drawBackground(1);
if (layer == self.bg[2].cnt.priority.read() and bg_enable >> 2 & 1 == 1) self.drawAffineBackground(2); if (layer == self.bg[2].cnt.priority.read() and bg_enable >> 2 & 1 == 1) self.drawAffineBackground(2);
} }
@ -533,6 +535,93 @@ pub const Ppu = struct {
return self.palette.getBackdrop(); return self.palette.getBackdrop();
} }
fn copyToBackgroundBuffer(self: *Self, comptime n: u2, bounds: ?WindowBounds, i: usize, bgr555: u16) void {
if (self.bldcnt.mode.read() != 0b00) {
// Standard Alpha Blending
const a_layers = self.bldcnt.layer_a.read();
const is_blend_enabled = (a_layers >> n) & 1 == 1;
// If Alpha Blending is enabled and we've found an eligible layer for
// Pixel A, store the pixel in the bottom pixel buffer
const win_part = if (bounds) |win| blk: {
// Window Enabled
break :blk switch (win) {
.win0 => self.win.in.w0_bld.read(),
.win1 => self.win.in.w1_bld.read(),
.out => self.win.out.out_bld.read(),
};
} else true;
if (win_part and is_blend_enabled) {
self.scanline.btm()[i] = bgr555;
return;
}
}
self.scanline.top()[i] = bgr555;
}
const WindowBounds = enum { win0, win1, out };
fn windowBounds(self: *Self, x: u9, y: u8) ?WindowBounds {
const win0 = self.dispcnt.win_enable.read() & 1 == 1;
const win1 = (self.dispcnt.win_enable.read() >> 1) & 1 == 1;
const winObj = self.dispcnt.obj_win_enable.read();
if (!(win0 or win1 or winObj)) return null;
if (win0 and self.win.inRange(0, x, y)) return .win0;
if (win1 and self.win.inRange(1, x, y)) return .win1;
return .out;
}
fn shouldDrawBackground(self: *Self, comptime n: u2, bounds: ?WindowBounds, i: usize) bool {
// If a pixel has been drawn on the top layer, it's because:
// 1. The pixel is to be blended with a pixel on the bottom layer
// 2. The pixel is not to be blended at all
// Also, if we find a pixel on the top layer we don't need to bother with this I think?
if (self.scanline.top()[i] != null) return false;
if (bounds) |win| {
switch (win) {
.win0 => if ((self.win.in.w0_bg.read() >> n) & 1 == 0) return false,
.win1 => if ((self.win.in.w1_bg.read() >> n) & 1 == 0) return false,
.out => if ((self.win.out.out_bg.read() >> n) & 1 == 0) return false,
}
}
if (self.scanline.btm()[i] != null) {
// The pixel found in the bottom layer is:
// 1. From a higher priority background
// 2. From a background that is marked for blending (Pixel A)
// If Alpha Blending isn't enabled, then we've already found a higher prio
// pixel, we can return early
if (self.bldcnt.mode.read() != 0b01) return false;
const b_layers = self.bldcnt.layer_b.read();
const win_part = if (bounds) |win| blk: {
// Window Enabled
break :blk switch (win) {
.win0 => self.win.in.w0_bld.read(),
.win1 => self.win.in.w1_bld.read(),
.out => self.win.out.out_bld.read(),
};
} else true;
// If the Background is not marked for blending, we've already found
// a higher priority pixel, move on.
const is_blend_enabled = win_part and ((b_layers >> n) & 1 == 1);
if (!is_blend_enabled) return false;
}
return true;
}
// TODO: Comment this + get a better understanding // TODO: Comment this + get a better understanding
fn tilemapOffset(size: u2, x: u32, y: u32) u32 { fn tilemapOffset(size: u2, x: u32, y: u32) u32 {
// Current Row: (y % PIXEL_COUNT) / 8 // Current Row: (y % PIXEL_COUNT) / 8
@ -794,6 +883,25 @@ const Window = struct {
}; };
} }
fn inRange(self: *const Self, comptime id: u1, x: u9, y: u8) bool {
const h = self.h[id];
const v = self.v[id];
const y1 = v.y1.read();
const y2 = if (y1 > v.y2.read()) 160 else std.math.min(160, v.y2.read());
if (y1 <= y and y < y2) {
// Within Y bounds
const x1 = h.x1.read();
const x2 = if (x1 > h.x2.read()) 240 else std.math.min(240, h.x2.read());
// Within X Bounds
return x1 <= x and x < x2;
}
return false;
}
pub fn setH(self: *Self, value: u32) void { pub fn setH(self: *Self, value: u32) void {
self.h[0].raw = @truncate(u16, value); self.h[0].raw = @truncate(u16, value);
self.h[1].raw = @truncate(u16, value >> 16); self.h[1].raw = @truncate(u16, value >> 16);
@ -1135,37 +1243,6 @@ fn alphaBlend(top: u16, btm: u16, bldalpha: io.BldAlpha) u16 {
return (bld_b << 10) | (bld_g << 5) | bld_r; return (bld_b << 10) | (bld_g << 5) | bld_r;
} }
fn shouldDrawBackground(comptime n: u2, bldcnt: io.BldCnt, scanline: *Scanline, i: usize) bool {
// If a pixel has been drawn on the top layer, it's because
// Either the pixel is to be blended with a pixel on the bottom layer
// or the pixel is not to be blended at all
// Consequentially, if we find a pixel on the top layer, there's no need
// to render anything I think?
if (scanline.top()[i] != null) return false;
if (scanline.btm()[i] != null) {
// The Pixel found in the Bottom layer is
// 1. From a higher priority
// 2. From a Backround that is marked for Blending (Pixel A)
//
// We now have to confirm whether this current Background can be used
// as Pixel B or not.
// If Alpha Blending isn't enabled, we've aready found a higher
// priority pixel to render. Move on
if (bldcnt.mode.read() != 0b01) return false;
const b_layers = bldcnt.layer_b.read();
const is_blend_enabled = (b_layers >> n) & 1 == 1;
// If the Background is not marked for blending, we've already found
// a higher priority pixel, move on.
if (!is_blend_enabled) return false;
}
return true;
}
fn shouldDrawSprite(bldcnt: io.BldCnt, scanline: *Scanline, x: u9) bool { fn shouldDrawSprite(bldcnt: io.BldCnt, scanline: *Scanline, x: u9) bool {
if (scanline.top()[x] != null) return false; if (scanline.top()[x] != null) return false;
@ -1180,23 +1257,6 @@ fn shouldDrawSprite(bldcnt: io.BldCnt, scanline: *Scanline, x: u9) bool {
return true; return true;
} }
fn copyToBackgroundBuffer(comptime n: u2, bldcnt: io.BldCnt, scanline: *Scanline, i: usize, bgr555: u16) void {
if (bldcnt.mode.read() != 0b00) {
// Standard Alpha Blending
const a_layers = bldcnt.layer_a.read();
const is_blend_enabled = (a_layers >> n) & 1 == 1;
// If Alpha Blending is enabled and we've found an eligible layer for
// Pixel A, store the pixel in the bottom pixel buffer
if (is_blend_enabled) {
scanline.btm()[i] = bgr555;
return;
}
}
scanline.top()[i] = bgr555;
}
fn copyToSpriteBuffer(bldcnt: io.BldCnt, scanline: *Scanline, x: u9, bgr555: u16) void { fn copyToSpriteBuffer(bldcnt: io.BldCnt, scanline: *Scanline, x: u9, bgr555: u16) void {
if (bldcnt.mode.read() != 0b00) { if (bldcnt.mode.read() != 0b00) {
// Alpha Blending // Alpha Blending

View File

@ -2,6 +2,7 @@ const std = @import("std");
const Bus = @import("Bus.zig"); const Bus = @import("Bus.zig");
const Arm7tdmi = @import("cpu.zig").Arm7tdmi; const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const Clock = @import("bus/GamePak.zig").Clock;
const Order = std.math.Order; const Order = std.math.Order;
const PriorityQueue = std.PriorityQueue; const PriorityQueue = std.PriorityQueue;
@ -60,6 +61,13 @@ pub const Scheduler = struct {
3 => cpu.bus.apu.ch4.channelTimerOverflow(late), 3 => cpu.bus.apu.ch4.channelTimerOverflow(late),
} }
}, },
.RealTimeClock => {
const device = &cpu.bus.pak.gpio.device;
if (device.kind != .Rtc or device.ptr == null) return;
const clock = @ptrCast(*Clock, @alignCast(@alignOf(*Clock), device.ptr.?));
clock.updateTime(late);
},
.FrameSequencer => cpu.bus.apu.tickFrameSequencer(late), .FrameSequencer => cpu.bus.apu.tickFrameSequencer(late),
.SampleAudio => cpu.bus.apu.sampleAudio(late), .SampleAudio => cpu.bus.apu.sampleAudio(late),
.HBlank => cpu.bus.ppu.handleHBlankEnd(cpu, late), // The end of a HBlank .HBlank => cpu.bus.ppu.handleHBlankEnd(cpu, late), // The end of a HBlank
@ -118,4 +126,5 @@ pub const EventKind = union(enum) {
SampleAudio, SampleAudio,
FrameSequencer, FrameSequencer,
ApuChannel: u2, ApuChannel: u2,
RealTimeClock,
}; };

View File

@ -3,6 +3,8 @@ const builtin = @import("builtin");
const Log2Int = std.math.Log2Int; const Log2Int = std.math.Log2Int;
const Arm7tdmi = @import("cpu.zig").Arm7tdmi; const Arm7tdmi = @import("cpu.zig").Arm7tdmi;
const allow_unhandled_io = @import("emu.zig").allow_unhandled_io;
// Sign-Extend value of type `T` to type `U` // Sign-Extend value of type `T` to type `U`
pub fn sext(comptime T: type, comptime U: type, value: T) T { pub fn sext(comptime T: type, comptime U: type, value: T) T {
// U must have less bits than T // U must have less bits than T
@ -102,6 +104,28 @@ pub const FilePaths = struct {
save: ?[]const u8, save: ?[]const u8,
}; };
pub const io = struct {
pub const read = struct {
pub fn todo(comptime log: anytype, comptime format: []const u8, args: anytype) u8 {
log.debug(format, args);
return 0;
}
pub fn undef(comptime T: type, log: anytype, comptime format: []const u8, args: anytype) ?T {
log.warn(format, args);
if (builtin.mode == .Debug and !allow_unhandled_io) std.debug.panic("TODO: Implement I/O Register", .{});
return null;
}
};
pub const write = struct {
pub fn undef(log: anytype, comptime format: []const u8, args: anytype) void {
log.warn(format, args);
if (builtin.mode == .Debug and !allow_unhandled_io) std.debug.panic("TODO: Implement I/O Register", .{});
}
};
};
pub fn readUndefined(log: anytype, comptime format: []const u8, args: anytype) u8 { pub fn readUndefined(log: anytype, comptime format: []const u8, args: anytype) u8 {
log.warn(format, args); log.warn(format, args);
if (builtin.mode == .Debug) std.debug.panic("TODO: Implement I/O Register", .{}); if (builtin.mode == .Debug) std.debug.panic("TODO: Implement I/O Register", .{});