diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-17 10:52:27 +0200 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2026-10-17 10:52:27 +0200 |
| commit | d3c95fce3f5c8b910d3dc04ed5d8c1673944baf0 (patch) | |
| tree | 61b36f4cf2c0c77a3ee3bc05a83384b695e58fb5 /src/game.c | |
| parent | f97bb735065392d639462e90d9abd1bb5f738c61 (diff) | |
Use `wasm2c` instead of WAMR
Instead of interpreting Wasm, compile it ahead of time to C and
run that instead:
- it is much faster (no interpreter overhead)
- it is easier to implement host functions, they are just C calls
This works well for us since we only ever load a single Wasm blob
(the PICO-8 runtime that `picow` is built with).
There was some fun figuring out how big-endian stuff works (WRT
memory layout), but otherwise it was pretty straight forward.
Note that traps are still not working, I need to figure that out
still...
Diffstat (limited to 'src/game.c')
| -rw-r--r-- | src/game.c | 562 |
1 files changed, 43 insertions, 519 deletions
@@ -1,338 +1,24 @@ -#include <math.h> - #include <SDL3/SDL_log.h> -#include <SDL3/SDL_timer.h> #include "game.h" -#include "input.h" -#include "sysroot.h" - -static void *wasm_malloc(unsigned int size) { return SDL_malloc((size_t)size); } - -static void *wasm_realloc(void *ptr, unsigned int size) { - return SDL_realloc(ptr, (size_t)size); -} - -static void wasm_free(void *ptr) { SDL_free(ptr); } - -static void *emrt_memory(wasm_exec_env_t exec, uint32_t offset, uint32_t size) { - wasm_module_inst_t instance = wasm_runtime_get_module_inst(exec); - if (!instance || !wasm_runtime_validate_app_addr(instance, offset, size)) { - return NULL; - } - - return wasm_runtime_addr_app_to_native(instance, offset); -} +#include "pico8.h" -#define emrt_write(m, t, v) \ - do { \ - uint8_t **emrt__m = (uint8_t **)(m); \ - t emrt__v = (v); \ - SDL_memcpy(*emrt__m, &emrt__v, sizeof(emrt__v)); \ - *emrt__m += sizeof(emrt__v); \ - } while (0) - -static void emrt_set_main_loop(wasm_exec_env_t exec, uint64_t *args) { - native_raw_get_arg(int32_t, func, args); - native_raw_get_arg(int32_t, fps, args); - native_raw_get_arg(int32_t, simulate_infinite_loop, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - SDL_LogDebug(0, "setting main loop function: %d", func); - game->mainfn = func; - - // Ignore the fps and simulate infinite loop parameters, they are always 0 - // for PICO-8 anyway. - (void)fps; - (void)simulate_infinite_loop; -} - -// PICO-8 engine is compiled with the Emscripten built-in SDL1.3 library, which -// has a different pixel format encoding than SDL3 which is used on the host. -// The pixel format used by the engine is: -#define EMRT_PIXELFORMAT_ABGR8888 0x86762004 - -static void emrt_set_video_mode(wasm_exec_env_t exec, uint64_t *args) { - native_raw_return_type(int32_t, args); - native_raw_get_arg(int32_t, w, args); - native_raw_get_arg(int32_t, h, args); - native_raw_get_arg(int32_t, bpp, args); - native_raw_get_arg(int32_t, flags, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - if (w != 128 || h != 128 || bpp != 32 || flags != 0) { - SDL_LogWarn(0, "invalid PICO-8 surface parameters"); - game->error.set = true; - native_raw_set_return(0); - return; - } - - // We need to allocate 60 bytes for the surface structure, 44 bytes for the - // pixel format, and `PW_FB_SIZE` bytes for the pixel data. - uint32_t surface; - uint8_t *memory; - { - uint32_t size = 60 + 44 + PW_FB_SIZE; - uint32_t margs[] = {size}; - if (!wasm_runtime_call_wasm(exec, game->malloc, 1, margs) || !margs[0]) { - SDL_LogWarn(0, "failed to allocate surface"); - game->error.set = true; - native_raw_set_return(0); - return; - } - - surface = margs[0]; - memory = emrt_memory(exec, surface, size); - if (!memory) { - SDL_LogWarn(0, "invalid surface allocation"); - game->error.set = true; - native_raw_set_return(0); - return; - } - } - - // surface - { - void *cursor = memory; - emrt_write(&cursor, int32_t, flags); - emrt_write(&cursor, uint32_t, surface + 60); - emrt_write(&cursor, int32_t, w); - emrt_write(&cursor, int32_t, h); - emrt_write(&cursor, int32_t, (w * bpp) / 8); - emrt_write(&cursor, uint32_t, surface + 60 + 44); - emrt_write(&cursor, uint32_t, 0); // userdata - emrt_write(&cursor, uint32_t, 0); // locked - emrt_write(&cursor, uint32_t, 0); // lock_data - emrt_write(&cursor, int32_t, 0); // clip_rect.x - emrt_write(&cursor, int32_t, 0); // clip_rect.y - emrt_write(&cursor, int32_t, w); // clip_rect.w - emrt_write(&cursor, int32_t, h); // clip_rect.h - emrt_write(&cursor, uint32_t, 0); // map - emrt_write(&cursor, uint32_t, 1); // refcount - }; - // pixel format - { - void *cursor = memory + 60; - emrt_write(&cursor, uint32_t, EMRT_PIXELFORMAT_ABGR8888); - emrt_write(&cursor, uint32_t, 0); // palette - emrt_write(&cursor, int8_t, (int8_t)bpp); - emrt_write(&cursor, int8_t, (int8_t)bpp / 8); - emrt_write(&cursor, uint16_t, 0); // padding - emrt_write(&cursor, uint32_t, 0x000000ff); // rmask - emrt_write(&cursor, uint32_t, 0x0000ff00); // gmask - emrt_write(&cursor, uint32_t, 0x00ff0000); // bmask - emrt_write(&cursor, uint32_t, 0xff000000); // amask - emrt_write(&cursor, uint8_t, 0); // rloss - emrt_write(&cursor, uint8_t, 0); // gloss - emrt_write(&cursor, uint8_t, 0); // bloss - emrt_write(&cursor, uint8_t, 0); // aloss - emrt_write(&cursor, uint8_t, 0); // rshift - emrt_write(&cursor, uint8_t, 8); // gshift - emrt_write(&cursor, uint8_t, 16); // bshift - emrt_write(&cursor, uint8_t, 24); // ashift - emrt_write(&cursor, int32_t, 1); // refcount - emrt_write(&cursor, uint32_t, 0); // next - } - // pixels - { - void *cursor = memory + 60 + 44; - SDL_memset(cursor, 0, PW_FB_SIZE); - } - - native_raw_set_return(surface); -} - -static void emrt_get_mouse_state(wasm_exec_env_t exec, uint64_t *args) { - native_raw_return_type(int32_t, args); - native_raw_get_arg(uint32_t, x, args); - native_raw_get_arg(uint32_t, y, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - struct pw_coordinates pos; - enum pw_mouse_button button = pw_input_mouse(game->input, &pos); - - if (x) { - uint8_t *memory = emrt_memory(exec, x, sizeof(int32_t)); - if (memory) { - emrt_write(&memory, int32_t, pos.x); - } - } - if (y) { - uint8_t *memory = emrt_memory(exec, y, sizeof(int32_t)); - if (memory) { - emrt_write(&memory, int32_t, pos.y); - } - } - - native_raw_set_return(button); -} - -static void emrt_lock_surface(wasm_exec_env_t exec, uint64_t *args) { - native_raw_return_type(int32_t, args); - native_raw_get_arg(uint32_t, surface, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - uint8_t *memory = emrt_memory(exec, surface, 60); - if (!memory) { - SDL_LogWarn(0, "invalid surface specified for locking"); - game->error.set = true; - native_raw_set_return(-1); - return; - } - - { - void *cursor = memory + 28; - emrt_write(&cursor, uint32_t, 1); // locked - }; - - native_raw_set_return(0); -} - -static void emrt_unlock_surface(wasm_exec_env_t exec, uint64_t *args) { - native_raw_get_arg(uint32_t, surface, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - uint8_t *memory = emrt_memory(exec, surface, 60); - if (!memory) { - SDL_LogWarn(0, "invalid surface specified for locking"); - game->error.set = true; - return; - } - - // Always clear the locked flag as unlocking should never fail. - { - void *cursor = memory + 28; - emrt_write(&cursor, uint32_t, 0); // locked - }; - - uint32_t pixels; - SDL_memcpy(&pixels, memory + 20, sizeof(pixels)); - - uint8_t *buffer = emrt_memory(exec, pixels, PW_FB_SIZE); - if (!buffer) { - SDL_LogWarn(0, "invalid surface pixel buffer"); - game->error.set = true; - return; - } - - if (!pw_fb_blit(game->fb, buffer)) { - SDL_LogWarn(0, "failed to blit surface to framebuffer: %s", SDL_GetError()); - game->error.set = true; - } -} - -static uint32_t truncated_ticks() { - return (uint32_t)(SDL_GetTicks() & 0xffffffff); -} - -static void emrt_get_ticks(wasm_exec_env_t exec, uint64_t *args) { - (void)exec; - native_raw_return_type(uint32_t, args); - native_raw_set_return(truncated_ticks()); -} - -static void emrt_get_error(wasm_exec_env_t exec, uint64_t *args) { - native_raw_return_type(uint32_t, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - uint32_t error = game->error.ptr; - if (!game->error.set) { - // Just point to the `\0` at the end of the error message, this avoids - // requiring a separate allocation for the cleared error. - error = game->error.ptr; - } - - native_raw_set_return(error); -} - -static void emrt_clear_error(wasm_exec_env_t exec, uint64_t *args) { - (void)args; - struct pw_game *game = wasm_runtime_get_user_data(exec); - game->error.set = false; -} - -#define EMRT_KEYDOWN 0x300 -#define EMRT_KEYUP 0x301 -#define EMRT_MOUSEMOTION 0x400 - -static void emrt_poll_event(wasm_exec_env_t exec, uint64_t *args) { - native_raw_return_type(int32_t, args); - native_raw_get_arg(uint32_t, event, args); - - struct pw_game *game = wasm_runtime_get_user_data(exec); - - bool remaining; - union pw_input_event input; - if (event) { - remaining = pw_input_poll(game->input, &input); - } else { - remaining = pw_input_poll(game->input, NULL); - goto exit; - } - - uint8_t *memory = emrt_memory(exec, event, 36); - if (!memory) { - SDL_LogWarn(0, "invalid event address for polling"); - game->error.set = true; - goto exit; - } - - if (remaining) { - void *cursor = memory; - - switch (input.type) { - case PW_INPUT_EVENT_KEY: - if (input.key.pressed) { - emrt_write(&cursor, uint32_t, EMRT_KEYDOWN); - } else { - emrt_write(&cursor, uint32_t, EMRT_KEYUP); - } - emrt_write(&cursor, uint32_t, 1); // windowID - emrt_write(&cursor, uint8_t, (uint8_t)input.key.pressed); - emrt_write(&cursor, uint8_t, (uint8_t)input.key.repeat); - emrt_write(&cursor, uint8_t, 0); // padding2 - emrt_write(&cursor, uint8_t, 0); // padding3 - emrt_write(&cursor, uint32_t, input.key.scancode); - emrt_write(&cursor, int32_t, input.key.keycode); - emrt_write(&cursor, uint16_t, (uint16_t)input.key.mod); - emrt_write(&cursor, uint16_t, 0); // keysym.(padding) - emrt_write(&cursor, uint32_t, 0); // keysym.unicode (deprecated) - break; - case PW_INPUT_EVENT_MOUSE: - emrt_write(&cursor, uint32_t, EMRT_MOUSEMOTION); - emrt_write(&cursor, uint32_t, truncated_ticks()); - emrt_write(&cursor, uint32_t, 1); // windowID - emrt_write(&cursor, uint32_t, 1); // which - emrt_write(&cursor, uint32_t, (uint32_t)input.mouse.button); - emrt_write(&cursor, int32_t, input.mouse.x); - emrt_write(&cursor, int32_t, input.mouse.y); - emrt_write(&cursor, int32_t, input.mouse.xrel); - emrt_write(&cursor, int32_t, input.mouse.yrel); - break; - }; - }; - -exit: - native_raw_set_return((int32_t)remaining); -} - -struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode) { +struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode, + size_t memory) { if (!renderer) { SDL_InvalidParamError("renderer"); return NULL; } - bool wasm_init = false; - struct pw_game *game = SDL_malloc(sizeof(*game)); + struct pw_game *game = SDL_calloc(1, sizeof(*game)); if (!game) { return NULL; } - SDL_zerop(game); + + game->env = pw_env_init(memory); + if (!game->env) { + goto error; + } game->fb = pw_fb_init(renderer, mode); if (!game->fb) { @@ -344,67 +30,19 @@ struct pw_game *pw_game_init(SDL_Renderer *renderer, enum pw_scale_mode mode) { goto error; } - struct RuntimeInitArgs init = { - .mem_alloc_type = Alloc_With_Allocator, - .mem_alloc_option.allocator.malloc_func = (void *)wasm_malloc, - .mem_alloc_option.allocator.realloc_func = (void *)wasm_realloc, - .mem_alloc_option.allocator.free_func = (void *)wasm_free, - }; - if (!wasm_runtime_full_init(&init)) { - SDL_SetError("unspecified error initializing WebAssembly runtime"); - goto error; - } - wasm_init = true; - - struct NativeSymbol env[] = { - {"_emscripten_set_main_loop", emrt_set_main_loop, "(iii)", NULL}, - {"_SDL_ClearError", emrt_clear_error, "()", NULL}, - {"_SDL_GetError", emrt_get_error, "()i", NULL}, - {"_SDL_GetMouseState", emrt_get_mouse_state, "(ii)i", NULL}, - {"_SDL_GetTicks", emrt_get_ticks, "()i", NULL}, - {"_SDL_LockSurface", emrt_lock_surface, "(i)i", NULL}, - {"_SDL_PollEvent", emrt_poll_event, "(i)i", NULL}, - {"_SDL_SetVideoMode", emrt_set_video_mode, "(iiii)i", NULL}, - {"_SDL_UnlockSurface", emrt_unlock_surface, "(i)", NULL}, - }; - if (!wasm_runtime_register_natives_raw("env", env, SDL_arraysize(env))) { - SDL_SetError("unspecified error registering host functions"); - goto error; - } - - char err[1024]; - game->module = wasm_runtime_load(stub_pico8_wasm.data, stub_pico8_wasm.size, - err, sizeof err); - if (game->module == NULL) { - SDL_SetError("%s", err); - goto error; - } - - struct NativeGlobal genv[] = { - {"NaN", {WASM_F64, .of.f64 = NAN}}, - {"Infinity", {WASM_F64, .of.f64 = INFINITY}}, - }; - if (!wasm_runtime_link_globals(game->module, "global", genv, - SDL_arraysize(genv))) { - SDL_SetError("unspecified error registiering host globals"); - goto error; - } - return game; error: + if (game->env) { + pw_env_free(game->env); + } if (game->fb) { pw_fb_free(game->fb); } if (game->input) { pw_input_free(game->input); } - if (game->module) { - wasm_runtime_unload(game->module); - } - if (wasm_init) { - wasm_runtime_destroy(); - } + SDL_free(game); return NULL; } @@ -415,157 +53,58 @@ void pw_game_free(struct pw_game *game) { return; } - if (game->exec) { - wasm_runtime_destroy_exec_env(game->exec); - } - if (game->instance) { - wasm_runtime_deinstantiate(game->instance); - } - wasm_runtime_unload(game->module); - wasm_runtime_destroy(); - - if (game->cart) { - pw_multicart_free(game->cart); - } pw_input_free(game->input); pw_fb_free(game->fb); + pw_env_free(game->env); SDL_free(game); } -bool pw_game_start(struct pw_game *game, struct pw_multicart *cart) { +bool pw_game_start(struct pw_game *game, struct pw_multicart *carts) { if (!game) { SDL_InvalidParamError("game"); return false; } - if (!cart) { - SDL_InvalidParamError("cart"); + if (!carts) { + SDL_InvalidParamError("carts"); return false; } - if (game->cart) { - pw_multicart_free(game->cart); - } - game->cart = cart; - - if (game->exec) { - wasm_runtime_destroy_exec_env(game->exec); - } - if (game->instance) { - wasm_runtime_deinstantiate(game->instance); - } - game->instance = NULL; - game->exec = NULL; - game->malloc = NULL; - game->dyncall = NULL; - game->mix = NULL; - - char err[1024]; - game->instance = - wasm_runtime_instantiate(game->module, 1024, 0, err, sizeof err); - if (!game->instance) { - return SDL_SetError("%s", err); - } - - wasm_function_inst_t ctor = wasm_runtime_lookup_function( - game->instance, "___emscripten_environ_constructor"); - wasm_function_inst_t start = - wasm_runtime_lookup_function(game->instance, "_main"); - wasm_function_inst_t stackalloc = - wasm_runtime_lookup_function(game->instance, "stackAlloc"); - wasm_function_inst_t malloc = - wasm_runtime_lookup_function(game->instance, "_malloc"); - wasm_function_inst_t dyncall = - wasm_runtime_lookup_function(game->instance, "dynCall_v"); - wasm_function_inst_t mix = - wasm_runtime_lookup_function(game->instance, "_mix_0"); - if (!ctor || !start || !stackalloc || !malloc || !dyncall || !mix) { - return SDL_SetError("could not find required exports"); - } - - game->exec = wasm_runtime_create_exec_env(game->instance, 1024); - if (game->exec == NULL) { - return SDL_SetError("failed to create execution environment"); - } - wasm_runtime_set_user_data(game->exec, game); - - game->malloc = malloc; - game->dyncall = dyncall; - game->mix = mix; - if (!wasm_runtime_call_wasm(game->exec, ctor, 0, NULL)) { - return SDL_SetError("error calling constructor: %s", - wasm_runtime_get_exception(game->instance)); + if (game->carts) { + pw_multicart_free(game->carts); } + game->carts = carts; - uint32_t arg0; - { - char const value[] = "./pico8"; - uint32_t args[] = {(uint32_t)sizeof(value)}; - if (!wasm_runtime_call_wasm(game->exec, stackalloc, 1, args)) { - return SDL_SetError("error allocating argument 0: %s", - wasm_runtime_get_exception(game->instance)); - } - - arg0 = args[0]; - char *target = emrt_memory(game->exec, arg0, sizeof(value)); - if (!target) { - return SDL_SetError("invalid argument 0 address"); - } - - SDL_memcpy(target, value, sizeof(value)); - } - - { - char const value[] = "unspecified error"; - uint32_t args[] = {(uint32_t)sizeof(value)}; - if (!wasm_runtime_call_wasm(game->exec, malloc, 1, args)) { - return SDL_SetError("error allocating SDL error string: %s", - wasm_runtime_get_exception(game->instance)); - } - - game->error.ptr = args[0]; - game->error.len = sizeof(value) - 1; - char *target = emrt_memory(game->exec, game->error.ptr, game->error.len); - if (!target) { - return SDL_SetError("invalid SDL error string address"); - } - - SDL_memcpy(target, value, sizeof(value)); - } + pw_env_link(game->env, (struct pw_env_ctx){ + .fb = game->fb, + .input = game->input, + .carts = game->carts, + .instance = &game->instance, + }); + wasm2c_pico8_instantiate(&game->instance, game->env); uint32_t argv; { - uint32_t const value[] = {arg0, 0}; - uint32_t args[] = {(uint32_t)sizeof(value)}; - if (!wasm_runtime_call_wasm(game->exec, stackalloc, 1, args)) { - return SDL_SetError("error allocating arguments array: %s", - wasm_runtime_get_exception(game->instance)); + char const value[] = "./pico8"; + uint32_t arg0 = w2c_pico8_stackAlloc(&game->instance, sizeof(value)); + if (!arg0) { + return SDL_OutOfMemory(); } - argv = args[0]; - char *target = emrt_memory(game->exec, argv, sizeof(value)); - if (!target) { - return SDL_SetError("invalid arguments array address"); + wasm_rt_memory_store(&game->env->memory, value, arg0, sizeof(value)); + argv = w2c_pico8_stackAlloc(&game->instance, 2 * sizeof(arg0)); + if (!argv) { + return SDL_OutOfMemory(); } - SDL_memcpy(target, value, sizeof(value)); + wasm_rt_memory_store32(&game->env->memory, argv, arg0); + wasm_rt_memory_store32(&game->env->memory, argv + 4, 0); } - game->mainfn = 0; - { - uint32_t args[] = {1, argv}; - if (!wasm_runtime_call_wasm(game->exec, start, 2, args)) { - return SDL_SetError("error calling main: %s", - wasm_runtime_get_exception(game->instance)); - } - if (args[0]) { - return SDL_SetError("main returned exit code"); - } - } - if (!game->mainfn) { - return SDL_SetError("main loop function not set"); + if (w2c_pico8_0x5Fmain(&game->instance, 1, argv)) { + return SDL_SetError("main returned exit code"); } - return true; + return game->env->main_loop; } bool pw_game_event(struct pw_game *game, struct pw_players *players, @@ -579,7 +118,7 @@ bool pw_game_event(struct pw_game *game, struct pw_players *players, } bool pw_game_iterate(struct pw_game *game) { - if (!game || !game->exec || !game->dyncall || !game->mix) { + if (!game) { SDL_InvalidParamError("game"); return false; } @@ -587,23 +126,8 @@ bool pw_game_iterate(struct pw_game *game) { pw_fb_iterate(game->fb); pw_input_iterate(game->input, game->fb); - { - uint32_t args[] = {game->mainfn}; - if (!wasm_runtime_call_wasm(game->exec, game->dyncall, 1, args)) { - return SDL_SetError("error calling main loop function: %s", - wasm_runtime_get_exception(game->instance)); - } - } - { - uint32_t args[] = {42, 1337}; - if (!wasm_runtime_call_wasm(game->exec, game->mix, 2, args)) { - return SDL_SetError("error calling audio mixer: %s", - wasm_runtime_get_exception(game->instance)); - } - if (!args[0]) { - return SDL_SetError("audio mixing failed"); - } - } + w2c_pico8_dynCall_v(&game->instance, game->env->main_loop); + w2c_pico8_0x5Fmix_0(&game->instance, 42, 1337); return true; } |
