web: MRPCI runs in a browser, as a player

The macroquad GUI now builds for wasm32 the way MRPGI's does, with two
deliberate differences.

It boots into Play and the F8 editor toggle is compiled out of the web
build. What ships to someone playing a game should be the game, not the tool
that made it.

And it embeds a WorldBundle rather than a game *folder*. MRPGI reaches for
include_dir! because its bundle carries only manifest+rooms; MRPCI's already
carries scripts and sprites too, so one `--export-bundle` document is the
whole game. That is also the format MRP3GI boots from, which means one file
now feeds two engines.

mrpci_alloc/mrpci_world_in let the page hand over another bundle while the
engine is running — the arcade picker and drag-and-drop both arrive there,
and the session restarts on the new world.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
m3ultra 2026-07-26 11:38:51 +10:00
parent ce42d69a3a
commit 50ede0febf
8 changed files with 241 additions and 13 deletions

16
.cargo/config.toml Normal file
View File

@ -0,0 +1,16 @@
# Which game gets baked into wasm builds (WEB_BUNDLE in mrpci/src/main.rs).
# It is a WorldBundle JSON, not a folder: the browser has no filesystem, and
# `mrpci-headless --export-bundle` already writes exactly this document.
# web/build.sh regenerates it and overrides the path per build.
[env]
MRPCI_WEB_BUNDLE = { value = "web/game.bundle.json", relative = true }
# Web builds: miniquad's JS imports (console_log, init_webgl, ...) are
# resolved at runtime by web/mq_js_bundle.js — tell the linker to allow them.
# The mrpci_* exports are the page's game-loading bridge into the engine.
[target.wasm32-unknown-unknown]
rustflags = [
"-C", "link-arg=--allow-undefined",
"-C", "link-arg=--export=mrpci_alloc",
"-C", "link-arg=--export=mrpci_world_in",
]

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
/target
games/*/saves/
.DS_Store
web/dist/
web/game.bundle.json

1
Cargo.lock generated
View File

@ -534,6 +534,7 @@ version = "0.1.0"
dependencies = [
"macroquad",
"mrpci-core",
"serde_json",
]
[[package]]

View File

@ -7,3 +7,6 @@ description = "Monster Robot Party Creative Interpreter — the SCI-generation s
[dependencies]
mrpci-core = { path = "../mrpci-core" }
macroquad = { version = "0.4", features = ["audio"] }
# The browser build has no filesystem: it boots from a WorldBundle JSON baked
# in at compile time, and the page can hand it another one at runtime.
serde_json = "1"

View File

@ -101,25 +101,82 @@ fn conf() -> Conf {
}
}
/// The browser build's default game, baked in at compile time.
///
/// A folder of JSON is a filesystem idea and the browser hasn't got one, so
/// the web build carries a `WorldBundle` — the same single-document form
/// `mrpci-headless --export-bundle` writes and the MRP3GI bridge boots from.
/// Which bundle is `MRPCI_WEB_BUNDLE` at compile time (see .cargo/config.toml).
#[cfg(target_arch = "wasm32")]
const WEB_BUNDLE: &str = include_str!(env!("MRPCI_WEB_BUNDLE"));
/// Rebuild a whole world from a bundle JSON. `None` if it doesn't parse —
/// a bad drag-and-drop should be a shrug, not a blank screen.
pub fn world_from_bundle(json: &str) -> Option<World> {
let b: mrpci_core::WorldBundle = serde_json::from_str(json).ok()?;
// Sorted, like the headless `--bundle` path: both boots must bake
// identical cels or the same game would look different in two windows.
let mut sprites: Vec<_> = b.sprites.into_iter().collect();
sprites.sort_by(|a, c| a.0.cmp(&c.0));
Some(World::from_memory(b.manifest, b.rooms, b.scripts, sprites))
}
/// The web save/load bridge, mirroring MRPGI's. The page writes a bundle
/// into an `mrpci_alloc` buffer and hands it over; the main loop picks it up
/// on the next frame. No threads, no async.
#[cfg(target_arch = "wasm32")]
mod web_bridge {
use std::sync::Mutex;
pub static PENDING_LOAD: Mutex<Option<String>> = Mutex::new(None);
/// JS asks for a buffer to write into.
#[no_mangle]
pub extern "C" fn mrpci_alloc(len: usize) -> *mut u8 {
Box::into_raw(vec![0u8; len].into_boxed_slice()) as *mut u8
}
/// JS hands over a bundle JSON it wrote into that buffer.
#[no_mangle]
pub extern "C" fn mrpci_world_in(ptr: *mut u8, len: usize) {
let s = unsafe {
let boxed = Box::from_raw(std::slice::from_raw_parts_mut(ptr, len) as *mut [u8]);
String::from_utf8_lossy(&boxed).into_owned()
};
*PENDING_LOAD.lock().unwrap() = Some(s);
}
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let game_dir = args
.iter()
.position(|a| a == "--game")
.and_then(|i| args.get(i + 1).cloned())
.unwrap_or_else(|| {
// Default to the demo if it's been generated, else the cwd.
if std::path::Path::new("games/neon-precinct/game.json").exists() {
"games/neon-precinct".into()
} else {
".".into()
}
});
#[cfg(not(target_arch = "wasm32"))]
let game_dir = {
let args: Vec<String> = std::env::args().collect();
args.iter()
.position(|a| a == "--game")
.and_then(|i| args.get(i + 1).cloned())
.unwrap_or_else(|| {
// Default to the demo if it's been generated, else the cwd.
if std::path::Path::new("games/neon-precinct/game.json").exists() {
"games/neon-precinct".into()
} else {
".".into()
}
})
};
// On the web the "game dir" is only ever an audio-lookup prefix; the
// world itself is embedded. Relative, so it works under any sub-path.
#[cfg(target_arch = "wasm32")]
let game_dir = String::from("game");
macroquad::Window::from_config(conf(), amain(game_dir));
}
async fn amain(game_dir: String) {
#[cfg(not(target_arch = "wasm32"))]
let world = World::load_game(&game_dir);
// A malformed baked bundle would be a build error we'd rather see as an
// empty room than a white screen.
#[cfg(target_arch = "wasm32")]
let world = world_from_bundle(WEB_BUNDLE).unwrap_or_else(|| World::load_game("."));
let mut gs = GameState::new(world);
let mut audio = sound::LazyAudio::start(&game_dir);
let mut ui = Ui {
@ -167,7 +224,32 @@ async fn amain(game_dir: String) {
show_mouse(false);
loop {
// --- a game handed over by the page ----------------------------------
// The browser build is a *player*: the picker (and drag-and-drop)
// swap the whole world underneath it, and the session restarts.
#[cfg(target_arch = "wasm32")]
{
let incoming = web_bridge::PENDING_LOAD.lock().unwrap().take();
if let Some(json) = incoming {
if let Some(w) = world_from_bundle(&json) {
gs = GameState::new(w);
ui.log.clear();
ui.selected_item = None;
ui.inventory_open = false;
ui.typing = false;
ui.fade = 0.0;
let boot = gs.apply(Command::NewGame { room: None });
handle_events(&boot, &mut ui, &mut audio);
} else {
ui.log.push("(that file isn't an MRPCI game bundle.)".into());
}
}
}
// --- edit-mode toggle -------------------------------------------------
// Native only. Authoring is a desktop job; what ships to a player is
// the game, not the tool that made it.
#[cfg(not(target_arch = "wasm32"))]
if is_key_pressed(KeyCode::F8) {
ed.active = !ed.active;
if ed.active {

45
web/build.sh Executable file
View File

@ -0,0 +1,45 @@
#!/bin/sh
# Build the browser version of MRPCI into web/dist/ (self-contained, static).
# Requires the wasm target: rustup target add wasm32-unknown-unknown
#
# ./web/build.sh # bakes games/neon-precinct
# ./web/build.sh /path/to/game # bake any game folder instead
#
# The browser build is a PLAYER: it boots straight into the game and the F8
# editor toggle is compiled out. Authoring stays on the desktop.
#
# Unlike MRPGI's build, which embeds a game *folder* with include_dir!, this
# bakes a single WorldBundle JSON — the same document `--export-bundle`
# writes and the MRP3GI bridge boots from. One format, three engines, and the
# page can hand the engine another one at runtime.
set -e
cd "$(dirname "$0")/.."
GAME="${1:-games/neon-precinct}"
BUNDLE="web/game.bundle.json"
echo "baking game: $GAME"
cargo build --release -p mrpci-core --bin mrpci-headless
./target/release/mrpci-headless --game "$GAME" --export-bundle "$BUNDLE"
# include_str! reads the path at compile time; make sure the crate recompiles
# when only the bundle changed.
touch mrpci/src/main.rs
cargo build -p mrpci --release --target wasm32-unknown-unknown
rm -rf web/dist
mkdir -p web/dist
cp target/wasm32-unknown-unknown/release/mrpci.wasm web/dist/
cp web/index.html web/mq_js_bundle.js web/dist/
# A game's own sfx/ and music/ ride along if it has them; the engine falls
# back to its built-in synth for anything missing, so this is optional.
for kind in sfx music; do
if [ -d "$GAME/$kind" ]; then
mkdir -p "web/dist/game/$kind"
cp "$GAME/$kind"/*.wav "$GAME/$kind"/*.ogg "$GAME/$kind"/*.mp3 \
"web/dist/game/$kind/" 2>/dev/null || true
fi
done
echo "web build ready: $(du -sh web/dist | cut -f1) in web/dist/"

76
web/index.html Normal file
View File

@ -0,0 +1,76 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>MRPCI — Monster Robot Party Creative Interpreter</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><text y='14' font-size='14'>🎨</text></svg>" />
<link rel="stylesheet" href="arcade.css" />
<style>
html, body { margin: 0; height: 100%; background: #05070b; overflow: hidden; }
/* miniquad sizes its drawing buffer from the canvas's *CSS* box, so the
canvas needs real dimensions — `max-width` inside a centring grid
resolves to zero and the engine renders a 0x0 frame. Give it the
whole area below the arcade bar, like MRPGI does. */
canvas {
position: absolute; inset: 34px 0 24px 0;
width: 100%; height: calc(100% - 58px);
display: block; outline: none; image-rendering: pixelated; background: #0b0d11;
}
body.arcade-standalone-page canvas { inset: 0 0 24px 0; height: calc(100% - 24px); }
#boot {
position: absolute; inset: 34px 0 0 0; display: grid; place-items: center;
background: #05070b; color: #8296aa; z-index: 20;
font: 12px/1 ui-monospace, Menlo, monospace; letter-spacing: 0.16em;
text-transform: uppercase; transition: opacity 400ms ease; pointer-events: none;
}
#keys {
position: fixed; bottom: 0; left: 0; right: 0; z-index: 30;
padding: 4px 10px; background: rgba(6,10,16,0.86); color: #6f8296;
border-top: 1px solid rgba(120,190,255,0.18);
font: 11px/1.5 ui-monospace, Menlo, monospace;
}
#keys b { color: #9fb4c8; font-weight: 600; }
</style>
</head>
<body class="arcade-inset">
<canvas id="glcanvas" tabindex="1"></canvas>
<div id="boot">starting the interpreter…</div>
<div id="keys">
<b>click</b> verb at pixel · <b>right-click</b> cycle verb · <b>F1F4</b> walk/look/do/talk ·
<b>I</b> inventory · <b>Enter</b> type a command · <b>F5/F7</b> save/restore · <b>M</b> mute · <b>N</b> scanlines
</div>
<script src="mq_js_bundle.js"></script>
<script>
// miniquad resolves the engine's undefined imports at runtime; register
// before the wasm loads or the instantiation fails.
miniquad_add_plugin({ register_plugin: () => {}, version: '1', name: 'mrpci_bridge' })
/** Hand a WorldBundle JSON to the running engine. */
function sendBundleToEngine(json) {
const bytes = new TextEncoder().encode(json)
const ptr = wasm_exports.mrpci_alloc(bytes.length)
new Uint8Array(wasm_memory.buffer, ptr, bytes.length).set(bytes)
wasm_exports.mrpci_world_in(ptr, bytes.length)
}
load('mrpci.wasm')
const engineReady = () => typeof wasm_exports !== 'undefined' && !!wasm_exports
const t = setInterval(() => {
if (!engineReady()) return
document.getElementById('boot').style.opacity = '0'
clearInterval(t)
}, 200)
</script>
<script src="picker.js"></script>
<script>
MRPArcade.init({
engine: 'mrpci',
ready: () => typeof wasm_exports !== 'undefined' && !!wasm_exports,
load: (json) => sendBundleToEngine(json),
})
</script>
</body>
</html>

3
web/mq_js_bundle.js Normal file

File diff suppressed because one or more lines are too long