Compare commits

...

12 Commits

Author SHA1 Message Date
Rekai Nyangadzayi Musuka a5ac5f7d04 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-05 01:17:03 -03:00
Rekai Nyangadzayi Musuka f74b016849 chore: refactor window 2022-09-05 01:17:03 -03:00
Rekai Nyangadzayi Musuka c89ccad6d0 chore: crude background window impl (no affine) 2022-09-05 01:17:03 -03:00
Rekai Nyangadzayi Musuka 79f2f79d9c chore: rename function (misspelt until now somehow) 2022-09-05 01:17:03 -03:00
Rekai Nyangadzayi Musuka 3fb7f2f814 chore: better conform to zig idioms 2022-09-03 18:30:48 -03:00
Rekai Nyangadzayi Musuka 59669ba3a5 chore: rename arm7tdmi variables to just cpu
Less verbose, specifying arm7tdmi doesn't really do much when there's
no other CPU in the system
2022-09-03 17:56:37 -03:00
Rekai Nyangadzayi Musuka 6a798d2c9d chore: allocate sprite array on heap
Each Sprite optional is 10 bytes meaning I'm allocating 1.28Kb on the
stack which isn't necessary.
2022-08-29 01:07:25 -05:00
Rekai Nyangadzayi Musuka 5f8c6833f4 chore: improve init/deinit methods 2022-08-29 01:07:25 -05:00
Rekai Nyangadzayi Musuka aa52bb5917 chore: reorganize some code 2022-08-26 14:13:49 -05:00
Rekai Nyangadzayi Musuka e57f918856 chore: pass the allocator as an argument more often
As of right now, I think the only cases where I shouldn't explicitly pass an allocator
are in read/write functions and deinits
2022-08-26 13:54:38 -05:00
Rekai Nyangadzayi Musuka e5b7441740 fix: resolve use-afer-free in backup.zig
This worked fine on stage1, and works fine in debug in stage3.
However, stage3 ReleaseSafe would panic due to what I assume must
have been an undefined behaviour optimization.

While I'm happy that I was quickly made aware of the issue thanks to
the safety checks in ReleaseSafe I do wish that this issue showed itself
in Debug, since I *am* using the GPA
2022-08-26 13:04:09 -05:00
Rekai Nyangadzayi Musuka 2ab8769b7a feat: Get ZBA working on Zig's new stage2/stage3 compiler 2022-08-21 12:28:31 -05:00
16 changed files with 395 additions and 299 deletions

@ -1 +1 @@
Subproject commit 401c50ff3d0b83ad4bd89caf580ce1bd90fb5618 Subproject commit d66925011971fbe221fc2a7f7cb4cd8c181d9ba3

View File

@ -14,7 +14,7 @@ fn PtrCastPreserveCV(comptime T: type, comptime PtrToT: type, comptime NewT: typ
fn BitType(comptime FieldType: type, comptime ValueType: type, comptime shamt: usize) type { fn BitType(comptime FieldType: type, comptime ValueType: type, comptime shamt: usize) type {
const self_bit: FieldType = (1 << shamt); const self_bit: FieldType = (1 << shamt);
return struct { return extern struct {
bits: Bitfield(FieldType, shamt, 1), bits: Bitfield(FieldType, shamt, 1),
pub fn set(self: anytype) void { pub fn set(self: anytype) void {
@ -63,7 +63,7 @@ pub fn Bitfield(comptime FieldType: type, comptime shamt: usize, comptime num_bi
const ValueType = std.meta.Int(.unsigned, num_bits); const ValueType = std.meta.Int(.unsigned, num_bits);
return struct { return extern struct {
dummy: FieldType, dummy: FieldType,
fn field(self: anytype) PtrCastPreserveCV(@This(), @TypeOf(self), FieldType) { fn field(self: anytype) PtrCastPreserveCV(@This(), @TypeOf(self), FieldType) {

View File

@ -11,7 +11,6 @@ const pitch = @import("core/ppu.zig").framebuf_pitch;
const scale = @import("core/emu.zig").win_scale; const scale = @import("core/emu.zig").win_scale;
const emu = @import("core/emu.zig"); const emu = @import("core/emu.zig");
const asString = @import("core/util.zig").asString;
const log = std.log.scoped(.GUI); const log = std.log.scoped(.GUI);
const default_title: []const u8 = "ZBA"; const default_title: []const u8 = "ZBA";
@ -54,11 +53,11 @@ pub fn init(title: [12]u8, width: i32, height: i32) Self {
}; };
} }
pub fn run(self: *Self, arm7tdmi: *Arm7tdmi, scheduler: *Scheduler) !void { pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void {
var quit = std.atomic.Atomic(bool).init(false); var quit = std.atomic.Atomic(bool).init(false);
var frame_rate = FpsTracker.init(); var frame_rate = FpsTracker.init();
const thread = try std.Thread.spawn(.{}, emu.run, .{ &quit, &frame_rate, scheduler, arm7tdmi }); const thread = try std.Thread.spawn(.{}, emu.run, .{ &quit, &frame_rate, scheduler, cpu });
defer thread.join(); defer thread.join();
var title_buf: [0x100]u8 = [_]u8{0} ** 0x100; var title_buf: [0x100]u8 = [_]u8{0} ** 0x100;
@ -69,7 +68,7 @@ pub fn run(self: *Self, arm7tdmi: *Arm7tdmi, scheduler: *Scheduler) !void {
switch (event.type) { switch (event.type) {
SDL.SDL_QUIT => break :emu_loop, SDL.SDL_QUIT => break :emu_loop,
SDL.SDL_KEYDOWN => { SDL.SDL_KEYDOWN => {
const io = &arm7tdmi.bus.io; const io = &cpu.bus.io;
const key_code = event.key.keysym.sym; const key_code = event.key.keysym.sym;
switch (key_code) { switch (key_code) {
@ -87,7 +86,7 @@ pub fn run(self: *Self, arm7tdmi: *Arm7tdmi, scheduler: *Scheduler) !void {
} }
}, },
SDL.SDL_KEYUP => { SDL.SDL_KEYUP => {
const io = &arm7tdmi.bus.io; const io = &cpu.bus.io;
const key_code = event.key.keysym.sym; const key_code = event.key.keysym.sym;
switch (key_code) { switch (key_code) {
@ -101,12 +100,12 @@ pub fn run(self: *Self, arm7tdmi: *Arm7tdmi, scheduler: *Scheduler) !void {
SDL.SDLK_s => io.keyinput.shoulder_r.set(), SDL.SDLK_s => io.keyinput.shoulder_r.set(),
SDL.SDLK_RETURN => io.keyinput.start.set(), SDL.SDLK_RETURN => io.keyinput.start.set(),
SDL.SDLK_RSHIFT => io.keyinput.select.set(), SDL.SDLK_RSHIFT => io.keyinput.select.set(),
SDL.SDLK_i => log.err("Sample Count: {}", .{@intCast(u32, SDL.SDL_AudioStreamAvailable(arm7tdmi.bus.apu.stream)) / (2 * @sizeOf(u16))}), SDL.SDLK_i => log.err("Sample Count: {}", .{@intCast(u32, SDL.SDL_AudioStreamAvailable(cpu.bus.apu.stream)) / (2 * @sizeOf(u16))}),
SDL.SDLK_j => log.err("Scheduler Capacity: {} | Scheduler Event Count: {}", .{ scheduler.queue.capacity(), scheduler.queue.count() }), SDL.SDLK_j => log.err("Scheduler Capacity: {} | Scheduler Event Count: {}", .{ scheduler.queue.capacity(), scheduler.queue.count() }),
SDL.SDLK_k => { SDL.SDLK_k => {
// Dump IWRAM to file // Dump IWRAM to file
log.info("PC: 0x{X:0>8}", .{arm7tdmi.r[15]}); log.info("PC: 0x{X:0>8}", .{cpu.r[15]});
log.info("LR: 0x{X:0>8}", .{arm7tdmi.r[14]}); log.info("LR: 0x{X:0>8}", .{cpu.r[14]});
// const iwram_file = try std.fs.cwd().createFile("iwram.bin", .{}); // const iwram_file = try std.fs.cwd().createFile("iwram.bin", .{});
// defer iwram_file.close(); // defer iwram_file.close();
@ -120,7 +119,7 @@ pub fn run(self: *Self, arm7tdmi: *Arm7tdmi, scheduler: *Scheduler) !void {
} }
// Emulator has an internal Double Buffer // Emulator has an internal Double Buffer
const framebuf = arm7tdmi.bus.ppu.framebuf.get(.Renderer); const framebuf = cpu.bus.ppu.framebuf.get(.Renderer);
_ = SDL.SDL_UpdateTexture(self.texture, null, framebuf.ptr, pitch); _ = SDL.SDL_UpdateTexture(self.texture, null, framebuf.ptr, pitch);
_ = SDL.SDL_RenderCopy(self.renderer, self.texture, null, null); _ = SDL.SDL_RenderCopy(self.renderer, self.texture, null, null);
SDL.SDL_RenderPresent(self.renderer); SDL.SDL_RenderPresent(self.renderer);
@ -137,12 +136,13 @@ pub fn initAudio(self: *Self, apu: *Apu) void {
self.audio.?.play(); self.audio.?.play();
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
if (self.audio) |aud| aud.deinit(); if (self.audio) |*aud| aud.deinit();
SDL.SDL_DestroyTexture(self.texture); SDL.SDL_DestroyTexture(self.texture);
SDL.SDL_DestroyRenderer(self.renderer); SDL.SDL_DestroyRenderer(self.renderer);
SDL.SDL_DestroyWindow(self.window); SDL.SDL_DestroyWindow(self.window);
SDL.SDL_Quit(); SDL.SDL_Quit();
self.* = undefined;
} }
const Audio = struct { const Audio = struct {
@ -169,12 +169,13 @@ const Audio = struct {
}; };
} }
fn deinit(this: This) void { fn deinit(self: *This) void {
SDL.SDL_CloseAudioDevice(this.device); SDL.SDL_CloseAudioDevice(self.device);
self.* = undefined;
} }
pub fn play(this: *This) void { pub fn play(self: *This) void {
SDL.SDL_PauseAudioDevice(this.device, 0); SDL.SDL_PauseAudioDevice(self.device, 0);
} }
export fn callback(userdata: ?*anyopaque, stream: [*c]u8, len: c_int) void { export fn callback(userdata: ?*anyopaque, stream: [*c]u8, len: c_int) void {

View File

@ -49,32 +49,29 @@ io: Io,
cpu: ?*Arm7tdmi, cpu: ?*Arm7tdmi,
sched: *Scheduler, sched: *Scheduler,
pub fn init(alloc: Allocator, sched: *Scheduler, paths: FilePaths) !Self { pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void {
return Self{ self.* = .{
.pak = try GamePak.init(alloc, paths.rom, paths.save), .pak = try GamePak.init(allocator, paths.rom, paths.save),
.bios = try Bios.init(alloc, paths.bios), .bios = try Bios.init(allocator, paths.bios),
.ppu = try Ppu.init(alloc, sched), .ppu = try Ppu.init(allocator, sched),
.apu = Apu.init(sched), .apu = Apu.init(sched),
.iwram = try Iwram.init(alloc), .iwram = try Iwram.init(allocator),
.ewram = try Ewram.init(alloc), .ewram = try Ewram.init(allocator),
.dma = createDmaTuple(), .dma = createDmaTuple(),
.tim = createTimerTuple(sched), .tim = createTimerTuple(sched),
.io = Io.init(), .io = Io.init(),
.cpu = null, .cpu = cpu,
.sched = sched, .sched = sched,
}; };
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.iwram.deinit(); self.iwram.deinit();
self.ewram.deinit(); self.ewram.deinit();
self.pak.deinit(); self.pak.deinit();
self.bios.deinit(); self.bios.deinit();
self.ppu.deinit(); self.ppu.deinit();
} self.* = undefined;
pub fn attach(self: *Self, cpu: *Arm7tdmi) void {
self.cpu = cpu;
} }
pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T { pub fn dbgRead(self: *const Self, comptime T: type, address: u32) T {

View File

@ -444,29 +444,29 @@ const ToneSweep = struct {
}; };
} }
pub fn tick(this: *This, ch1: *Self) void { pub fn tick(self: *This, ch1: *Self) void {
if (this.timer != 0) this.timer -= 1; if (self.timer != 0) self.timer -= 1;
if (this.timer == 0) { if (self.timer == 0) {
const period = ch1.sweep.period.read(); const period = ch1.sweep.period.read();
this.timer = if (period == 0) 8 else period; self.timer = if (period == 0) 8 else period;
if (!this.calc_performed) this.calc_performed = true; if (!self.calc_performed) self.calc_performed = true;
if (this.enabled and period != 0) { if (self.enabled and period != 0) {
const new_freq = this.calcFrequency(ch1); const new_freq = self.calcFrequency(ch1);
if (new_freq <= 0x7FF and ch1.sweep.shift.read() != 0) { if (new_freq <= 0x7FF and ch1.sweep.shift.read() != 0) {
ch1.freq.frequency.write(@truncate(u11, new_freq)); ch1.freq.frequency.write(@truncate(u11, new_freq));
this.shadow = @truncate(u11, new_freq); self.shadow = @truncate(u11, new_freq);
_ = this.calcFrequency(ch1); _ = self.calcFrequency(ch1);
} }
} }
} }
} }
fn calcFrequency(this: *This, ch1: *Self) u12 { fn calcFrequency(self: *This, ch1: *Self) u12 {
const shadow = @as(u12, this.shadow); const shadow = @as(u12, self.shadow);
const shadow_shifted = shadow >> ch1.sweep.shift.read(); const shadow_shifted = shadow >> ch1.sweep.shift.read();
const decrease = ch1.sweep.direction.read(); const decrease = ch1.sweep.direction.read();

View File

@ -8,27 +8,28 @@ pub const size = 0x4000;
const Self = @This(); const Self = @This();
buf: ?[]u8, buf: ?[]u8,
alloc: Allocator, allocator: Allocator,
addr_latch: u32, addr_latch: u32,
pub fn init(alloc: Allocator, maybe_path: ?[]const u8) !Self { pub fn init(allocator: Allocator, maybe_path: ?[]const u8) !Self {
var buf: ?[]u8 = null; const buf: ?[]u8 = if (maybe_path) |path| blk: {
if (maybe_path) |path| {
const file = try std.fs.cwd().openFile(path, .{}); const file = try std.fs.cwd().openFile(path, .{});
defer file.close(); defer file.close();
buf = try file.readToEndAlloc(alloc, try file.getEndPos());
} break :blk try file.readToEndAlloc(allocator, try file.getEndPos());
} else null;
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
.addr_latch = 0, .addr_latch = 0,
}; };
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
if (self.buf) |buf| self.alloc.free(buf); if (self.buf) |buf| self.allocator.free(buf);
self.* = undefined;
} }
pub fn read(self: *Self, comptime T: type, r15: u32, addr: u32) T { pub fn read(self: *Self, comptime T: type, r15: u32, addr: u32) T {

View File

@ -5,20 +5,21 @@ const ewram_size = 0x40000;
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
pub fn init(alloc: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try alloc.alloc(u8, ewram_size); const buf = try allocator.alloc(u8, ewram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
}; };
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *const Self, comptime T: type, address: usize) T { pub fn read(self: *const Self, comptime T: type, address: usize) T {

View File

@ -8,22 +8,22 @@ const Self = @This();
title: [12]u8, title: [12]u8,
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
backup: Backup, backup: Backup,
pub fn init(alloc: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { pub fn init(allocator: Allocator, 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(alloc, try file.getEndPos()); const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos());
const title = parseTitle(file_buf); const title = parseTitle(file_buf);
const kind = Backup.guessKind(file_buf) orelse .None; const kind = Backup.guessKind(file_buf) orelse .None;
const pak = Self{ const pak = Self{
.buf = file_buf, .buf = file_buf,
.alloc = alloc, .allocator = allocator,
.title = title, .title = title,
.backup = try Backup.init(alloc, kind, title, save_path), .backup = try Backup.init(allocator, kind, title, save_path),
}; };
pak.parseHeader(); pak.parseHeader();
@ -58,9 +58,10 @@ inline fn isLarge(self: *const Self) bool {
return self.buf.len > 0x100_0000; return self.buf.len > 0x100_0000;
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.alloc.free(self.buf);
self.backup.deinit(); self.backup.deinit();
self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *Self, comptime T: type, address: u32) T { pub fn read(self: *Self, comptime T: type, address: u32) T {

View File

@ -5,20 +5,21 @@ const iwram_size = 0x8000;
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
pub fn init(alloc: Allocator) !Self { pub fn init(allocator: Allocator) !Self {
const buf = try alloc.alloc(u8, iwram_size); const buf = try allocator.alloc(u8, iwram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
}; };
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *const Self, comptime T: type, address: usize) T { pub fn read(self: *const Self, comptime T: type, address: usize) T {

View File

@ -3,7 +3,7 @@ const Allocator = std.mem.Allocator;
const log = std.log.scoped(.Backup); const log = std.log.scoped(.Backup);
const escape = @import("../util.zig").escape; const escape = @import("../util.zig").escape;
const asString = @import("../util.zig").asString; const asStringSlice = @import("../util.zig").asStringSlice;
const backup_kinds = [5]Needle{ const backup_kinds = [5]Needle{
.{ .str = "EEPROM_V", .kind = .Eeprom }, .{ .str = "EEPROM_V", .kind = .Eeprom },
@ -17,8 +17,8 @@ pub const Backup = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
kind: BackupKind, kind: Kind,
title: [12]u8, title: [12]u8,
save_path: ?[]const u8, save_path: ?[]const u8,
@ -26,7 +26,15 @@ pub const Backup = struct {
flash: Flash, flash: Flash,
eeprom: Eeprom, eeprom: Eeprom,
pub fn init(alloc: Allocator, kind: BackupKind, title: [12]u8, path: ?[]const u8) !Self { const Kind = enum {
Eeprom,
Sram,
Flash,
Flash1M,
None,
};
pub fn init(allocator: Allocator, kind: Kind, title: [12]u8, path: ?[]const u8) !Self {
log.info("Kind: {}", .{kind}); log.info("Kind: {}", .{kind});
const buf_size: usize = switch (kind) { const buf_size: usize = switch (kind) {
@ -36,24 +44,24 @@ pub const Backup = struct {
.None, .Eeprom => 0, // EEPROM is handled upon first Read Request to it .None, .Eeprom => 0, // EEPROM is handled upon first Read Request to it
}; };
const buf = try alloc.alloc(u8, buf_size); const buf = try allocator.alloc(u8, buf_size);
std.mem.set(u8, buf, 0xFF); std.mem.set(u8, buf, 0xFF);
var backup = Self{ var backup = Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
.kind = kind, .kind = kind,
.title = title, .title = title,
.save_path = path, .save_path = path,
.flash = Flash.init(), .flash = Flash.init(),
.eeprom = Eeprom.init(alloc), .eeprom = Eeprom.init(allocator),
}; };
if (backup.save_path) |p| backup.loadSaveFromDisk(p) catch |e| log.err("Failed to load save: {}", .{e}); if (backup.save_path) |p| backup.loadSaveFromDisk(allocator, p) catch |e| log.err("Failed to load save: {}", .{e});
return backup; return backup;
} }
pub fn guessKind(rom: []const u8) ?BackupKind { 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;
@ -66,14 +74,15 @@ pub const Backup = struct {
return null; return null;
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
if (self.save_path) |path| self.writeSaveToDisk(path) catch |e| log.err("Failed to write save: {}", .{e}); if (self.save_path) |path| self.writeSaveToDisk(self.allocator, path) catch |e| log.err("Failed to write save: {}", .{e});
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
fn loadSaveFromDisk(self: *Self, path: []const u8) !void { fn loadSaveFromDisk(self: *Self, allocator: Allocator, path: []const u8) !void {
const file_path = try self.getSaveFilePath(path); const file_path = try self.getSaveFilePath(allocator, path);
defer self.alloc.free(file_path); defer allocator.free(file_path);
// FIXME: Don't rely on this lol // FIXME: Don't rely on this lol
if (std.mem.eql(u8, file_path[file_path.len - 12 .. file_path.len], "untitled.sav")) { if (std.mem.eql(u8, file_path[file_path.len - 12 .. file_path.len], "untitled.sav")) {
@ -81,8 +90,8 @@ pub const Backup = struct {
} }
const file: std.fs.File = try std.fs.openFileAbsolute(file_path, .{}); const file: std.fs.File = try std.fs.openFileAbsolute(file_path, .{});
const file_buf = try file.readToEndAlloc(self.alloc, try file.getEndPos()); const file_buf = try file.readToEndAlloc(allocator, try file.getEndPos());
defer self.alloc.free(file_buf); defer allocator.free(file_buf);
switch (self.kind) { switch (self.kind) {
.Sram, .Flash, .Flash1M => { .Sram, .Flash, .Flash1M => {
@ -97,7 +106,7 @@ pub const Backup = struct {
if (file_buf.len == 0x200 or file_buf.len == 0x2000) { if (file_buf.len == 0x200 or file_buf.len == 0x2000) {
self.eeprom.kind = if (file_buf.len == 0x200) .Small else .Large; self.eeprom.kind = if (file_buf.len == 0x200) .Small else .Large;
self.buf = try self.alloc.alloc(u8, file_buf.len); self.buf = try allocator.alloc(u8, file_buf.len);
std.mem.copy(u8, self.buf, file_buf); std.mem.copy(u8, self.buf, file_buf);
return log.info("Loaded Save from {s}", .{file_path}); return log.info("Loaded Save from {s}", .{file_path});
} }
@ -111,23 +120,23 @@ pub const Backup = struct {
} }
} }
fn getSaveFilePath(self: *const Self, path: []const u8) ![]const u8 { fn getSaveFilePath(self: *const Self, allocator: Allocator, path: []const u8) ![]const u8 {
const filename = try self.getSaveFilename(); const filename = try self.getSaveFilename(allocator);
defer self.alloc.free(filename); defer allocator.free(filename);
return try std.fs.path.join(self.alloc, &[_][]const u8{ path, filename }); return try std.fs.path.join(allocator, &[_][]const u8{ path, filename });
} }
fn getSaveFilename(self: *const Self) ![]const u8 { fn getSaveFilename(self: *const Self, allocator: Allocator) ![]const u8 {
const title = asString(escape(self.title)); const title_str = asStringSlice(&escape(self.title));
const name = if (title.len != 0) title else "untitled"; const name = if (title_str.len != 0) title_str else "untitled";
return try std.mem.concat(self.alloc, u8, &[_][]const u8{ name, ".sav" }); return try std.mem.concat(allocator, u8, &[_][]const u8{ name, ".sav" });
} }
fn writeSaveToDisk(self: Self, path: []const u8) !void { fn writeSaveToDisk(self: Self, allocator: Allocator, path: []const u8) !void {
const file_path = try self.getSaveFilePath(path); const file_path = try self.getSaveFilePath(allocator, path);
defer self.alloc.free(file_path); defer allocator.free(file_path);
switch (self.kind) { switch (self.kind) {
.Sram, .Flash, .Flash1M, .Eeprom => { .Sram, .Flash, .Flash1M, .Eeprom => {
@ -201,21 +210,13 @@ pub const Backup = struct {
} }
}; };
const BackupKind = enum {
Eeprom,
Sram,
Flash,
Flash1M,
None,
};
const Needle = struct { const Needle = struct {
const Self = @This(); const Self = @This();
str: []const u8, str: []const u8,
kind: BackupKind, kind: Backup.Kind,
fn init(str: []const u8, kind: BackupKind) Self { fn init(str: []const u8, kind: Backup.Kind) Self {
return .{ return .{
.str = str, .str = str,
.kind = kind, .kind = kind,
@ -230,7 +231,7 @@ const SaveError = error{
const Flash = struct { const Flash = struct {
const Self = @This(); const Self = @This();
state: FlashState, state: State,
id_mode: bool, id_mode: bool,
set_bank: bool, set_bank: bool,
@ -239,6 +240,12 @@ const Flash = struct {
bank: u1, bank: u1,
const State = enum {
Ready,
Set,
Command,
};
fn init() Self { fn init() Self {
return .{ return .{
.state = .Ready, .state = .Ready,
@ -293,12 +300,6 @@ const Flash = struct {
} }
}; };
const FlashState = enum {
Ready,
Set,
Command,
};
const Eeprom = struct { const Eeprom = struct {
const Self = @This(); const Self = @This();
@ -309,7 +310,7 @@ const Eeprom = struct {
writer: Writer, writer: Writer,
reader: Reader, reader: Reader,
alloc: Allocator, allocator: Allocator,
const Kind = enum { const Kind = enum {
Unknown, Unknown,
@ -325,14 +326,14 @@ const Eeprom = struct {
RequestEnd, RequestEnd,
}; };
fn init(alloc: Allocator) Self { fn init(allocator: Allocator) Self {
return .{ return .{
.kind = .Unknown, .kind = .Unknown,
.state = .Ready, .state = .Ready,
.writer = Writer.init(), .writer = Writer.init(),
.reader = Reader.init(), .reader = Reader.init(),
.addr = 0, .addr = 0,
.alloc = alloc, .allocator = allocator,
}; };
} }
@ -360,7 +361,7 @@ const Eeprom = struct {
else => unreachable, else => unreachable,
}; };
buf.* = self.alloc.alloc(u8, len) catch |e| { buf.* = self.allocator.alloc(u8, len) catch |e| {
log.err("Failed to resize EEPROM buf to {} bytes", .{len}); log.err("Failed to resize EEPROM buf to {} bytes", .{len});
std.debug.panic("EEPROM entered irrecoverable state {}", .{e}); std.debug.panic("EEPROM entered irrecoverable state {}", .{e});
}; };

View File

@ -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),
@ -464,37 +472,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

@ -12,7 +12,7 @@ const File = std.fs.File;
// ARM Instructions // ARM Instructions
pub const arm = struct { pub const arm = struct {
pub const InstrFn = fn (*Arm7tdmi, *Bus, u32) void; pub const InstrFn = *const fn (*Arm7tdmi, *Bus, u32) void;
const lut: [0x1000]InstrFn = populate(); const lut: [0x1000]InstrFn = populate();
const processing = @import("cpu/arm/data_processing.zig").dataProcessing; const processing = @import("cpu/arm/data_processing.zig").dataProcessing;
@ -110,7 +110,7 @@ pub const arm = struct {
// THUMB Instructions // THUMB Instructions
pub const thumb = struct { pub const thumb = struct {
pub const InstrFn = fn (*Arm7tdmi, *Bus, u16) void; pub const InstrFn = *const fn (*Arm7tdmi, *Bus, u16) void;
const lut: [0x400]InstrFn = populate(); const lut: [0x400]InstrFn = populate();
const processing = @import("cpu/thumb/data_processing.zig"); const processing = @import("cpu/thumb/data_processing.zig");
@ -250,7 +250,7 @@ pub const Arm7tdmi = struct {
logger: ?Logger, logger: ?Logger,
pub fn init(sched: *Scheduler, bus: *Bus) Self { pub fn init(sched: *Scheduler, bus: *Bus, log_file: ?std.fs.File) Self {
return Self{ return Self{
.r = [_]u32{0x00} ** 16, .r = [_]u32{0x00} ** 16,
.sched = sched, .sched = sched,
@ -260,14 +260,10 @@ pub const Arm7tdmi = struct {
.banked_fiq = [_]u32{0x00} ** 10, .banked_fiq = [_]u32{0x00} ** 10,
.banked_r = [_]u32{0x00} ** 12, .banked_r = [_]u32{0x00} ** 12,
.banked_spsr = [_]PSR{.{ .raw = 0x0000_0000 }} ** 5, .banked_spsr = [_]PSR{.{ .raw = 0x0000_0000 }} ** 5,
.logger = null, .logger = if (log_file) |file| Logger.init(file) else null,
}; };
} }
pub fn attach(self: *Self, log_file: std.fs.File) void {
self.logger = Logger.init(log_file);
}
inline fn bankedIdx(mode: Mode, kind: BankedKind) usize { inline fn bankedIdx(mode: Mode, kind: BankedKind) usize {
const idx: usize = switch (mode) { const idx: usize = switch (mode) {
.User, .System => 0, .User, .System => 0,

View File

@ -41,28 +41,25 @@ pub const Ppu = struct {
oam: Oam, oam: Oam,
sched: *Scheduler, sched: *Scheduler,
framebuf: FrameBuffer, framebuf: FrameBuffer,
alloc: Allocator, allocator: Allocator,
scanline_sprites: [128]?Sprite, scanline_sprites: *[128]?Sprite,
scanline: Scanline, scanline: Scanline,
pub fn init(alloc: Allocator, sched: *Scheduler) !Self { pub fn init(allocator: Allocator, sched: *Scheduler) !Self {
// Queue first Hblank // Queue first Hblank
sched.push(.Draw, 240 * 4); sched.push(.Draw, 240 * 4);
const framebufs = try alloc.alloc(u8, (framebuf_pitch * height) * 2); const sprites = try allocator.create([128]?Sprite);
std.mem.set(u8, framebufs, 0); sprites.* = [_]?Sprite{null} ** 128;
const scanline_buf = try alloc.alloc(?u16, width * 2);
std.mem.set(?u16, scanline_buf, null);
return Self{ return Self{
.vram = try Vram.init(alloc), .vram = try Vram.init(allocator),
.palette = try Palette.init(alloc), .palette = try Palette.init(allocator),
.oam = try Oam.init(alloc), .oam = try Oam.init(allocator),
.sched = sched, .sched = sched,
.framebuf = FrameBuffer.init(framebufs), .framebuf = try FrameBuffer.init(allocator),
.alloc = alloc, .allocator = allocator,
// Registers // Registers
.win = Window.init(), .win = Window.init(),
@ -75,17 +72,19 @@ pub const Ppu = struct {
.bldalpha = .{ .raw = 0x0000 }, .bldalpha = .{ .raw = 0x0000 },
.bldy = .{ .raw = 0x0000 }, .bldy = .{ .raw = 0x0000 },
.scanline = Scanline.init(scanline_buf), .scanline = try Scanline.init(allocator),
.scanline_sprites = [_]?Sprite{null} ** 128, .scanline_sprites = sprites,
}; };
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.framebuf.deinit(self.alloc); self.allocator.destroy(self.scanline_sprites);
self.scanline.deinit(self.alloc); self.framebuf.deinit();
self.scanline.deinit();
self.vram.deinit(); self.vram.deinit();
self.palette.deinit(); self.palette.deinit();
self.oam.deinit(); self.oam.deinit();
self.* = undefined;
} }
pub fn setBgOffsets(self: *Self, comptime n: u2, word: u32) void { pub fn setBgOffsets(self: *Self, comptime n: u2, word: u32) void {
@ -278,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;
@ -297,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);
} }
} }
@ -306,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());
@ -326,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));
@ -354,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);
} }
} }
} }
@ -380,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
@ -399,7 +400,7 @@ pub const Ppu = struct {
// Reset Current Scanline Pixel Buffer and list of fetched sprites // Reset Current Scanline Pixel Buffer and list of fetched sprites
// in prep for next scanline // in prep for next scanline
self.scanline.reset(); self.scanline.reset();
std.mem.set(?Sprite, &self.scanline_sprites, null); std.mem.set(?Sprite, self.scanline_sprites, null);
}, },
0x1 => { 0x1 => {
const fb_base = framebuf_pitch * @as(usize, scanline); const fb_base = framebuf_pitch * @as(usize, scanline);
@ -408,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);
} }
@ -426,7 +427,7 @@ pub const Ppu = struct {
// Reset Current Scanline Pixel Buffer and list of fetched sprites // Reset Current Scanline Pixel Buffer and list of fetched sprites
// in prep for next scanline // in prep for next scanline
self.scanline.reset(); self.scanline.reset();
std.mem.set(?Sprite, &self.scanline_sprites, null); std.mem.set(?Sprite, self.scanline_sprites, null);
}, },
0x2 => { 0x2 => {
const fb_base = framebuf_pitch * @as(usize, scanline); const fb_base = framebuf_pitch * @as(usize, scanline);
@ -452,7 +453,7 @@ pub const Ppu = struct {
// Reset Current Scanline Pixel Buffer and list of fetched sprites // Reset Current Scanline Pixel Buffer and list of fetched sprites
// in prep for next scanline // in prep for next scanline
self.scanline.reset(); self.scanline.reset();
std.mem.set(?Sprite, &self.scanline_sprites, null); std.mem.set(?Sprite, self.scanline_sprites, null);
}, },
0x3 => { 0x3 => {
const vram_base = width * @sizeOf(u16) * @as(usize, scanline); const vram_base = width * @sizeOf(u16) * @as(usize, scanline);
@ -534,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
@ -629,20 +717,21 @@ const Palette = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
fn init(alloc: Allocator) !Self { fn init(allocator: Allocator) !Self {
const buf = try alloc.alloc(u8, palram_size); const buf = try allocator.alloc(u8, palram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
}; };
} }
fn deinit(self: Self) void { fn deinit(self: *Self) void {
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *const Self, comptime T: type, address: usize) T { pub fn read(self: *const Self, comptime T: type, address: usize) T {
@ -677,20 +766,21 @@ const Vram = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
fn init(alloc: Allocator) !Self { fn init(allocator: Allocator) !Self {
const buf = try alloc.alloc(u8, vram_size); const buf = try allocator.alloc(u8, vram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
}; };
} }
fn deinit(self: Self) void { fn deinit(self: *Self) void {
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *const Self, comptime T: type, address: usize) T { pub fn read(self: *const Self, comptime T: type, address: usize) T {
@ -737,20 +827,21 @@ const Oam = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
alloc: Allocator, allocator: Allocator,
fn init(alloc: Allocator) !Self { fn init(allocator: Allocator) !Self {
const buf = try alloc.alloc(u8, oam_size); const buf = try allocator.alloc(u8, oam_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.alloc = alloc, .allocator = allocator,
}; };
} }
fn deinit(self: Self) void { fn deinit(self: *Self) void {
self.alloc.free(self.buf); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn read(self: *const Self, comptime T: type, address: usize) T { pub fn read(self: *const Self, comptime T: type, address: usize) T {
@ -792,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);
@ -1133,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;
@ -1178,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
@ -1213,35 +1275,38 @@ fn copyToSpriteBuffer(bldcnt: io.BldCnt, scanline: *Scanline, x: u9, bgr555: u16
const Scanline = struct { const Scanline = struct {
const Self = @This(); const Self = @This();
buf: [2][]?u16, layers: [2][]?u16,
original: []?u16, buf: []?u16,
fn init(buf: []?u16) Self { allocator: Allocator,
std.debug.assert(buf.len == width * 2);
const top_slice = buf[0..][0..width]; fn init(allocator: Allocator) !Self {
const btm_slice = buf[width..][0..width]; const buf = try allocator.alloc(?u16, width * 2); // Top & Bottom Scanline
std.mem.set(?u16, buf, null);
return .{ return .{
.buf = [_][]?u16{ top_slice, btm_slice }, // Top & Bototm Layers
.original = buf, .layers = [_][]?u16{ buf[0..][0..width], buf[width..][0..width] },
.buf = buf,
.allocator = allocator,
}; };
} }
fn reset(self: *Self) void { fn reset(self: *Self) void {
std.mem.set(?u16, self.original, null); std.mem.set(?u16, self.buf, null);
} }
fn deinit(self: Self, alloc: Allocator) void { fn deinit(self: *Self) void {
alloc.free(self.original); self.allocator.free(self.buf);
self.* = undefined;
} }
fn top(self: *Self) []?u16 { fn top(self: *Self) []?u16 {
return self.buf[0]; return self.layers[0];
} }
fn btm(self: *Self) []?u16 { fn btm(self: *Self) []?u16 {
return self.buf[1]; return self.layers[1];
} }
}; };
@ -1249,31 +1314,36 @@ const Scanline = struct {
const FrameBuffer = struct { const FrameBuffer = struct {
const Self = @This(); const Self = @This();
buf: [2][]u8, layers: [2][]u8,
original: []u8, buf: []u8,
current: u1, current: u1,
allocator: Allocator,
// TODO: Rename // TODO: Rename
const Device = enum { const Device = enum {
Emulator, Emulator,
Renderer, Renderer,
}; };
pub fn init(bufs: []u8) Self { pub fn init(allocator: Allocator) !Self {
std.debug.assert(bufs.len == framebuf_pitch * height * 2); const framebuf_len = framebuf_pitch * height;
const buf = try allocator.alloc(u8, framebuf_len * 2);
const front = bufs[0 .. framebuf_pitch * height]; std.mem.set(u8, buf, 0);
const back = bufs[framebuf_pitch * height ..];
return .{ return .{
.buf = [2][]u8{ front, back }, // Front and Back Framebuffers
.original = bufs, .layers = [_][]u8{ buf[0..][0..framebuf_len], buf[framebuf_len..][0..framebuf_len] },
.buf = buf,
.current = 0, .current = 0,
.allocator = allocator,
}; };
} }
fn deinit(self: Self, alloc: Allocator) void { fn deinit(self: *Self) void {
alloc.free(self.original); self.allocator.free(self.buf);
self.* = undefined;
} }
pub fn swap(self: *Self) void { pub fn swap(self: *Self) void {
@ -1281,6 +1351,6 @@ const FrameBuffer = struct {
} }
pub fn get(self: *Self, comptime dev: Device) []u8 { pub fn get(self: *Self, comptime dev: Device) []u8 {
return self.buf[if (dev == .Emulator) self.current else ~self.current]; return self.layers[if (dev == .Emulator) self.current else ~self.current];
} }
}; };

View File

@ -14,15 +14,16 @@ pub const Scheduler = struct {
tick: u64, tick: u64,
queue: PriorityQueue(Event, void, lessThan), queue: PriorityQueue(Event, void, lessThan),
pub fn init(alloc: Allocator) Self { pub fn init(allocator: Allocator) Self {
var sched = Self{ .tick = 0, .queue = PriorityQueue(Event, void, lessThan).init(alloc, {}) }; var sched = Self{ .tick = 0, .queue = PriorityQueue(Event, void, lessThan).init(allocator, {}) };
sched.queue.add(.{ .kind = .HeatDeath, .tick = std.math.maxInt(u64) }) catch unreachable; sched.queue.add(.{ .kind = .HeatDeath, .tick = std.math.maxInt(u64) }) catch unreachable;
return sched; return sched;
} }
pub fn deinit(self: Self) void { pub fn deinit(self: *Self) void {
self.queue.deinit(); self.queue.deinit();
self.* = undefined;
} }
pub inline fn now(self: *const Self) u64 { pub inline fn now(self: *const Self) u64 {

View File

@ -69,7 +69,7 @@ pub fn intToBytes(comptime T: type, value: anytype) [@sizeOf(T)]u8 {
/// ///
/// This function returns a slice of everything just before the first /// This function returns a slice of everything just before the first
/// `\0` /// `\0`
pub fn asString(title: [12]u8) []const u8 { pub fn asStringSlice(title: *const [12]u8) []const u8 {
var len = title.len; var len = title.len;
for (title) |char, i| { for (title) |char, i| {
if (char == 0) { if (char == 0) {
@ -129,45 +129,45 @@ pub const Logger = struct {
try self.buf.writer().print(format, args); try self.buf.writer().print(format, args);
} }
pub fn mgbaLog(self: *Self, arm7tdmi: *const Arm7tdmi, opcode: u32) void { pub fn mgbaLog(self: *Self, cpu: *const Arm7tdmi, opcode: u32) void {
const fmt_base = "{X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} cpsr: {X:0>8} | "; const fmt_base = "{X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} {X:0>8} cpsr: {X:0>8} | ";
const thumb_fmt = fmt_base ++ "{X:0>4}:\n"; const thumb_fmt = fmt_base ++ "{X:0>4}:\n";
const arm_fmt = fmt_base ++ "{X:0>8}:\n"; const arm_fmt = fmt_base ++ "{X:0>8}:\n";
if (arm7tdmi.cpsr.t.read()) { if (cpu.cpsr.t.read()) {
if (opcode >> 11 == 0x1E) { if (opcode >> 11 == 0x1E) {
// Instruction 1 of a BL Opcode, print in ARM mode // Instruction 1 of a BL Opcode, print in ARM mode
const low = arm7tdmi.bus.dbgRead(u16, arm7tdmi.r[15]); const low = cpu.bus.dbgRead(u16, cpu.r[15]);
const bl_opcode = @as(u32, opcode) << 16 | low; const bl_opcode = @as(u32, opcode) << 16 | low;
self.print(arm_fmt, Self.fmtArgs(arm7tdmi, bl_opcode)) catch @panic("failed to write to log file"); self.print(arm_fmt, Self.fmtArgs(cpu, bl_opcode)) catch @panic("failed to write to log file");
} else { } else {
self.print(thumb_fmt, Self.fmtArgs(arm7tdmi, opcode)) catch @panic("failed to write to log file"); self.print(thumb_fmt, Self.fmtArgs(cpu, opcode)) catch @panic("failed to write to log file");
} }
} else { } else {
self.print(arm_fmt, Self.fmtArgs(arm7tdmi, opcode)) catch @panic("failed to write to log file"); self.print(arm_fmt, Self.fmtArgs(cpu, opcode)) catch @panic("failed to write to log file");
} }
} }
fn fmtArgs(arm7tdmi: *const Arm7tdmi, opcode: u32) FmtArgTuple { fn fmtArgs(cpu: *const Arm7tdmi, opcode: u32) FmtArgTuple {
return .{ return .{
arm7tdmi.r[0], cpu.r[0],
arm7tdmi.r[1], cpu.r[1],
arm7tdmi.r[2], cpu.r[2],
arm7tdmi.r[3], cpu.r[3],
arm7tdmi.r[4], cpu.r[4],
arm7tdmi.r[5], cpu.r[5],
arm7tdmi.r[6], cpu.r[6],
arm7tdmi.r[7], cpu.r[7],
arm7tdmi.r[8], cpu.r[8],
arm7tdmi.r[9], cpu.r[9],
arm7tdmi.r[10], cpu.r[10],
arm7tdmi.r[11], cpu.r[11],
arm7tdmi.r[12], cpu.r[12],
arm7tdmi.r[13], cpu.r[13],
arm7tdmi.r[14], cpu.r[14],
arm7tdmi.r[15], cpu.r[15],
arm7tdmi.cpsr.raw, cpu.cpsr.raw,
opcode, opcode,
}; };
} }

View File

@ -14,7 +14,7 @@ const Allocator = std.mem.Allocator;
const log = std.log.scoped(.CLI); const log = std.log.scoped(.CLI);
const width = @import("core/ppu.zig").width; const width = @import("core/ppu.zig").width;
const height = @import("core/ppu.zig").height; const height = @import("core/ppu.zig").height;
const arm7tdmi_logging = @import("core/emu.zig").cpu_logging; const cpu_logging = @import("core/emu.zig").cpu_logging;
pub const log_level = if (builtin.mode != .Debug) .info else std.log.default_level; pub const log_level = if (builtin.mode != .Debug) .info else std.log.default_level;
// TODO: Reimpl Logging // TODO: Reimpl Logging
@ -40,27 +40,25 @@ pub fn main() anyerror!void {
const paths = try handleArguments(allocator, &result); const paths = try handleArguments(allocator, &result);
defer if (paths.save) |path| allocator.free(path); defer if (paths.save) |path| allocator.free(path);
const log_file: ?std.fs.File = if (cpu_logging) try std.fs.cwd().createFile("zba.log", .{}) else null;
defer if (log_file) |file| file.close();
// TODO: Take Emulator Init Code out of main.zig // TODO: Take Emulator Init Code out of main.zig
var scheduler = Scheduler.init(allocator); var scheduler = Scheduler.init(allocator);
defer scheduler.deinit(); defer scheduler.deinit();
var bus = try Bus.init(allocator, &scheduler, paths); var bus: Bus = undefined;
var cpu = Arm7tdmi.init(&scheduler, &bus, log_file);
if (paths.bios == null) cpu.fastBoot();
try bus.init(allocator, &scheduler, &cpu, paths);
defer bus.deinit(); defer bus.deinit();
var arm7tdmi = Arm7tdmi.init(&scheduler, &bus);
const log_file: ?std.fs.File = if (arm7tdmi_logging) try std.fs.cwd().createFile("zba.log", .{}) else null;
defer if (log_file) |file| file.close();
if (log_file) |file| arm7tdmi.attach(file);
bus.attach(&arm7tdmi); // TODO: Shrink Surface (only CPSR and r15?)
if (paths.bios == null) arm7tdmi.fastBoot();
var gui = Gui.init(bus.pak.title, width, height); var gui = Gui.init(bus.pak.title, width, height);
gui.initAudio(&bus.apu); gui.initAudio(&bus.apu);
defer gui.deinit(); defer gui.deinit();
try gui.run(&arm7tdmi, &scheduler); try gui.run(&cpu, &scheduler);
} }
fn getSavePath(allocator: Allocator) !?[]const u8 { fn getSavePath(allocator: Allocator) !?[]const u8 {