const std = @import("std"); const common = @import("../common.zig"); const Mirroring = common.Mirroring; // Mapper 66 (GxROM / GNROM) - 32KB PRG bank in bits 4-5, 8KB CHR bank in bits 0-1 pub const Gxrom = @This(); prg_bank: u8 = 0, chr_bank: u8 = 0, mirroring_mode: Mirroring, pub fn init(initial_mirroring: Mirroring) Gxrom { return .{ .mirroring_mode = initial_mirroring }; } pub fn cpuRead(self: *const Gxrom, address: u16, prg_rom: []const u8, prg_ram: []const u8) ?u8 { if (address >= 0x6000 and address <= 0x7fff) { const offset = address - 0x6000; if (offset < prg_ram.len) return prg_ram[offset]; return 0; } if (address >= 0x8000 and address <= 0xffff) { const total_32k_banks = @max(1, prg_rom.len / 0x8000); const bank = @as(usize, self.prg_bank) % total_32k_banks; const offset = (bank * 0x8000) + (address - 0x8000); if (offset < prg_rom.len) return prg_rom[offset]; return 0; } return null; } pub fn cpuWrite(self: *Gxrom, address: u16, value: u8, prg_ram: []u8) bool { if (address >= 0x6000 and address <= 0x7fff) { const offset = address - 0x6000; if (offset < prg_ram.len) { prg_ram[offset] = value; return true; } } if (address >= 0x8000 and address <= 0xffff) { self.prg_bank = (value >> 4) & 0x03; self.chr_bank = value & 0x03; return true; } return false; } pub fn ppuRead(self: *const Gxrom, address: u16, chr_rom: []const u8, chr_ram: []const u8, chr_is_ram: bool) ?u8 { if (address < 0x2000) { if (chr_is_ram) { if (address < chr_ram.len) return chr_ram[address]; } else if (chr_rom.len > 0) { const total_8k_banks = @max(1, chr_rom.len / 0x2000); const bank = @as(usize, self.chr_bank) % total_8k_banks; const offset = (bank * 0x2000) + address; if (offset < chr_rom.len) return chr_rom[offset]; } return 0; } return null; } pub fn ppuWrite(_: *Gxrom, address: u16, value: u8, chr_ram: []u8, chr_is_ram: bool) bool { if (address < 0x2000 and chr_is_ram) { if (address < chr_ram.len) { chr_ram[address] = value; return true; } } return false; } pub fn mirroring(self: *const Gxrom) Mirroring { return self.mirroring_mode; } pub fn irqLine(_: *const Gxrom) bool { return false; } pub fn notifyPpuAddress(_: *Gxrom, _: u16) void {} test "gxrom bank switching" { var gx = Gxrom.init(.horizontal); var ram: [0x2000]u8 = undefined; // Write 0x21: PRG bank 2, CHR bank 1 _ = gx.cpuWrite(0x8000, 0x21, &ram); try std.testing.expectEqual(@as(u8, 2), gx.prg_bank); try std.testing.expectEqual(@as(u8, 1), gx.chr_bank); }