#include "chip8.h" #include "memory.h" #include "cpu.h" #include "input.h" #include "libft.h" #include #include #include #include int chip8_load_rom(t_chip8 *emu, const char *path) { FILE *fp = fopen(path, "rb"); if (fp == NULL) { return 1; } if (memory_load_rom(&emu->memory, fp) == 1) { fclose(fp); return (1); } fclose(fp); return (0); } void chip8_init(t_chip8 *emu) { ft_memset(emu->keyboard.keyboard, 0, sizeof(emu->keyboard.keyboard)); memory_init(&emu->memory); memory_load_fontset(&emu->memory); memset(emu->v, 0, sizeof(emu->v)); memset(emu->stack, 0, sizeof(emu->stack)); emu->i = 0; emu->pc = 0x200; emu->delay_timer = 0; emu->sound_timer = 0; emu->sp = 0; if (graphics_init(&emu->display) != 0) { printf("Failed to initialize graphics!\n"); exit(1); } if (graphics_display_ready() != 1) { printf("Graphics display failed to initialize properly!\n"); exit(1); } emu->running = 1; } void chip8_run(t_chip8 *emu) { uint32_t frame_start, frame_end, frame_duration; SDL_Event event; while (emu->running) { frame_start = SDL_GetTicks(); while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { emu->running = 0; break; } if (event.type == SDL_KEYDOWN || event.type == SDL_KEYUP) { input_update(&event, emu->keyboard.keyboard); } } if (emu->keyboard.waiting_for_key) { uint8_t key = get_pressed_key(emu); if (key != 0xFF) { emu->v[emu->keyboard.key_register] = key; emu->keyboard.waiting_for_key = 0; } } else { for (int i = 0; i < 10; i++) { uint16_t opcode = cpu_fetch(emu); t_instruction instruction = cpu_decode(opcode); cpu_execute(emu, instruction); } } if (emu->delay_timer > 0) emu->delay_timer--; if (emu->sound_timer > 0) emu->sound_timer--; graphics_render(emu); frame_end = SDL_GetTicks(); frame_duration = frame_end - frame_start; if (frame_duration < FRAME_TIME_MS) { SDL_Delay(FRAME_TIME_MS - frame_duration); } } }