save game support, and don't update the timer for now, it breaks things

This commit is contained in:
Matthew Laux 2022-08-04 15:03:58 -05:00
parent 03dab9524b
commit b2a6890524
4 changed files with 56 additions and 2 deletions

View File

@ -13,6 +13,7 @@ extern "C" {
#include "cpu.h"
#include "rom.h"
#include "lcd.h"
#include "mbc.h"
#include "instructions.h"
}
@ -163,6 +164,7 @@ int main(int argc, char *argv[])
dmg_new(&dmg, &cpu, &rom, &lcd);
cpu.dmg = &dmg;
mbc_load_ram(dmg.rom->mbc, "save.sav");
// cpu_bind_mem_model(&cpu, &dmg, dmg_read, dmg_write);
cpu.pc = 0x100;
@ -382,6 +384,7 @@ int main(int argc, char *argv[])
SDL_DestroyWindow(window);
SDL_Quit();
mbc_save_ram(dmg.rom->mbc, "save.sav");
rom_free(&rom);
return 0;

View File

@ -278,7 +278,7 @@ void dmg_step(void *_dmg)
// order of dependencies? i think cpu needs to step first then update
// all other hw
cpu_step(dmg->cpu);
timer_step(dmg);
// timer_step(dmg);
// each line takes 456 cycles
int cycle_diff = dmg->cpu->cycle_count - dmg->last_lcd_update;

View File

@ -57,6 +57,7 @@ struct mbc *mbc_new(int type)
return NULL;
}
mbc.type = type;
mbc.has_battery = type == 3;
return &mbc;
}
@ -76,3 +77,47 @@ int mbc_write(struct mbc *mbc, struct dmg *dmg, u16 addr, u8 data)
}
return mbc1_write(mbc, dmg, addr, data);
}
int mbc_save_ram(struct mbc *mbc, const char *filename)
{
FILE *fp;
if (!mbc->has_battery) {
return 0;
}
fp = fopen(filename, "w");
if (!fp) {
return 0;
}
if (fwrite(mbc->ram, 1, RAM_SIZE, fp) < RAM_SIZE) {
fclose(fp);
return 0;
}
fclose(fp);
return 1;
}
int mbc_load_ram(struct mbc *mbc, const char *filename)
{
FILE *fp;
if (!mbc->has_battery) {
return 0;
}
fp = fopen(filename, "r");
if (!fp) {
return 0;
}
if (fread(mbc->ram, 1, RAM_SIZE, fp) < RAM_SIZE) {
fclose(fp);
return 0;
}
fclose(fp);
return 1;
}

View File

@ -3,14 +3,17 @@
#include "types.h"
#define RAM_SIZE 0x8000
struct dmg;
struct mbc {
int type;
int has_battery;
int rom_bank;
int ram_bank;
int ram_enabled;
u8 ram[0x8000];
u8 ram[RAM_SIZE];
};
struct mbc *mbc_new(int type);
@ -19,5 +22,8 @@ struct mbc *mbc_new(int type);
int mbc_read(struct mbc *mbc, struct dmg *dmg, u16 addr, u8 *out_data);
// return 1 if handled, return 0 for base dmg behavior
int mbc_write(struct mbc *mbc, struct dmg *dmg, u16 addr, u8 data);
// 1 if success, 0 if error
int mbc_save_ram(struct mbc *mbc, const char *filename);
int mbc_load_ram(struct mbc *mbc, const char *filename);
#endif