nesemu/system.c

71 lines
1.7 KiB
C
Raw Normal View History

2024-01-06 14:27:09 -05:00
//
// Created by william on 12/23/23.
//
#include "include/cpu.h"
#include "include/system.h"
#include "memory.h"
#include <unistd.h>
#include <assert.h>
2024-05-06 20:23:44 -04:00
#include "cpu.h"
2024-01-06 14:27:09 -05:00
2024-05-06 20:23:44 -04:00
System current_sys;
2024-01-06 14:27:09 -05:00
2024-05-06 20:23:44 -04:00
void system_init() {
byte *registers_base_addr = mem_get_ptr(PPU_REGISTERS_BASE_ADDR);
byte *oam_dma_register = mem_get_ptr(PPU_REGISTER_OAM_DMA_ADDR);
2024-01-06 14:27:09 -05:00
2024-05-06 20:23:44 -04:00
cpu_init();
ppu_init(registers_base_addr, oam_dma_register);
current_sys.mapper = get_mapper(MAPPER_TYPE_SIMPLE);
current_sys.cycle_count = 7;
2024-01-06 14:27:09 -05:00
}
2024-05-06 20:23:44 -04:00
void system_start() {
address pc = mem_get_word(0xfffc);
cpu_get_state()->program_counter = pc;
2024-01-06 14:27:09 -05:00
}
2024-05-06 20:23:44 -04:00
void system_loop() {
2024-01-06 14:27:09 -05:00
assert(CPU_CLOCK_DIVISOR > PPU_CLOCK_DIVISOR);
unsigned int master_cycle_per_frame = MASTER_CLOCK / FRAME_RATE;
unsigned int cpu_cycle_per_frame = master_cycle_per_frame / CPU_CLOCK_DIVISOR;
unsigned int ppu_cycle_per_cpu_cycle = CPU_CLOCK_DIVISOR / PPU_CLOCK_DIVISOR;
long frame = 1;
long cpu_cycle_count = 0;
while (true) {
2024-05-04 22:16:12 -04:00
// log_info("Frame %d", frame);
2024-01-06 14:27:09 -05:00
2024-05-06 20:23:44 -04:00
while (current_sys.cycle_count < cpu_cycle_per_frame * frame) {
if (cpu_cycle_count == current_sys.cycle_count) {
cpu_cycle();
2024-01-06 14:27:09 -05:00
}
cpu_cycle_count++;
for (int ppu_c = 0; ppu_c < ppu_cycle_per_cpu_cycle; ppu_c++) {
2024-05-06 20:23:44 -04:00
ppu_cycle();
2024-01-06 14:27:09 -05:00
}
}
frame++;
usleep(17000); // Wait 16.6666ms
}
}
2024-05-06 20:23:44 -04:00
void system_uninit() {
}
unsigned int system_get_cycles() {
return current_sys.cycle_count;
}
void system_add_cycles(unsigned int cycles) {
current_sys.cycle_count += cycles;
}
Mapper *system_get_mapper() {
return &current_sys.mapper;
2024-01-06 14:27:09 -05:00
}