mugon.net docs
SDKs

Bevy

A Bevy game compiled to wasm, with the mugon-sdk-bevy crate.

Bevy is the main SDK. Start a project with mugon init and pick the bevy template (see what you need installed). It gives you a Bevy app, a small Vite entry and build commands. Two pieces have to work together:

The entry (src/index.js) imports the SDK first and starts the wasm from inside Mugon.start, which publishes the context as window.mugon. Vite bundles it, the SDK and the wasm into your distribution folder; you don't ship any SDK file yourself:

import { Mugon } from "@mugon/sdk";
import init from "../pkg/game.js";

Mugon.start(async () => {
  try {
    await init(); // downloads game_bg.wasm through the file proxy and runs main
  } catch (error) {
    // Bevy's web event loop unwinds `main` with this exception on purpose.
    if (!String(error).includes("control flow")) throw error;
  }
  // Keep the callback pending, see below.
  await new Promise(() => {});
});

The crate mugon-sdk-bevy reads that context:

use bevy::prelude::*;
use mugon_sdk_bevy::prelude::*;

fn main() {
    App::new()
        .add_plugins((DefaultPlugins, MugonPlugin))
        .add_systems(Startup, setup)
        .run();
}

fn setup(bridge: NonSend<Bridge>) {
    info!("{:?} {}", bridge.network_role(), bridge.self_player().id);
    bridge.loaded(); // the game is playable: close the loading overlay
}

MugonPlugin panics with a clear message if window.mugon is missing, i.e. if the wasm isn't started from inside the Mugon.start callback.

Loading progress

The entry keeps the Mugon.start callback pending because App::run returns immediately on the web, and a returning callback closes the overlay before your assets are loaded. Close it from Rust instead:

  • Bridge::loaded() when the game is ready, and optionally Bridge::set_progress(fraction, label) while loading; or
  • enable the loading feature, add MugonLoadingPlugin and track assets: the overlay shows loaded/total and closes when they are all loaded.
fn setup(asset_server: Res<AssetServer>, mut loading: ResMut<MugonLoading>) {
    loading.track(asset_server.load::<Image>("sprite.png"));
}

Track everything the game needs before it's playable in one go; assets tracked after the overlay closed are not waited for.

The bridge

Bridge is a NonSend resource with network_role(), self_player(), server_player(), pop_connect(), pop_disconnect(), pop_recv(), send(player_id, bytes, channel), disconnect_player(player_id), show_invite(), end_game(), next_round(&settings, carry_over), carry_over() and toggle_fullscreen(). A Player has an id and a name; pop_connect() returns one, pop_disconnect() and pop_recv() work with ids. On a server the connect queue starts with the players that were connected already. For Lightyear games, the mugon-sdk-lightyear crate builds on this.

Settings

The values the lobby chose for the [[setting]]s in your mugon.toml are fixed when the game starts, and Bridge reads them once:

MethodReturns
get_bool(key)Option<bool> for a boolean setting
get_number(key)Option<f64> for a number setting; every number setting is an f64
get_string(key)Option<&str> for a text setting or a single-choice select
get_strings(key)Option<Vec<&str>> for a select with multiple = true; a single-choice one reads as a one-element list
setting(key) / settings()The SettingValue (Bool, Number, Text or List) of one setting, or all of them

Each getter returns None if the setting is absent or declared with another type.

Ending the game

On the host, Bridge::end_game() sends everyone back to the lobby and Bridge::next_round(&settings, carry_over) asks the host to continue to another round. carry_over is an optional &str (up to 1 MiB) the host's game reads back with Bridge::carry_over() in the next round, see carrying state over. next_round takes the complete settings and replaces the lobby's, so start from cloned_settings(). See ending the game for what the host sees and what happens to invalid settings. Both need SDK 0.2 (next_round was next_game before 0.3) and do nothing on a client.

fn next_round(bridge: NonSend<Bridge>) {
    let mut settings = bridge.cloned_settings();
    settings.insert("map".into(), SettingValue::Text("desert".into()));
    bridge.next_round(&settings, Some("round 2"));
}
fn setup(bridge: NonSend<Bridge>) {
    let friendly_fire = bridge.get_bool("friendly-fire").unwrap_or(false);
    let round_time = bridge.get_number("round-time").unwrap_or(120.0);
}

With the serde feature, Bridge::settings_as::<T>() deserializes all of them into a struct. Setting keys can contain - and ., so rename the fields that need it. A whole-numbered setting fits an integer field; a missing or mismatching setting is an error naming the field:

#[derive(serde::Deserialize)]
struct GameSettings {
    #[serde(rename = "friendly-fire")]
    friendly_fire: bool,
    #[serde(rename = "round-time")]
    round_time: u32,
    #[serde(default)]
    modifiers: Vec<String>,
}

fn setup(bridge: NonSend<Bridge>) {
    let settings: GameSettings = bridge.settings_as().expect("settings match mugon.toml");
}

Your game only receives the final values. Whether a setting may be edited (enabled-when) and whether the game may start (settings-valid-when) is decided by mugon.net before the game launches, so the game doesn't evaluate expressions. A setting that is disabled still has a value: check the setting that gates it before reading it.

Building

The template has two build commands. Both run cargo build --target wasm32-unknown-unknown, wasm-bindgen --target web into pkg/, and npm run build (Vite):

  • mugon dev uses the plain --release profile, which compiles quickly on every save.
  • mugon publish uses the release-lto profile (full LTO, one codegen unit): a much slower compile for a smaller and faster wasm.

Install the wasm-bindgen CLI in the same version as the wasm-bindgen crate in your Cargo.lock. Debug builds of Bevy are very large (hundreds of megabytes), so the template never uses them.

On this page