main_sdl.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. /**
  2. @file main_sdl.c
  3. This is an SDL2 implementation of the game front end. It can be used to
  4. compile a native executable or a transpiled JS browser version with
  5. emscripten.
  6. This frontend is not strictly minimal, it could be reduced a lot. If you want
  7. a learning example of frontend, look at another, simpler one, e.g. terminal.
  8. To compile with emscripten run:
  9. emcc ./main_sdl.c -s USE_SDL=2 -O3 --shell-file HTMLshell.html -o game.html
  10. by Miloslav Ciz (drummyfish), 2019
  11. Released under CC0 1.0 (https://creativecommons.org/publicdomain/zero/1.0/)
  12. plus a waiver of all other intellectual property. The goal of this work is to
  13. be and remain completely in the public domain forever, available for any use
  14. whatsoever.
  15. */
  16. #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) || defined(__NT__) || defined(__APPLE__)
  17. #define SFG_OS_IS_MALWARE 1
  18. #endif
  19. // #define SFG_START_LEVEL 1
  20. // #define SFG_QUICK_WIN 1
  21. // #define SFG_IMMORTAL 1
  22. // #define SFG_ALL_LEVELS 1
  23. // #define SFG_UNLOCK_DOOR 1
  24. // #define SFG_REVEAL_MAP 1
  25. // #define SFG_INFINITE_AMMO 1
  26. // #define SFG_TIME_MULTIPLIER 512
  27. // #define SFG_CPU_LOAD(percent) printf("CPU load: %d%\n",percent);
  28. // #define GAME_LQ
  29. #ifndef __EMSCRIPTEN__
  30. #ifndef GAME_LQ
  31. // higher quality
  32. #define SFG_FPS 60
  33. #define SFG_LOG(str) puts(str);
  34. #define SFG_SCREEN_RESOLUTION_X 700
  35. #define SFG_SCREEN_RESOLUTION_Y 512
  36. #define SFG_DITHERED_SHADOW 1
  37. #define SFG_DIMINISH_SPRITES 1
  38. #define SFG_HEADBOB_SHEAR (-1 * SFG_SCREEN_RESOLUTION_Y / 80)
  39. #define SFG_BACKGROUND_BLUR 1
  40. #else
  41. // lower quality
  42. #define SFG_FPS 35
  43. #define SFG_SCREEN_RESOLUTION_X 640
  44. #define SFG_SCREEN_RESOLUTION_Y 480
  45. #define SFG_RAYCASTING_SUBSAMPLE 2
  46. #define SFG_RESOLUTION_SCALEDOWN 2
  47. #define SFG_LOG(str) puts(str);
  48. #define SFG_DIMINISH_SPRITES 0
  49. #define SFG_DITHERED_SHADOW 0
  50. #define SFG_BACKGROUND_BLUR 0
  51. #define SFG_RAYCASTING_MAX_STEPS 18
  52. #define SFG_RAYCASTING_MAX_HITS 8
  53. #endif
  54. #else
  55. // emscripten
  56. #define SFG_FPS 35
  57. #define SFG_SCREEN_RESOLUTION_X 512
  58. #define SFG_SCREEN_RESOLUTION_Y 320
  59. #define SFG_CAN_EXIT 0
  60. #define SFG_RESOLUTION_SCALEDOWN 2
  61. #define SFG_DITHERED_SHADOW 1
  62. #define SFG_BACKGROUND_BLUR 0
  63. #define SFG_RAYCASTING_MAX_STEPS 18
  64. #define SFG_RAYCASTING_MAX_HITS 8
  65. #include <emscripten.h>
  66. #endif
  67. /*
  68. SDL is easier to play thanks to nice controls so make the player take full
  69. damage to make it a bit harder.
  70. */
  71. #define SFG_PLAYER_DAMAGE_MULTIPLIER 1024
  72. #define SDL_MUSIC_VOLUME 16
  73. #define SDL_ANALOG_DIVIDER 1024
  74. #if !SFG_OS_IS_MALWARE
  75. #include <signal.h>
  76. #endif
  77. #define SDL_MAIN_HANDLED 1
  78. #define SDL_DISABLE_IMMINTRIN_H 1
  79. #include <stdio.h>
  80. #include <unistd.h>
  81. #include <SDL2/SDL.h>
  82. #include "game.h"
  83. #include "sounds.h"
  84. const uint8_t *sdlKeyboardState;
  85. uint8_t webKeyboardState[SFG_KEY_COUNT];
  86. uint8_t sdlMouseButtonState = 0;
  87. int8_t sdlMouseWheelState = 0;
  88. SDL_GameController *sdlController;
  89. uint16_t sdlScreen[SFG_SCREEN_RESOLUTION_X * SFG_SCREEN_RESOLUTION_Y]; // RGB565
  90. SDL_Window *window;
  91. SDL_Renderer *renderer;
  92. SDL_Texture *texture;
  93. // now implement the Anarch API functions (SFG_*)
  94. void SFG_setPixel(uint16_t x, uint16_t y, uint8_t colorIndex)
  95. {
  96. sdlScreen[y * SFG_SCREEN_RESOLUTION_X + x] = paletteRGB565[colorIndex];
  97. }
  98. uint32_t SFG_getTimeMs(void)
  99. {
  100. return SDL_GetTicks();
  101. }
  102. void SFG_save(uint8_t data[SFG_SAVE_SIZE])
  103. {
  104. FILE *f = fopen(SFG_SAVE_FILE_PATH,"wb");
  105. puts("SDL: opening and writing save file");
  106. if (f == NULL)
  107. {
  108. puts("SDL: could not open the file!");
  109. return;
  110. }
  111. fwrite(data,1,SFG_SAVE_SIZE,f);
  112. fclose(f);
  113. }
  114. uint8_t SFG_load(uint8_t data[SFG_SAVE_SIZE])
  115. {
  116. #ifndef __EMSCRIPTEN__
  117. FILE *f = fopen(SFG_SAVE_FILE_PATH,"rb");
  118. puts("SDL: opening and reading save file");
  119. if (f == NULL)
  120. {
  121. puts("SDL: no save file to open");
  122. }
  123. else
  124. {
  125. fread(data,1,SFG_SAVE_SIZE,f);
  126. fclose(f);
  127. }
  128. return 1;
  129. #else
  130. // no saving for web version
  131. return 0;
  132. #endif
  133. }
  134. void SFG_sleepMs(uint16_t timeMs)
  135. {
  136. #ifndef __EMSCRIPTEN__
  137. usleep(timeMs * 1000);
  138. #endif
  139. }
  140. #ifdef __EMSCRIPTEN__
  141. void webButton(uint8_t key, uint8_t down) // HTML button pressed
  142. {
  143. webKeyboardState[key] = down;
  144. }
  145. #endif
  146. int8_t mouseMoved = 0; /* Whether the mouse has moved since program started,
  147. this is needed to fix an SDL limitation. */
  148. void SFG_getMouseOffset(int16_t *x, int16_t *y)
  149. {
  150. #ifndef __EMSCRIPTEN__
  151. if (mouseMoved)
  152. {
  153. int mX, mY;
  154. SDL_GetMouseState(&mX,&mY);
  155. *x = mX - SFG_SCREEN_RESOLUTION_X / 2;
  156. *y = mY - SFG_SCREEN_RESOLUTION_Y / 2;
  157. SDL_WarpMouseInWindow(window,
  158. SFG_SCREEN_RESOLUTION_X / 2, SFG_SCREEN_RESOLUTION_Y / 2);
  159. }
  160. if (sdlController != NULL)
  161. {
  162. *x +=
  163. (SDL_GameControllerGetAxis(sdlController,SDL_CONTROLLER_AXIS_RIGHTX) +
  164. SDL_GameControllerGetAxis(sdlController,SDL_CONTROLLER_AXIS_LEFTX)) /
  165. SDL_ANALOG_DIVIDER;
  166. *y +=
  167. (SDL_GameControllerGetAxis(sdlController,SDL_CONTROLLER_AXIS_RIGHTY) +
  168. SDL_GameControllerGetAxis(sdlController,SDL_CONTROLLER_AXIS_LEFTY)) /
  169. SDL_ANALOG_DIVIDER;
  170. }
  171. #endif
  172. }
  173. void SFG_processEvent(uint8_t event, uint8_t data)
  174. {
  175. }
  176. int8_t SFG_keyPressed(uint8_t key)
  177. {
  178. if (webKeyboardState[key]) // this only takes effect in the web version
  179. return 1;
  180. #define k(x) sdlKeyboardState[SDL_SCANCODE_ ## x]
  181. #define b(x) ((sdlController != NULL) && \
  182. SDL_GameControllerGetButton(sdlController,SDL_CONTROLLER_BUTTON_ ## x))
  183. switch (key)
  184. {
  185. case SFG_KEY_UP: return k(UP) || k(W) || k(KP_8) || b(DPAD_UP); break;
  186. case SFG_KEY_RIGHT:
  187. return k(RIGHT) || k(E) || k(KP_6) || b(DPAD_RIGHT); break;
  188. case SFG_KEY_DOWN:
  189. return k(DOWN) || k(S) || k(KP_5) || k(KP_2) || b(DPAD_DOWN); break;
  190. case SFG_KEY_LEFT: return k(LEFT) || k(Q) || k(KP_4) || b(DPAD_LEFT); break;
  191. case SFG_KEY_A: return k(J) || k(RETURN) || k(LCTRL) || k(RCTRL) || b(X) ||
  192. b(RIGHTSTICK) || (sdlMouseButtonState & SDL_BUTTON_LMASK); break;
  193. case SFG_KEY_B: return k(K) || k(LSHIFT) || b(B); break;
  194. case SFG_KEY_C: return k(L) || b(Y); break;
  195. case SFG_KEY_JUMP: return k(SPACE) || b(A); break;
  196. case SFG_KEY_STRAFE_LEFT: return k(A) || k(KP_7); break;
  197. case SFG_KEY_STRAFE_RIGHT: return k(D) || k(KP_9); break;
  198. case SFG_KEY_MAP: return k(TAB) || b(BACK); break;
  199. case SFG_KEY_CYCLE_WEAPON: return k(F) ||
  200. (sdlMouseButtonState & SDL_BUTTON_MMASK); break;
  201. case SFG_KEY_TOGGLE_FREELOOK: return b(LEFTSTICK) ||
  202. (sdlMouseButtonState & SDL_BUTTON_RMASK); break;
  203. case SFG_KEY_MENU: return k(ESCAPE) || b(START); break;
  204. case SFG_KEY_NEXT_WEAPON:
  205. if (k(P) || k(X) || b(RIGHTSHOULDER))
  206. return 1;
  207. #define checkMouse(cmp)\
  208. if (sdlMouseWheelState cmp 0) { sdlMouseWheelState = 0; return 1; }
  209. checkMouse(>)
  210. return 0;
  211. break;
  212. case SFG_KEY_PREVIOUS_WEAPON:
  213. if (k(O) || k(Y) || k(Z) || b(LEFTSHOULDER))
  214. return 1;
  215. checkMouse(<)
  216. #undef checkMouse
  217. return 0;
  218. break;
  219. default: return 0; break;
  220. }
  221. #undef k
  222. #undef b
  223. }
  224. int running;
  225. void mainLoopIteration(void)
  226. {
  227. SDL_Event event;
  228. #ifdef __EMSCRIPTEN__
  229. // hack, without it sound won't work because of shitty browser audio policies
  230. if (SFG_game.frame % 512 == 0)
  231. SDL_PauseAudio(0);
  232. #endif
  233. while (SDL_PollEvent(&event)) // also automatically updates sdlKeyboardState
  234. {
  235. if (event.type == SDL_MOUSEWHEEL)
  236. {
  237. if (event.wheel.y > 0) // scroll up
  238. sdlMouseWheelState = 1;
  239. else if (event.wheel.y < 0) // scroll down
  240. sdlMouseWheelState = -1;
  241. }
  242. else if (event.type == SDL_QUIT)
  243. running = 0;
  244. else if (event.type == SDL_MOUSEMOTION)
  245. mouseMoved = 1;
  246. }
  247. sdlMouseButtonState = SDL_GetMouseState(NULL,NULL);
  248. if (!SFG_mainLoopBody())
  249. running = 0;
  250. SDL_UpdateTexture(texture,NULL,sdlScreen,
  251. SFG_SCREEN_RESOLUTION_X * sizeof(uint16_t));
  252. SDL_RenderClear(renderer);
  253. SDL_RenderCopy(renderer,texture,NULL,NULL);
  254. SDL_RenderPresent(renderer);
  255. }
  256. #ifdef __EMSCRIPTEN__
  257. typedef void (*em_callback_func)(void);
  258. void emscripten_set_main_loop(
  259. em_callback_func func, int fps, int simulate_infinite_loop);
  260. #endif
  261. uint16_t audioBuff[SFG_SFX_SAMPLE_COUNT];
  262. uint16_t audioPos = 0; // audio position for the next audio buffer fill
  263. uint32_t audioUpdateFrame = 0; // game frame at which audio buffer fill happened
  264. static inline int16_t mixSamples(int16_t sample1, int16_t sample2)
  265. {
  266. return sample1 + sample2;
  267. }
  268. uint8_t musicOn = 0;
  269. // ^ this has to be init to 0 (not 1), else a few samples get played at start
  270. void audioFillCallback(void *userdata, uint8_t *s, int l)
  271. {
  272. uint16_t *s16 = (uint16_t *) s;
  273. for (int i = 0; i < l / 2; ++i)
  274. {
  275. s16[i] = musicOn ?
  276. mixSamples(audioBuff[audioPos], SDL_MUSIC_VOLUME *
  277. (SFG_getNextMusicSample() - SFG_musicTrackAverages[SFG_MusicState.track]))
  278. : audioBuff[audioPos];
  279. audioBuff[audioPos] = 0;
  280. audioPos = (audioPos < SFG_SFX_SAMPLE_COUNT - 1) ? (audioPos + 1) : 0;
  281. }
  282. audioUpdateFrame = SFG_game.frame;
  283. }
  284. void SFG_setMusic(uint8_t value)
  285. {
  286. switch (value)
  287. {
  288. case SFG_MUSIC_TURN_ON: musicOn = 1; break;
  289. case SFG_MUSIC_TURN_OFF: musicOn = 0; break;
  290. case SFG_MUSIC_NEXT: SFG_nextMusicTrack(); break;
  291. default: break;
  292. }
  293. }
  294. void SFG_playSound(uint8_t soundIndex, uint8_t volume)
  295. {
  296. uint16_t pos = (audioPos +
  297. ((SFG_game.frame - audioUpdateFrame) * SFG_MS_PER_FRAME * 8)) %
  298. SFG_SFX_SAMPLE_COUNT;
  299. uint16_t volumeScale = 1 << (volume / 37);
  300. for (int i = 0; i < SFG_SFX_SAMPLE_COUNT; ++i)
  301. {
  302. audioBuff[pos] = mixSamples(audioBuff[pos],
  303. (128 - SFG_GET_SFX_SAMPLE(soundIndex,i)) * volumeScale);
  304. pos = (pos < SFG_SFX_SAMPLE_COUNT - 1) ? (pos + 1) : 0;
  305. }
  306. }
  307. void handleSignal(int signal)
  308. {
  309. running = 0;
  310. }
  311. int main(int argc, char *argv[])
  312. {
  313. uint8_t argHelp = 0;
  314. uint8_t argForceWindow = 0;
  315. uint8_t argForceFullscreen = 0;
  316. #ifndef __EMSCRIPTEN__
  317. argForceFullscreen = 1;
  318. #endif
  319. for (uint8_t i = 0; i < SFG_KEY_COUNT; ++i)
  320. webKeyboardState[i] = 0;
  321. for (uint8_t i = 1; i < argc; ++i)
  322. {
  323. if (argv[i][0] == '-' && argv[i][1] == 'h' && argv[i][2] == 0)
  324. argHelp = 1;
  325. else if (argv[i][0] == '-' && argv[i][1] == 'w' && argv[i][2] == 0)
  326. argForceWindow = 1;
  327. else if (argv[i][0] == '-' && argv[i][1] == 'f' && argv[i][2] == 0)
  328. argForceFullscreen = 1;
  329. else
  330. puts("SDL: unknown argument");
  331. }
  332. if (argHelp)
  333. {
  334. puts("Anarch (SDL), version " SFG_VERSION_STRING "\n");
  335. puts("Anarch is a unique suckless FPS game. Collect weapons and items and destroy");
  336. puts("robot enemies in your way in order to get to the level finish. Some door are");
  337. puts("locked and require access cards. Good luck!\n");
  338. puts("created by Miloslav \"drummyfish\" Ciz, 2020, released under CC0 1.0 (public domain)\n");
  339. puts("CLI flags:\n");
  340. puts("-h print this help and exit");
  341. puts("-w force window");
  342. puts("-f force fullscreen\n");
  343. puts("controls:\n");
  344. puts("- arrows, numpad, [W] [S] [A] [D] [Q] [E]: movement");
  345. puts("- mouse: rotation, [LMB] shoot, [RMB] toggle free look");
  346. puts("- [SPACE]: jump");
  347. puts("- [J] [RETURN] [CTRL] [LMB]: game A button (shoot, confirm)");
  348. puts("- [K] [SHIFT]: game B button (cancel, strafe)");
  349. puts("- [L]: game C button (+ down = menu, + up = jump, ...)");
  350. puts("- [F]: cycle next/previous weapon");
  351. puts("- [O] [P] [X] [Y] [Z] [mouse wheel] [mouse middle]: change weapons");
  352. puts("- [TAB]: map");
  353. puts("- [ESCAPE]: menu");
  354. return 0;
  355. }
  356. SFG_init();
  357. puts("SDL: initializing SDL");
  358. SDL_Init(SDL_INIT_AUDIO | SDL_INIT_JOYSTICK);
  359. window =
  360. SDL_CreateWindow("Anarch", SDL_WINDOWPOS_UNDEFINED,
  361. SDL_WINDOWPOS_UNDEFINED, SFG_SCREEN_RESOLUTION_X, SFG_SCREEN_RESOLUTION_Y,
  362. SDL_WINDOW_SHOWN);
  363. renderer = SDL_CreateRenderer(window,-1,0);
  364. texture =
  365. SDL_CreateTexture(renderer,SDL_PIXELFORMAT_RGB565,SDL_TEXTUREACCESS_STATIC,
  366. SFG_SCREEN_RESOLUTION_X,SFG_SCREEN_RESOLUTION_Y);
  367. #if SFG_FULLSCREEN
  368. argForceFullscreen = 1;
  369. #endif
  370. if (!argForceWindow && argForceFullscreen)
  371. {
  372. puts("SDL: setting fullscreen");
  373. SDL_SetWindowFullscreen(window,SDL_WINDOW_FULLSCREEN_DESKTOP);
  374. }
  375. sdlKeyboardState = SDL_GetKeyboardState(NULL);
  376. sdlController = SDL_GameControllerOpen(0);
  377. #if !SFG_OS_IS_MALWARE
  378. signal(SIGINT,handleSignal);
  379. signal(SIGQUIT,handleSignal);
  380. signal(SIGTERM,handleSignal);
  381. #endif
  382. SDL_AudioSpec audioSpec;
  383. SDL_memset(&audioSpec, 0, sizeof(audioSpec));
  384. audioSpec.callback = audioFillCallback;
  385. audioSpec.freq = 8000;
  386. audioSpec.format = AUDIO_S16;
  387. audioSpec.channels = 1;
  388. #ifdef __EMSCRIPTEN__
  389. audioSpec.samples = 1024;
  390. #else
  391. audioSpec.samples = 256;
  392. #endif
  393. if (SDL_OpenAudio(&audioSpec,NULL) < 0)
  394. puts("SDL: could not initialize audio");
  395. for (int16_t i = 0; i < SFG_SFX_SAMPLE_COUNT; ++i)
  396. audioBuff[i] = 0;
  397. SDL_PauseAudio(0);
  398. running = 1;
  399. SDL_ShowCursor(0);
  400. SDL_PumpEvents();
  401. SDL_GameControllerUpdate();
  402. SDL_WarpMouseInWindow(window,
  403. SFG_SCREEN_RESOLUTION_X / 2, SFG_SCREEN_RESOLUTION_Y / 2);
  404. #ifdef __EMSCRIPTEN__
  405. emscripten_set_main_loop(mainLoopIteration,0,1);
  406. #else
  407. while (running)
  408. mainLoopIteration();
  409. #endif
  410. puts("SDL: freeing SDL");
  411. SDL_GameControllerClose(sdlController);
  412. SDL_PauseAudio(1);
  413. SDL_CloseAudio();
  414. SDL_DestroyTexture(texture);
  415. SDL_DestroyRenderer(renderer);
  416. SDL_DestroyWindow(window);
  417. puts("SDL: ending");
  418. return 0;
  419. }