media-raylib.c (2579B)
1 #include <assert.h> 2 #include <string.h> 3 4 #include <raylib.h> 5 6 #include "media.h" 7 8 #define PIXEL_RADIUS 16 9 10 #define SCREEN_WIDTH (64*PIXEL_RADIUS) 11 #define SCREEN_HEIGHT (32*PIXEL_RADIUS) 12 13 #define WINDOW_NAME "CHIP-8 emulator" 14 15 #define BG_COLOR BLACK 16 #define FG_COLOR WHITE 17 18 #define SOUND_DEV_FREQ 48000 19 #define SOUND_SAMPLES 4096 20 #define BUZZER_FREQ 440 21 #define BUZZER_VOL .05 22 23 int buzzer_state; 24 AudioStream audio; 25 26 /* 27 ┌───┬───┬───┬───┐ 28 │ 1 │ 2 │ 3 │ C │ 29 ├───┼───┼───┼───┤ 30 │ 4 │ 5 │ 6 │ D │ 31 ├───┼───┼───┼───┤ 32 │ 7 │ 8 │ 9 │ E │ 33 ├───┼───┼───┼───┤ 34 │ A │ 0 │ B │ F │ 35 └───┴───┴───┴───┘ 36 */ 37 38 KeyboardKey keys[16] = { 39 KEY_V, 40 KEY_THREE, KEY_FOUR, KEY_FIVE, 41 KEY_E, KEY_R, KEY_T, 42 KEY_D, KEY_F, KEY_G, 43 KEY_C, KEY_B, 44 KEY_SIX, KEY_Y, KEY_H, KEY_N 45 }; 46 47 static void update_audio(void){ 48 static bool should_buzz = 0; 49 static long sample_num = 0; 50 static char audio_buffer[SOUND_SAMPLES]; 51 52 if (buzzer_state) 53 should_buzz = 1; 54 55 if (IsAudioStreamProcessed(audio)){ 56 for(int i=0 ; i<SOUND_SAMPLES ; i++){ 57 if (should_buzz) 58 audio_buffer[i] = 59 ((sample_num++*256*BUZZER_FREQ/SOUND_DEV_FREQ) 60 %256)*BUZZER_VOL; 61 else 62 audio_buffer[i] = 0; 63 } 64 UpdateAudioStream(audio, audio_buffer, SOUND_SAMPLES); 65 should_buzz = 0; 66 } 67 } 68 69 int m_init(int argc, char **argv){ 70 (void)argc, (void)argv; 71 72 InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, WINDOW_NAME); 73 SetTargetFPS(60); 74 75 InitAudioDevice(); 76 audio = InitAudioStream(SOUND_DEV_FREQ, 8, 1); 77 78 PlayAudioStream(audio); 79 80 BeginDrawing(); 81 82 return 0; 83 } 84 85 void m_quit(void){ 86 EndDrawing(); 87 88 CloseAudioStream(audio); 89 CloseAudioDevice(); 90 91 CloseWindow(); 92 } 93 94 unsigned short get_input(unsigned short input){ 95 if (WindowShouldClose()) 96 return -1; 97 98 input = 0; 99 100 for(int i=0 ; i<16 ; i++){ 101 if(IsKeyDown(keys[i])) 102 input |= 1<<i; 103 } 104 105 return input; 106 } 107 unsigned short wait_input(unsigned short input){ 108 int new_input; 109 110 while((new_input = get_input(input)) == input) 111 frame(); 112 113 return new_input; 114 } 115 116 void clear_screen(void){ 117 ClearBackground(BG_COLOR); 118 } 119 120 void draw(int x, int y, int value){ 121 assert(0<=x && x<64); 122 assert(0<=y && y<32); 123 DrawRectangle(x*PIXEL_RADIUS, y*PIXEL_RADIUS, 124 PIXEL_RADIUS, PIXEL_RADIUS, 125 value ? FG_COLOR : BG_COLOR); 126 } 127 128 void frame(void){ 129 update_audio(); 130 131 EndDrawing(); 132 BeginDrawing(); 133 } 134 135 void set_buzzer_state(int state){ 136 buzzer_state = state; 137 } 138 139 void wait_tick(void){ 140 //XXX: not used anymore 141 }