diff --git a/roms/nestest.nes b/roms/nestest.nes new file mode 100644 index 0000000..fc2a88c Binary files /dev/null and b/roms/nestest.nes differ diff --git a/src/bus.rs b/src/bus.rs index 6d7fa20..10a793a 100644 --- a/src/bus.rs +++ b/src/bus.rs @@ -2,10 +2,12 @@ use std::cell::RefCell; use std::rc::{Rc, Weak}; use crate::cpu::CPU; +use crate::cartridge::Cartridge; pub struct Bus { cpu: Weak>, + cartridge: Cartridge, ram: Vec } @@ -17,6 +19,7 @@ impl Bus Bus { cpu: Weak::new(), + cartridge: Cartridge::new("roms/nestest.nes"), ram: vec![0; 0x800] } } @@ -38,6 +41,12 @@ impl Bus pub fn read_cpu(&self, addr: u16) -> u8 { - self.ram[addr as usize] + match addr + { + 0..=0x1FFF => self.ram[(addr & 0x7FF) as usize], + 0x8000..=0xFFFF => self.cartridge.read_prg(addr & 0x7FFF), + + _ => panic!("Tried to access invalid memory address {}", addr) + } } } \ No newline at end of file diff --git a/src/cartridge.rs b/src/cartridge.rs new file mode 100644 index 0000000..e3cb62d --- /dev/null +++ b/src/cartridge.rs @@ -0,0 +1,54 @@ +use std::fs; + +struct Header +{ + prg_blocks: u8, + chr_blocks: u8 +} + +pub struct Cartridge +{ + header: Header, + + prg: Vec, + chr: Vec +} + +impl Cartridge +{ + pub fn new(filepath: &str) -> Cartridge + { + let contents = fs::read(filepath).expect("Failed to load ROM"); + let iter = contents.iter(); + + let mut curr_pos: usize = 0; + + let header_data = &contents[curr_pos..curr_pos + 16]; + let header = Header { + prg_blocks: header_data[4], + chr_blocks: header_data[5] + }; + + // TODO: For now assume there is no trainer + curr_pos = 16; + let prg_data = &contents[curr_pos..(curr_pos + 0x4000 * header.prg_blocks as usize)]; + + curr_pos += 0x4000 * header.prg_blocks as usize; + let chr_data = &contents[curr_pos..(curr_pos + 0x2000 * header.chr_blocks as usize)]; + + Cartridge + { + header: header, + + prg: prg_data.to_vec(), + chr: chr_data.to_vec() + } + } + + // TODO: For now all memio is hardcoded to work with nestest.nes for testing + + pub fn read_prg(&self, addr: u16) -> u8 + { + self.prg[(addr & 0x3FFF) as usize] + } +} \ No newline at end of file diff --git a/src/cpu.rs b/src/cpu.rs index e6dfd3a..d3c1818 100644 --- a/src/cpu.rs +++ b/src/cpu.rs @@ -41,6 +41,9 @@ impl CPU self.x = 0; self.y = 0; self.sp = 0xFD; + + // TODO: This is just for the nestest.nes + self.pc = 0xC000; } pub fn execute(&mut self) @@ -51,7 +54,7 @@ impl CPU match (opcode) { - _ => panic!("Unimplemented opcode {}", opcode) + _ => panic!("Unimplemented opcode {:X}", opcode) } } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index f2fa933..442d5af 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ mod nes; mod bus; mod cpu; +mod cartridge; use nes::NES;