Guest User

First approach (CHIP-8)

a guest
Aug 24th, 2023
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.35 KB | Source Code | 0 0
  1. void chip8_cycle(Chip8 *vm)
  2. {
  3.     vm->ticks++;
  4.     fetch_decode_and_execute(vm);
  5. }
  6.  
  7. int main(int argc, char *argv[])
  8. {
  9.     if (argc != 3) {
  10.         SDL_Log("Usage: %s <instr-per-sec> <rom-file>", argv[0]);
  11.         return 1;
  12.     }
  13.  
  14.     // Instructions per second executed by the VM (e.g. 540)
  15.     int ips = SDL_atoi(argv[1]);
  16.  
  17.     // Read ROM file ...
  18.  
  19.     Chip8 vm;
  20.     chip8_init(&vm);
  21.     chip8_load_rom(&vm, rom, rom_size);
  22.  
  23.     // If ips=540 clock_delay=1.85ms and timers_period=9
  24.     double clock_delay = 1000.0 / ips;
  25.     int timers_period = ips / 60;
  26.  
  27.     // Initialize graphics ...
  28.  
  29.     while (true) {
  30.         Uint64 start = SDL_GetPerformanceCounter();
  31.  
  32.        // Handle input event ...
  33.  
  34.         chip8_cycle(&vm);
  35.  
  36.         // If ips=540 decrease the timers every 9th instruction
  37.         if (vm.ticks % timers_period == 0)
  38.             chip8_decrease_timers(&vm);
  39.  
  40.         // If executed instruction == 0xDxyn (DRAW) update graphics
  41.         if ((vm.opcode & 0xF000) == 0xD000)
  42.             // Update graphics ...
  43.  
  44.         Uint64 end = SDL_GetPerformanceCounter();
  45.         double frequency = (double) SDL_GetPerformanceFrequency();
  46.         double elapsed_time = ((end - start) * 1000) / frequency;
  47.  
  48.         if (elapsed_time < clock_delay)
  49.             SDL_Delay((Uint32) (clock_delay - elapsed_time));
  50.     }
  51.  
  52.     return 0;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment