bytepusher.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /*
  2. * An implementation of the BytePusher VM.
  3. *
  4. * For example programs and more information about BytePusher, see
  5. * https://esolangs.org/wiki/BytePusher
  6. *
  7. * This code is public domain. Feel free to use it for any purpose!
  8. */
  9. #define SDL_MAIN_USE_CALLBACKS
  10. #include <SDL3/SDL.h>
  11. #include <SDL3/SDL_main.h>
  12. #include <stdarg.h>
  13. #define SCREEN_W 256
  14. #define SCREEN_H 256
  15. #define RAM_SIZE 0x1000000
  16. #define FRAMES_PER_SECOND 60
  17. #define SAMPLES_PER_FRAME 256
  18. #define NS_PER_SECOND (Uint64)SDL_NS_PER_SECOND
  19. #define MAX_AUDIO_LATENCY_FRAMES 5
  20. #define IO_KEYBOARD 0
  21. #define IO_PC 2
  22. #define IO_SCREEN_PAGE 5
  23. #define IO_AUDIO_BANK 6
  24. typedef struct {
  25. Uint8 ram[RAM_SIZE + 8];
  26. Uint64 last_tick;
  27. Uint64 tick_acc;
  28. SDL_Window* window;
  29. SDL_Renderer* renderer;
  30. SDL_Surface* screen;
  31. SDL_Texture* screentex;
  32. SDL_Texture* rendertarget; /* we need this render target for text to look good */
  33. SDL_AudioStream* audiostream;
  34. char status[SCREEN_W / 8];
  35. int status_ticks;
  36. Uint16 keystate;
  37. bool display_help;
  38. bool positional_input;
  39. } BytePusher;
  40. static const struct {
  41. const char *key;
  42. const char *value;
  43. } extended_metadata[] = {
  44. { SDL_PROP_APP_METADATA_URL_STRING, "https://examples.libsdl.org/SDL3/demo/04-bytepusher/" },
  45. { SDL_PROP_APP_METADATA_CREATOR_STRING, "SDL team" },
  46. { SDL_PROP_APP_METADATA_COPYRIGHT_STRING, "Placed in the public domain" },
  47. { SDL_PROP_APP_METADATA_TYPE_STRING, "game" }
  48. };
  49. static inline Uint16 read_u16(const BytePusher* vm, Uint32 addr) {
  50. const Uint8* ptr = &vm->ram[addr];
  51. return ((Uint16)ptr[0] << 8) | ((Uint16)ptr[1]);
  52. }
  53. static inline Uint32 read_u24(const BytePusher* vm, Uint32 addr) {
  54. const Uint8* ptr = &vm->ram[addr];
  55. return ((Uint32)ptr[0] << 16) | ((Uint32)ptr[1] << 8) | ((Uint32)ptr[2]);
  56. }
  57. static void set_status(BytePusher* vm, const char* fmt, ...) {
  58. va_list args;
  59. va_start(args, fmt);
  60. SDL_vsnprintf(vm->status, sizeof(vm->status), fmt, args);
  61. va_end(args);
  62. vm->status[sizeof(vm->status) - 1] = 0;
  63. vm->status_ticks = FRAMES_PER_SECOND * 3;
  64. }
  65. static bool load(BytePusher* vm, SDL_IOStream* stream, bool closeio) {
  66. size_t bytes_read = 0;
  67. bool ok = true;
  68. SDL_memset(vm->ram, 0, RAM_SIZE);
  69. if (!stream) {
  70. return false;
  71. }
  72. while (bytes_read < RAM_SIZE) {
  73. size_t read = SDL_ReadIO(stream, &vm->ram[bytes_read], RAM_SIZE - bytes_read);
  74. bytes_read += read;
  75. if (read == 0) {
  76. ok = SDL_GetIOStatus(stream) == SDL_IO_STATUS_EOF;
  77. break;
  78. }
  79. }
  80. if (closeio) {
  81. SDL_CloseIO(stream);
  82. }
  83. SDL_ClearAudioStream(vm->audiostream);
  84. vm->display_help = !ok;
  85. return ok;
  86. }
  87. static const char* filename(const char* path) {
  88. size_t i = SDL_strlen(path) + 1;
  89. while (i > 0) {
  90. i -= 1;
  91. if (path[i] == '/' || path[i] == '\\') {
  92. return path + i + 1;
  93. }
  94. }
  95. return path;
  96. }
  97. static bool load_file(BytePusher* vm, const char* path) {
  98. if (load(vm, SDL_IOFromFile(path, "rb"), true)) {
  99. set_status(vm, "loaded %s", filename(path));
  100. return true;
  101. } else {
  102. set_status(vm, "load failed: %s", filename(path));
  103. return false;
  104. }
  105. }
  106. static void print(BytePusher* vm, int x, int y, const char* str) {
  107. SDL_SetRenderDrawColor(vm->renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  108. SDL_RenderDebugText(vm->renderer, (float)(x + 1), (float)(y + 1), str);
  109. SDL_SetRenderDrawColor(vm->renderer, 0xff, 0xff, 0xff, SDL_ALPHA_OPAQUE);
  110. SDL_RenderDebugText(vm->renderer, (float)x, (float)y, str);
  111. SDL_SetRenderDrawColor(vm->renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
  112. }
  113. SDL_AppResult SDL_AppInit(void** appstate, int argc, char* argv[]) {
  114. BytePusher* vm;
  115. SDL_Palette* palette;
  116. SDL_Rect usable_bounds;
  117. SDL_AudioSpec audiospec = { SDL_AUDIO_S8, 1, SAMPLES_PER_FRAME * FRAMES_PER_SECOND };
  118. SDL_DisplayID primary_display;
  119. SDL_PropertiesID texprops;
  120. int zoom = 2;
  121. int i;
  122. Uint8 r, g, b;
  123. (void)argc;
  124. (void)argv;
  125. if (!SDL_SetAppMetadata("SDL 3 BytePusher", "1.0", "com.example.SDL3BytePusher")) {
  126. return SDL_APP_FAILURE;
  127. }
  128. for (i = 0; i < (int)SDL_arraysize(extended_metadata); i++) {
  129. if (!SDL_SetAppMetadataProperty(extended_metadata[i].key, extended_metadata[i].value)) {
  130. return SDL_APP_FAILURE;
  131. }
  132. }
  133. if (!SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO)) {
  134. return SDL_APP_FAILURE;
  135. }
  136. if (!(vm = (BytePusher *)SDL_calloc(1, sizeof(*vm)))) {
  137. return SDL_APP_FAILURE;
  138. }
  139. *(BytePusher**)appstate = vm;
  140. vm->display_help = true;
  141. primary_display = SDL_GetPrimaryDisplay();
  142. if (SDL_GetDisplayUsableBounds(primary_display, &usable_bounds)) {
  143. int zoom_w = (usable_bounds.w - usable_bounds.x) * 2 / 3 / SCREEN_W;
  144. int zoom_h = (usable_bounds.h - usable_bounds.y) * 2 / 3 / SCREEN_H;
  145. zoom = zoom_w < zoom_h ? zoom_w : zoom_h;
  146. if (zoom < 1) {
  147. zoom = 1;
  148. }
  149. }
  150. if (!SDL_CreateWindowAndRenderer("SDL 3 BytePusher",
  151. SCREEN_W * zoom, SCREEN_H * zoom, SDL_WINDOW_RESIZABLE,
  152. &vm->window, &vm->renderer
  153. )) {
  154. return SDL_APP_FAILURE;
  155. }
  156. if (!SDL_SetRenderLogicalPresentation(
  157. vm->renderer, SCREEN_W, SCREEN_H, SDL_LOGICAL_PRESENTATION_INTEGER_SCALE
  158. )) {
  159. return SDL_APP_FAILURE;
  160. }
  161. if (!(vm->screen = SDL_CreateSurfaceFrom(
  162. SCREEN_W, SCREEN_H, SDL_PIXELFORMAT_INDEX8, vm->ram, SCREEN_W
  163. ))) {
  164. return SDL_APP_FAILURE;
  165. }
  166. if (!(palette = SDL_CreateSurfacePalette(vm->screen))) {
  167. return SDL_APP_FAILURE;
  168. }
  169. i = 0;
  170. for (r = 0; r < 6; ++r) {
  171. for (g = 0; g < 6; ++g) {
  172. for (b = 0; b < 6; ++b, ++i) {
  173. SDL_Color color = { (Uint8)(r * 0x33), (Uint8)(g * 0x33), (Uint8)(b * 0x33), SDL_ALPHA_OPAQUE };
  174. palette->colors[i] = color;
  175. }
  176. }
  177. }
  178. for (; i < 256; ++i) {
  179. SDL_Color color = { 0, 0, 0, SDL_ALPHA_OPAQUE };
  180. palette->colors[i] = color;
  181. }
  182. texprops = SDL_CreateProperties();
  183. SDL_SetNumberProperty(texprops, SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, SDL_TEXTUREACCESS_STREAMING);
  184. SDL_SetNumberProperty(texprops, SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER, SCREEN_W);
  185. SDL_SetNumberProperty(texprops, SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER, SCREEN_H);
  186. vm->screentex = SDL_CreateTextureWithProperties(vm->renderer, texprops);
  187. SDL_SetNumberProperty(texprops, SDL_PROP_TEXTURE_CREATE_ACCESS_NUMBER, SDL_TEXTUREACCESS_TARGET);
  188. vm->rendertarget = SDL_CreateTextureWithProperties(vm->renderer, texprops);
  189. SDL_DestroyProperties(texprops);
  190. if (!vm->screentex || !vm->rendertarget) {
  191. return SDL_APP_FAILURE;
  192. }
  193. SDL_SetTextureScaleMode(vm->screentex, SDL_SCALEMODE_NEAREST);
  194. SDL_SetTextureScaleMode(vm->rendertarget, SDL_SCALEMODE_NEAREST);
  195. if (!(vm->audiostream = SDL_OpenAudioDeviceStream(
  196. SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audiospec, NULL, NULL
  197. ))) {
  198. return SDL_APP_FAILURE;
  199. }
  200. SDL_SetAudioStreamGain(vm->audiostream, 0.1f); /* examples are loud! */
  201. SDL_ResumeAudioStreamDevice(vm->audiostream);
  202. set_status(vm, "renderer: %s", SDL_GetRendererName(vm->renderer));
  203. vm->last_tick = SDL_GetTicksNS();
  204. vm->tick_acc = NS_PER_SECOND;
  205. return SDL_APP_CONTINUE;
  206. }
  207. SDL_AppResult SDL_AppIterate(void* appstate) {
  208. BytePusher* vm = (BytePusher*)appstate;
  209. Uint64 tick = SDL_GetTicksNS();
  210. Uint64 delta = tick - vm->last_tick;
  211. bool updated, skip_audio;
  212. vm->last_tick = tick;
  213. vm->tick_acc += delta * FRAMES_PER_SECOND;
  214. updated = vm->tick_acc >= NS_PER_SECOND;
  215. skip_audio = vm->tick_acc >= MAX_AUDIO_LATENCY_FRAMES * NS_PER_SECOND;
  216. if (skip_audio) {
  217. // don't let audio fall too far behind
  218. SDL_ClearAudioStream(vm->audiostream);
  219. }
  220. while (vm->tick_acc >= NS_PER_SECOND) {
  221. Uint32 pc;
  222. int i;
  223. vm->tick_acc -= NS_PER_SECOND;
  224. vm->ram[IO_KEYBOARD] = (Uint8)(vm->keystate >> 8);
  225. vm->ram[IO_KEYBOARD + 1] = (Uint8)(vm->keystate);
  226. pc = read_u24(vm, IO_PC);
  227. for (i = 0; i < SCREEN_W * SCREEN_H; ++i) {
  228. Uint32 src = read_u24(vm, pc);
  229. Uint32 dst = read_u24(vm, pc + 3);
  230. vm->ram[dst] = vm->ram[src];
  231. pc = read_u24(vm, pc + 6);
  232. }
  233. if (!skip_audio || vm->tick_acc < NS_PER_SECOND) {
  234. SDL_PutAudioStreamData(
  235. vm->audiostream,
  236. &vm->ram[(Uint32)read_u16(vm, IO_AUDIO_BANK) << 8],
  237. SAMPLES_PER_FRAME
  238. );
  239. }
  240. }
  241. if (updated) {
  242. SDL_Surface *tex;
  243. SDL_SetRenderTarget(vm->renderer, vm->rendertarget);
  244. if (!SDL_LockTextureToSurface(vm->screentex, NULL, &tex)) {
  245. return SDL_APP_FAILURE;
  246. }
  247. vm->screen->pixels = &vm->ram[(Uint32)vm->ram[IO_SCREEN_PAGE] << 16];
  248. SDL_BlitSurface(vm->screen, NULL, tex, NULL);
  249. SDL_UnlockTexture(vm->screentex);
  250. SDL_RenderTexture(vm->renderer, vm->screentex, NULL, NULL);
  251. if (vm->display_help) {
  252. print(vm, 4, 4, "Drop a BytePusher file in this");
  253. print(vm, 8, 12, "window to load and run it!");
  254. print(vm, 4, 28, "Press ENTER to switch between");
  255. print(vm, 8, 36, "positional and symbolic input.");
  256. }
  257. if (vm->status_ticks > 0) {
  258. vm->status_ticks -= 1;
  259. print(vm, 4, SCREEN_H - 12, vm->status);
  260. }
  261. }
  262. SDL_SetRenderTarget(vm->renderer, NULL);
  263. SDL_RenderClear(vm->renderer);
  264. SDL_RenderTexture(vm->renderer, vm->rendertarget, NULL, NULL);
  265. SDL_RenderPresent(vm->renderer);
  266. return SDL_APP_CONTINUE;
  267. }
  268. static Uint16 keycode_mask(SDL_Keycode key) {
  269. int index;
  270. if (key >= SDLK_0 && key <= SDLK_9) {
  271. index = key - SDLK_0;
  272. } else if (key >= SDLK_A && key <= SDLK_F) {
  273. index = key - SDLK_A + 10;
  274. } else {
  275. return 0;
  276. }
  277. return (Uint16)1 << index;
  278. }
  279. static Uint16 scancode_mask(SDL_Scancode scancode) {
  280. int index;
  281. switch (scancode) {
  282. case SDL_SCANCODE_1: index = 0x1; break;
  283. case SDL_SCANCODE_2: index = 0x2; break;
  284. case SDL_SCANCODE_3: index = 0x3; break;
  285. case SDL_SCANCODE_4: index = 0xc; break;
  286. case SDL_SCANCODE_Q: index = 0x4; break;
  287. case SDL_SCANCODE_W: index = 0x5; break;
  288. case SDL_SCANCODE_E: index = 0x6; break;
  289. case SDL_SCANCODE_R: index = 0xd; break;
  290. case SDL_SCANCODE_A: index = 0x7; break;
  291. case SDL_SCANCODE_S: index = 0x8; break;
  292. case SDL_SCANCODE_D: index = 0x9; break;
  293. case SDL_SCANCODE_F: index = 0xe; break;
  294. case SDL_SCANCODE_Z: index = 0xa; break;
  295. case SDL_SCANCODE_X: index = 0x0; break;
  296. case SDL_SCANCODE_C: index = 0xb; break;
  297. case SDL_SCANCODE_V: index = 0xf; break;
  298. default: return 0;
  299. }
  300. return (Uint16)1 << index;
  301. }
  302. SDL_AppResult SDL_AppEvent(void* appstate, SDL_Event* event) {
  303. BytePusher* vm = (BytePusher*)appstate;
  304. switch (event->type) {
  305. case SDL_EVENT_QUIT:
  306. return SDL_APP_SUCCESS;
  307. case SDL_EVENT_DROP_FILE:
  308. load_file(vm, event->drop.data);
  309. break;
  310. case SDL_EVENT_KEY_DOWN:
  311. #ifndef __EMSCRIPTEN__
  312. if (event->key.key == SDLK_ESCAPE) {
  313. return SDL_APP_SUCCESS;
  314. }
  315. #endif
  316. if (event->key.key == SDLK_RETURN) {
  317. vm->positional_input = !vm->positional_input;
  318. vm->keystate = 0;
  319. if (vm->positional_input) {
  320. set_status(vm, "switched to positional input");
  321. } else {
  322. set_status(vm, "switched to symbolic input");
  323. }
  324. }
  325. if (vm->positional_input) {
  326. vm->keystate |= scancode_mask(event->key.scancode);
  327. } else {
  328. vm->keystate |= keycode_mask(event->key.key);
  329. }
  330. break;
  331. case SDL_EVENT_KEY_UP:
  332. if (vm->positional_input) {
  333. vm->keystate &= ~scancode_mask(event->key.scancode);
  334. } else {
  335. vm->keystate &= ~keycode_mask(event->key.key);
  336. }
  337. break;
  338. }
  339. return SDL_APP_CONTINUE;
  340. }
  341. void SDL_AppQuit(void* appstate, SDL_AppResult result) {
  342. if (result == SDL_APP_FAILURE) {
  343. SDL_Log("Error: %s", SDL_GetError());
  344. }
  345. if (appstate) {
  346. BytePusher* vm = (BytePusher*)appstate;
  347. SDL_DestroyAudioStream(vm->audiostream);
  348. SDL_DestroyTexture(vm->rendertarget);
  349. SDL_DestroyTexture(vm->screentex);
  350. SDL_DestroySurface(vm->screen);
  351. SDL_DestroyRenderer(vm->renderer);
  352. SDL_DestroyWindow(vm->window);
  353. SDL_free(vm);
  354. }
  355. }