Advertisement
Guest User

Second approach (CHIP-8)

a guest
Aug 24th, 2023
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.37 KB | Source Code | 0 0
  1. #define CLOCK_FREQUENCY 60  // 60Hz
  2. #define CLOCK_PERIOD 16.666f // Delay in milliseconds needed to achieve 60fps (1000/60=16.666)
  3.  
  4. void chip8_init(Chip8 *vm, int ips)
  5. {
  6.     // Initialize the VM ...
  7.  
  8.     // Instructions per frame. If ips=540 then ipf=9
  9.     vm->IPF = ips / CLOCK_FREQUENCY;
  10. }
  11.  
  12. void chip8_cycle(Chip8 *vm)
  13. {
  14.     // If ips=540 execute 9 instructions per cycle
  15.     for (int i = 0; i < vm->IPF; i++) {
  16.         fetch_decode_execute(vm);
  17.     }
  18.  
  19.     chip8_decrease_timers(vm);
  20. }
  21.  
  22. int main(int argc, char *argv[])
  23. {
  24.     if (argc != 3) {
  25.         SDL_Log("Usage: %s <instr-per-sec> <rom-file>", argv[0]);
  26.         return 1;
  27.     }
  28.  
  29.     // Instructions per second executed by the VM (e.g. 540)
  30.     int ips = SDL_atoi(argv[1]);
  31.  
  32.     // Read ROM file ...
  33.  
  34.     Chip8 vm;
  35.     chip8_init(&vm, ips);
  36.     chip8_load_rom(&vm, rom, rom_size);
  37.  
  38.     // Initialize graphics ...
  39.  
  40.     while (true) {
  41.         Uint64 start = SDL_GetPerformanceCounter();
  42.  
  43.         // Handle input event ...
  44.  
  45.         chip8_cycle(&vm);
  46.  
  47.         // Update graphics ...
  48.  
  49.         Uint64 end = SDL_GetPerformanceCounter();
  50.         double frequency = (double) SDL_GetPerformanceFrequency();
  51.         double elapsed_time = ((end - start) * 1000) / frequency;
  52.  
  53.         if (elapsed_time < CLOCK_PERIOD)
  54.             SDL_Delay((Uint32) (CLOCK_PERIOD - elapsed_time));
  55.     }
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement