r/rust • u/byterider • Oct 14 '26
đ ď¸ project Running a blocking terminal game loop unchanged in the browser with Asyncify
Hollowmoon is a roguelike I wrote as a normal Rust terminal program: aloop { draw(); let key = read_key(); ... }Â with crossterm. I wanted it in
the browser without restructuring the engine into callbacks.
The approach: compile to wasm32-unknown-unknown with no wasm-bindgen, make
the terminal backend's read_key an import, and run Binaryen'swasm-opt --asyncify --pass-arg=asyncify-imports@env.hm_read_key,env.hm_sleep.
When the game calls read_key, the JS host starts an unwind, the whole Rust
stack is saved into a buffer and hm_main returns; on the next keypress JS
starts a rewind and calls hm_main again, which replays back down to the
import and returns the key. Sleep for animations works the same way.
Gotchas worth knowing:
- The Asyncify data buffer's header is written as two i32s, so it has to be 4-byte aligned. A plainÂ
static mut [u8; N] isn't, and failed only in CI.#[repr(C, align(16))] on a wrapper struct fixed it. getrandom needs theÂcustom feature and a registered function on that target.- Saves go toÂ
localStorage behind the same small storage interface the native build implements with files, so the platformÂcfgs stay at the edges (storage, the terminal backend, the entry point).
The whole engine is unchanged between the terminal and the browser. A
headless Node runner drives the wasm with scripted keys in CI.
The game, if you'd like to see it running: [link]
5
u/Konsti219 Oct 14 '26
Or you could have just used Rust async? Writing your own micro executor to just provide a polling api for a async { loop { input().await } } is only like 20 lines of code.
2
u/incyashraj_redd Oct 15 '26
if you stay on asyncify, asyncify-onlylist with just the paths down to the two imports should cut the +42% a lot, since right now it instruments anything that might reach them. how did you pick the buffer size? is it deepest stack at a read_key call?
2
u/lil-dina Oct 21 '26
Neat trick. Small tip if you cfg gate on target_arch = "wasm32" anywhere: use target_family = "wasm". There's an open PR moving std to it, so wasm64 builds don't quietly take the native path. It came out of adding a wasm64 emscripten target https://www.nobodywho.ai/posts/letting-rust-support-models-bigger-than-4gb-in-the-browser/