gbemu/lib/emu.c

116 lines
2.0 KiB
C
Raw Normal View History

2025-01-30 14:30:19 -07:00
#include <emu.h>
#include <stdio.h>
#include <cart.h>
#include <cpu.h>
#include <ui.h>
2025-02-01 00:48:49 -07:00
#include <timer.h>
#include <dma.h>
#include <ppu.h>
2025-02-01 23:58:55 -07:00
#include <audio.h>
#ifdef _WIN32
#include <windows.h>
2025-02-08 13:08:34 -07:00
#else
#include <pthread.h>
#include <unistd.h>
#endif
2025-01-30 14:30:19 -07:00
static emu_context ctx;
emu_context *emu_get_context() {
return &ctx;
}
2025-02-08 13:08:34 -07:00
#ifdef _WIN32
DWORD WINAPI cpu_run(void *p) {
2025-02-08 13:08:34 -07:00
#else
void *cpu_run(void *p) {
#endif
2025-02-01 00:48:49 -07:00
ppu_init();
timer_init();
2025-01-30 14:30:19 -07:00
cpu_init();
2025-02-01 23:58:55 -07:00
audio_init();
2025-01-30 14:30:19 -07:00
ctx.running = true;
ctx.paused = false;
ctx.ticks = 0;
while (ctx.running) {
if (ctx.paused) {
delay(10);
continue;
}
if (!cpu_step()) {
printf("CPU stopped\n");
2025-02-08 13:08:34 -07:00
return 0;
2025-01-30 14:30:19 -07:00
}
}
return 0;
2025-01-30 16:27:27 -07:00
}
void sleep_ms(int milis) {
#ifdef _WIN32
Sleep(milis);
2025-02-08 13:08:34 -07:00
#else
usleep(milis * 1000);
#endif
}
int emu_run(int argc, char **argv) {
if (argc < 2) {
printf("Usage: gbemu <rom_file>\n");
return -1;
}
if(!cart_load(argv[1])) {
printf("Failed to load ROM file: %s\n", argv[1]);
return -2;
}
2025-02-08 13:08:34 -07:00
printf("Cart loaded..\n");
2025-02-17 21:22:13 -07:00
ctx.app_path = argv[0];
ui_init();
#ifdef _WIN32
HANDLE thread = CreateThread(NULL, 0, cpu_run, NULL, 0, NULL);
if(!thread) {
fprintf(stderr, "Unable to create main CPU thread!\n");
return -1;
}
2025-02-08 13:08:34 -07:00
#else
pthread_t t1;
if(pthread_create(&t1, NULL, cpu_run, NULL)) {
fprintf(stderr, "Unable to create main CPU thread!\n");
return -1;
}
#endif
2025-02-01 00:48:49 -07:00
u32 prev_frame = 0;
while(!ctx.die) {
sleep_ms(1);
ui_handle_events();
2025-02-19 10:20:45 -07:00
//if (prev_frame != ppu_get_context()->current_frame) {
2025-02-01 00:48:49 -07:00
ui_update();
2025-02-19 10:20:45 -07:00
//}
//prev_frame = ppu_get_context()->current_frame;
}
return 0;
}
2025-01-30 16:27:27 -07:00
void emu_cycles(int cpu_cycles) {
2025-02-01 00:48:49 -07:00
for (int i = 0; i < cpu_cycles; i++){
for(int n = 0; n < 4; n++){
ctx.ticks++;
timer_tick();
ppu_tick();
}
dma_tick();
}
2025-02-08 13:08:34 -07:00
}