Compare commits

..

9 Commits

Author SHA1 Message Date
Rekai Nyangadzayi Musuka f601bec0c4 fix: advance r15, even when the pipeline is reloaded from the scheduler
The PC would fall behind whenever an IRQ was called because the pipeline
was reloaded (+8 to PC), however that was never actually done by any code

Now, the PC is always incremented when the pipeline is reloaded
2022-08-26 23:59:59 -05:00
Rekai Nyangadzayi Musuka 2c0c3a8ac4 chore: dump pipeline state on cpu panic 2022-08-26 21:45:35 -05:00
Rekai Nyangadzayi Musuka 20d9f0a7f4 fix: reimpl THUMB.5 instructions
pipeline branch now passes arm.gba and thumb.gba again

(TODO: Stop rewriting my commits away)
2022-08-26 20:44:26 -05:00
Rekai Nyangadzayi Musuka 6919322c8c fix: impl workaround for stage2 miscompilation 2022-08-26 19:23:50 -05:00
Rekai Nyangadzayi Musuka affd89c6d6 chore: instantly refill the pipeline on flush
I believe this to be necessary in order to get hardware interrupts
working.

thumb.gba test 108 fails but I'm committing anyways (despite the
regression) because this is kind of rebase/merge hell and I have
something that at least sort of works rn
2022-08-26 14:29:49 -05:00
Rekai Nyangadzayi Musuka 5c334057b5 fix: reimpl handleInterrupt code 2022-08-26 14:29:49 -05:00
Rekai Nyangadzayi Musuka cec0e7f072 feat: implement basic pipeline
passes arm.gba, thumb.gb and armwrestler, fails in actual games
TODO: run FuzzARM debug specific titles
2022-08-26 14:29:49 -05:00
Rekai Nyangadzayi Musuka 442e90e24d feat: resolve off-by-{word, halfword} errors when printing debug info 2022-08-26 14:29:49 -05:00
Rekai Nyangadzayi Musuka 960683a1f5 feat: reimplement cpu logging 2022-08-26 14:29:49 -05:00
13 changed files with 181 additions and 190 deletions

View File

@ -53,11 +53,11 @@ pub fn init(title: [12]u8, width: i32, height: i32) Self {
}; };
} }
pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void { pub fn run(self: *Self, arm7tdmi: *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, cpu }); const thread = try std.Thread.spawn(.{}, emu.run, .{ &quit, &frame_rate, scheduler, arm7tdmi });
defer thread.join(); defer thread.join();
var title_buf: [0x100]u8 = [_]u8{0} ** 0x100; var title_buf: [0x100]u8 = [_]u8{0} ** 0x100;
@ -68,7 +68,7 @@ pub fn run(self: *Self, cpu: *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 = &cpu.bus.io; const io = &arm7tdmi.bus.io;
const key_code = event.key.keysym.sym; const key_code = event.key.keysym.sym;
switch (key_code) { switch (key_code) {
@ -86,7 +86,7 @@ pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void {
} }
}, },
SDL.SDL_KEYUP => { SDL.SDL_KEYUP => {
const io = &cpu.bus.io; const io = &arm7tdmi.bus.io;
const key_code = event.key.keysym.sym; const key_code = event.key.keysym.sym;
switch (key_code) { switch (key_code) {
@ -100,12 +100,12 @@ pub fn run(self: *Self, cpu: *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(cpu.bus.apu.stream)) / (2 * @sizeOf(u16))}), SDL.SDLK_i => log.err("Sample Count: {}", .{@intCast(u32, SDL.SDL_AudioStreamAvailable(arm7tdmi.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}", .{cpu.r[15]}); log.info("PC: 0x{X:0>8}", .{arm7tdmi.r[15]});
log.info("LR: 0x{X:0>8}", .{cpu.r[14]}); log.info("LR: 0x{X:0>8}", .{arm7tdmi.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();
@ -119,7 +119,7 @@ pub fn run(self: *Self, cpu: *Arm7tdmi, scheduler: *Scheduler) !void {
} }
// Emulator has an internal Double Buffer // Emulator has an internal Double Buffer
const framebuf = cpu.bus.ppu.framebuf.get(.Renderer); const framebuf = arm7tdmi.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);
@ -136,13 +136,12 @@ 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,13 +168,12 @@ const Audio = struct {
}; };
} }
fn deinit(self: *This) void { fn deinit(this: This) void {
SDL.SDL_CloseAudioDevice(self.device); SDL.SDL_CloseAudioDevice(this.device);
self.* = undefined;
} }
pub fn play(self: *This) void { pub fn play(this: *This) void {
SDL.SDL_PauseAudioDevice(self.device, 0); SDL.SDL_PauseAudioDevice(this.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,29 +49,32 @@ io: Io,
cpu: ?*Arm7tdmi, cpu: ?*Arm7tdmi,
sched: *Scheduler, sched: *Scheduler,
pub fn init(self: *Self, allocator: Allocator, sched: *Scheduler, cpu: *Arm7tdmi, paths: FilePaths) !void { pub fn init(alloc: Allocator, sched: *Scheduler, paths: FilePaths) !Self {
self.* = .{ return Self{
.pak = try GamePak.init(allocator, paths.rom, paths.save), .pak = try GamePak.init(alloc, paths.rom, paths.save),
.bios = try Bios.init(allocator, paths.bios), .bios = try Bios.init(alloc, paths.bios),
.ppu = try Ppu.init(allocator, sched), .ppu = try Ppu.init(alloc, sched),
.apu = Apu.init(sched), .apu = Apu.init(sched),
.iwram = try Iwram.init(allocator), .iwram = try Iwram.init(alloc),
.ewram = try Ewram.init(allocator), .ewram = try Ewram.init(alloc),
.dma = createDmaTuple(), .dma = createDmaTuple(),
.tim = createTimerTuple(sched), .tim = createTimerTuple(sched),
.io = Io.init(), .io = Io.init(),
.cpu = cpu, .cpu = null,
.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(self: *This, ch1: *Self) void { pub fn tick(this: *This, ch1: *Self) void {
if (self.timer != 0) self.timer -= 1; if (this.timer != 0) this.timer -= 1;
if (self.timer == 0) { if (this.timer == 0) {
const period = ch1.sweep.period.read(); const period = ch1.sweep.period.read();
self.timer = if (period == 0) 8 else period; this.timer = if (period == 0) 8 else period;
if (!self.calc_performed) self.calc_performed = true; if (!this.calc_performed) this.calc_performed = true;
if (self.enabled and period != 0) { if (this.enabled and period != 0) {
const new_freq = self.calcFrequency(ch1); const new_freq = this.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));
self.shadow = @truncate(u11, new_freq); this.shadow = @truncate(u11, new_freq);
_ = self.calcFrequency(ch1); _ = this.calcFrequency(ch1);
} }
} }
} }
} }
fn calcFrequency(self: *This, ch1: *Self) u12 { fn calcFrequency(this: *This, ch1: *Self) u12 {
const shadow = @as(u12, self.shadow); const shadow = @as(u12, this.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,28 +8,27 @@ pub const size = 0x4000;
const Self = @This(); const Self = @This();
buf: ?[]u8, buf: ?[]u8,
allocator: Allocator, alloc: Allocator,
addr_latch: u32, addr_latch: u32,
pub fn init(allocator: Allocator, maybe_path: ?[]const u8) !Self { pub fn init(alloc: Allocator, maybe_path: ?[]const u8) !Self {
const buf: ?[]u8 = if (maybe_path) |path| blk: { const buf: ?[]u8 = if (maybe_path) |path| blk: {
const file = try std.fs.cwd().openFile(path, .{}); const file = try std.fs.cwd().openFile(path, .{});
defer file.close(); defer file.close();
break :blk try file.readToEndAlloc(allocator, try file.getEndPos()); break :blk try file.readToEndAlloc(alloc, try file.getEndPos());
} else null; } else null;
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
.addr_latch = 0, .addr_latch = 0,
}; };
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: Self) void {
if (self.buf) |buf| self.allocator.free(buf); if (self.buf) |buf| self.alloc.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,21 +5,20 @@ const ewram_size = 0x40000;
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
pub fn init(allocator: Allocator) !Self { pub fn init(alloc: Allocator) !Self {
const buf = try allocator.alloc(u8, ewram_size); const buf = try alloc.alloc(u8, ewram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
}; };
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: Self) void {
self.allocator.free(self.buf); self.alloc.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,
allocator: Allocator, alloc: Allocator,
backup: Backup, backup: Backup,
pub fn init(allocator: Allocator, rom_path: []const u8, save_path: ?[]const u8) !Self { pub fn init(alloc: 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(allocator, try file.getEndPos()); const file_buf = try file.readToEndAlloc(alloc, 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,
.allocator = allocator, .alloc = alloc,
.title = title, .title = title,
.backup = try Backup.init(allocator, kind, title, save_path), .backup = try Backup.init(alloc, kind, title, save_path),
}; };
pak.parseHeader(); pak.parseHeader();
@ -58,10 +58,9 @@ 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,21 +5,20 @@ const iwram_size = 0x8000;
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
pub fn init(allocator: Allocator) !Self { pub fn init(alloc: Allocator) !Self {
const buf = try allocator.alloc(u8, iwram_size); const buf = try alloc.alloc(u8, iwram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
}; };
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: Self) void {
self.allocator.free(self.buf); self.alloc.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

@ -17,7 +17,7 @@ pub const Backup = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
kind: Kind, kind: Kind,
title: [12]u8, title: [12]u8,
@ -49,7 +49,7 @@ pub const Backup = struct {
var backup = Self{ var backup = Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = allocator,
.kind = kind, .kind = kind,
.title = title, .title = title,
.save_path = path, .save_path = path,
@ -74,10 +74,9 @@ 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(self.allocator, path) catch |e| log.err("Failed to write save: {}", .{e}); if (self.save_path) |path| self.writeSaveToDisk(self.alloc, path) catch |e| log.err("Failed to write save: {}", .{e});
self.allocator.free(self.buf); self.alloc.free(self.buf);
self.* = undefined;
} }
fn loadSaveFromDisk(self: *Self, allocator: Allocator, path: []const u8) !void { fn loadSaveFromDisk(self: *Self, allocator: Allocator, path: []const u8) !void {
@ -310,7 +309,7 @@ const Eeprom = struct {
writer: Writer, writer: Writer,
reader: Reader, reader: Reader,
allocator: Allocator, alloc: Allocator,
const Kind = enum { const Kind = enum {
Unknown, Unknown,
@ -326,14 +325,14 @@ const Eeprom = struct {
RequestEnd, RequestEnd,
}; };
fn init(allocator: Allocator) Self { fn init(alloc: 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,
.allocator = allocator, .alloc = alloc,
}; };
} }
@ -361,7 +360,7 @@ const Eeprom = struct {
else => unreachable, else => unreachable,
}; };
buf.* = self.allocator.alloc(u8, len) catch |e| { buf.* = self.alloc.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

@ -251,7 +251,7 @@ pub const Arm7tdmi = struct {
logger: ?Logger, logger: ?Logger,
pub fn init(sched: *Scheduler, bus: *Bus, log_file: ?std.fs.File) Self { pub fn init(sched: *Scheduler, bus: *Bus) Self {
return Self{ return Self{
.r = [_]u32{0x00} ** 16, .r = [_]u32{0x00} ** 16,
.pipe = Pipline.init(), .pipe = Pipline.init(),
@ -262,10 +262,14 @@ 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 = if (log_file) |file| Logger.init(file) else null, .logger = 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,25 +41,28 @@ pub const Ppu = struct {
oam: Oam, oam: Oam,
sched: *Scheduler, sched: *Scheduler,
framebuf: FrameBuffer, framebuf: FrameBuffer,
allocator: Allocator, alloc: Allocator,
scanline_sprites: *[128]?Sprite, scanline_sprites: [128]?Sprite,
scanline: Scanline, scanline: Scanline,
pub fn init(allocator: Allocator, sched: *Scheduler) !Self { pub fn init(alloc: Allocator, sched: *Scheduler) !Self {
// Queue first Hblank // Queue first Hblank
sched.push(.Draw, 240 * 4); sched.push(.Draw, 240 * 4);
const sprites = try allocator.create([128]?Sprite); const framebufs = try alloc.alloc(u8, (framebuf_pitch * height) * 2);
sprites.* = [_]?Sprite{null} ** 128; std.mem.set(u8, framebufs, 0);
const scanline_buf = try alloc.alloc(?u16, width * 2);
std.mem.set(?u16, scanline_buf, null);
return Self{ return Self{
.vram = try Vram.init(allocator), .vram = try Vram.init(alloc),
.palette = try Palette.init(allocator), .palette = try Palette.init(alloc),
.oam = try Oam.init(allocator), .oam = try Oam.init(alloc),
.sched = sched, .sched = sched,
.framebuf = try FrameBuffer.init(allocator), .framebuf = FrameBuffer.init(framebufs),
.allocator = allocator, .alloc = alloc,
// Registers // Registers
.win = Window.init(), .win = Window.init(),
@ -72,19 +75,17 @@ pub const Ppu = struct {
.bldalpha = .{ .raw = 0x0000 }, .bldalpha = .{ .raw = 0x0000 },
.bldy = .{ .raw = 0x0000 }, .bldy = .{ .raw = 0x0000 },
.scanline = try Scanline.init(allocator), .scanline = Scanline.init(scanline_buf),
.scanline_sprites = sprites, .scanline_sprites = [_]?Sprite{null} ** 128,
}; };
} }
pub fn deinit(self: *Self) void { pub fn deinit(self: Self) void {
self.allocator.destroy(self.scanline_sprites); self.framebuf.deinit(self.alloc);
self.framebuf.deinit(); self.scanline.deinit(self.alloc);
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 {
@ -398,7 +399,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);
@ -425,7 +426,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);
@ -451,7 +452,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);
@ -628,21 +629,20 @@ const Palette = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
fn init(allocator: Allocator) !Self { fn init(alloc: Allocator) !Self {
const buf = try allocator.alloc(u8, palram_size); const buf = try alloc.alloc(u8, palram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
}; };
} }
fn deinit(self: *Self) void { fn deinit(self: Self) void {
self.allocator.free(self.buf); self.alloc.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,21 +677,20 @@ const Vram = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
fn init(allocator: Allocator) !Self { fn init(alloc: Allocator) !Self {
const buf = try allocator.alloc(u8, vram_size); const buf = try alloc.alloc(u8, vram_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
}; };
} }
fn deinit(self: *Self) void { fn deinit(self: Self) void {
self.allocator.free(self.buf); self.alloc.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 {
@ -738,21 +737,20 @@ const Oam = struct {
const Self = @This(); const Self = @This();
buf: []u8, buf: []u8,
allocator: Allocator, alloc: Allocator,
fn init(allocator: Allocator) !Self { fn init(alloc: Allocator) !Self {
const buf = try allocator.alloc(u8, oam_size); const buf = try alloc.alloc(u8, oam_size);
std.mem.set(u8, buf, 0); std.mem.set(u8, buf, 0);
return Self{ return Self{
.buf = buf, .buf = buf,
.allocator = allocator, .alloc = alloc,
}; };
} }
fn deinit(self: *Self) void { fn deinit(self: Self) void {
self.allocator.free(self.buf); self.alloc.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 {
@ -1215,38 +1213,35 @@ fn copyToSpriteBuffer(bldcnt: io.BldCnt, scanline: *Scanline, x: u9, bgr555: u16
const Scanline = struct { const Scanline = struct {
const Self = @This(); const Self = @This();
layers: [2][]?u16, buf: [2][]?u16,
buf: []?u16, original: []?u16,
allocator: Allocator, fn init(buf: []?u16) Self {
std.debug.assert(buf.len == width * 2);
fn init(allocator: Allocator) !Self { const top_slice = buf[0..][0..width];
const buf = try allocator.alloc(?u16, width * 2); // Top & Bottom Scanline const btm_slice = buf[width..][0..width];
std.mem.set(?u16, buf, null);
return .{ return .{
// Top & Bototm Layers .buf = [_][]?u16{ top_slice, btm_slice },
.layers = [_][]?u16{ buf[0..][0..width], buf[width..][0..width] }, .original = buf,
.buf = buf,
.allocator = allocator,
}; };
} }
fn reset(self: *Self) void { fn reset(self: *Self) void {
std.mem.set(?u16, self.buf, null); std.mem.set(?u16, self.original, null);
} }
fn deinit(self: *Self) void { fn deinit(self: Self, alloc: Allocator) void {
self.allocator.free(self.buf); alloc.free(self.original);
self.* = undefined;
} }
fn top(self: *Self) []?u16 { fn top(self: *Self) []?u16 {
return self.layers[0]; return self.buf[0];
} }
fn btm(self: *Self) []?u16 { fn btm(self: *Self) []?u16 {
return self.layers[1]; return self.buf[1];
} }
}; };
@ -1254,36 +1249,31 @@ const Scanline = struct {
const FrameBuffer = struct { const FrameBuffer = struct {
const Self = @This(); const Self = @This();
layers: [2][]u8, buf: [2][]u8,
buf: []u8, original: []u8,
current: u1, current: u1,
allocator: Allocator,
// TODO: Rename // TODO: Rename
const Device = enum { const Device = enum {
Emulator, Emulator,
Renderer, Renderer,
}; };
pub fn init(allocator: Allocator) !Self { pub fn init(bufs: []u8) Self {
const framebuf_len = framebuf_pitch * height; std.debug.assert(bufs.len == framebuf_pitch * height * 2);
const buf = try allocator.alloc(u8, framebuf_len * 2);
std.mem.set(u8, buf, 0); const front = bufs[0 .. framebuf_pitch * height];
const back = bufs[framebuf_pitch * height ..];
return .{ return .{
// Front and Back Framebuffers .buf = [2][]u8{ front, back },
.layers = [_][]u8{ buf[0..][0..framebuf_len], buf[framebuf_len..][0..framebuf_len] }, .original = bufs,
.buf = buf,
.current = 0, .current = 0,
.allocator = allocator,
}; };
} }
fn deinit(self: *Self) void { fn deinit(self: Self, alloc: Allocator) void {
self.allocator.free(self.buf); alloc.free(self.original);
self.* = undefined;
} }
pub fn swap(self: *Self) void { pub fn swap(self: *Self) void {
@ -1291,6 +1281,6 @@ const FrameBuffer = struct {
} }
pub fn get(self: *Self, comptime dev: Device) []u8 { pub fn get(self: *Self, comptime dev: Device) []u8 {
return self.layers[if (dev == .Emulator) self.current else ~self.current]; return self.buf[if (dev == .Emulator) self.current else ~self.current];
} }
}; };

View File

@ -14,16 +14,15 @@ pub const Scheduler = struct {
tick: u64, tick: u64,
queue: PriorityQueue(Event, void, lessThan), queue: PriorityQueue(Event, void, lessThan),
pub fn init(allocator: Allocator) Self { pub fn init(alloc: Allocator) Self {
var sched = Self{ .tick = 0, .queue = PriorityQueue(Event, void, lessThan).init(allocator, {}) }; var sched = Self{ .tick = 0, .queue = PriorityQueue(Event, void, lessThan).init(alloc, {}) };
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

@ -130,45 +130,45 @@ pub const Logger = struct {
try self.buf.flush(); // FIXME: On panics, whatever is in the buffer isn't written to file try self.buf.flush(); // FIXME: On panics, whatever is in the buffer isn't written to file
} }
pub fn mgbaLog(self: *Self, cpu: *const Arm7tdmi, opcode: u32) void { pub fn mgbaLog(self: *Self, arm7tdmi: *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 (cpu.cpsr.t.read()) { if (arm7tdmi.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 = cpu.bus.dbgRead(u16, cpu.r[15]); const low = arm7tdmi.bus.dbgRead(u16, arm7tdmi.r[15]);
const bl_opcode = @as(u32, opcode) << 16 | low; const bl_opcode = @as(u32, opcode) << 16 | low;
self.print(arm_fmt, Self.fmtArgs(cpu, bl_opcode)) catch @panic("failed to write to log file"); self.print(arm_fmt, Self.fmtArgs(arm7tdmi, bl_opcode)) catch @panic("failed to write to log file");
} else { } else {
self.print(thumb_fmt, Self.fmtArgs(cpu, opcode)) catch @panic("failed to write to log file"); self.print(thumb_fmt, Self.fmtArgs(arm7tdmi, opcode)) catch @panic("failed to write to log file");
} }
} else { } else {
self.print(arm_fmt, Self.fmtArgs(cpu, opcode)) catch @panic("failed to write to log file"); self.print(arm_fmt, Self.fmtArgs(arm7tdmi, opcode)) catch @panic("failed to write to log file");
} }
} }
fn fmtArgs(cpu: *const Arm7tdmi, opcode: u32) FmtArgTuple { fn fmtArgs(arm7tdmi: *const Arm7tdmi, opcode: u32) FmtArgTuple {
return .{ return .{
cpu.r[0], arm7tdmi.r[0],
cpu.r[1], arm7tdmi.r[1],
cpu.r[2], arm7tdmi.r[2],
cpu.r[3], arm7tdmi.r[3],
cpu.r[4], arm7tdmi.r[4],
cpu.r[5], arm7tdmi.r[5],
cpu.r[6], arm7tdmi.r[6],
cpu.r[7], arm7tdmi.r[7],
cpu.r[8], arm7tdmi.r[8],
cpu.r[9], arm7tdmi.r[9],
cpu.r[10], arm7tdmi.r[10],
cpu.r[11], arm7tdmi.r[11],
cpu.r[12], arm7tdmi.r[12],
cpu.r[13], arm7tdmi.r[13],
cpu.r[14], arm7tdmi.r[14],
cpu.r[15] - if (cpu.cpsr.t.read()) 2 else @as(u32, 4), arm7tdmi.r[15] - if (arm7tdmi.cpsr.t.read()) 2 else @as(u32, 4),
cpu.cpsr.raw, arm7tdmi.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 cpu_logging = @import("core/emu.zig").cpu_logging; const arm7tdmi_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,25 +40,27 @@ 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: Bus = undefined; var bus = try Bus.init(allocator, &scheduler, paths);
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(&cpu, &scheduler); try gui.run(&arm7tdmi, &scheduler);
} }
fn getSavePath(allocator: Allocator) !?[]const u8 { fn getSavePath(allocator: Allocator) !?[]const u8 {