> ## Documentation Index
> Fetch the complete documentation index at: https://docs.opengame.io/llms.txt
> Use this file to discover all available pages before exploring further.

# WebAssembly

> Deploy raw WebAssembly, Emscripten builds of C and C++, and Rust, Zig and Go compiled to wasm, and connect them to the SDK.

OpenGame hosts a WebAssembly game as a static folder: `index.html`, the `.wasm` module and the JavaScript that loads it. That covers a module with a loader you wrote, a C or C++ game compiled with Emscripten, and Rust, Zig or Go compiled to wasm, including Bevy and Ebitengine games. OpenGame does not compile anything: you build, and upload the build.

| Topic | On OpenGame |
| - | - |
| Hosting | The build folder. `.wasm` files are served as `application/wasm`, so `WebAssembly.instantiateStreaming` works |
| Services | Player, leaderboards, achievements, events, pause, mute, fullscreen and links, through the page global and an OpenGame package for C, Rust, Zig or Go |
| Threads | Supported. A build whose wasm uses shared memory, such as Emscripten with `-pthread`, is served cross-origin isolated |
| Renderer | Whatever your code draws with: WebGL, WebGPU or a 2D canvas |
| Multiplayer | The browser's WebSocket or WebRTC, through Emscripten or `web-sys`. No raw sockets. See [Multiplayer](https://docs.opengame.io/guides/multiplayer.md#by-engine) |

## Choose the engine ID

`opengame init` detects most of these from your project. Pass `--engine` to choose one yourself:

| Build | `--engine` | Detected from |
| - | - | - |
| A wasm module with your own loader | `webassembly` | Pass the ID yourself |
| Emscripten | `emscripten`, `c` or `cpp` | Pass the ID yourself. With a `Makefile`, `init` sets `make` as the build command |
| Rust | `rust` | A `Cargo.toml` that names a wasm target, wasm-bindgen, `web-sys` or `js-sys` |
| Zig | `zig` | `build.zig` |
| Go | `go` | `go.mod` |

In the build, `opengame check` and the server recognize Emscripten from its runtime code and the `.wasm` it built, threaded or not, and from its `MINIMAL_RUNTIME` loader, as well as Rust's wasm-bindgen glue and Go's `wasm_exec.js`. A Zig build carries no signature of its own, so a module its page loads itself is named WebAssembly. Hosting is the same either way.

## Starters

The [OpenGame repository](https://github.com/opengamehq/opengame) has a starter for each language, under `templates/`. Each builds with `node build.mjs` into `dist/`, and needs its compiler on your `PATH`.

| Starter | Compiler | SDK in the build |
| - | - | - |
| `templates/c` | `emcc` | Add `opengame-global.js` yourself |
| `templates/cpp` | `em++` | Add `opengame-global.js` yourself |
| `templates/rust` | `cargo` with `wasm32-unknown-unknown` | Add `opengame-global.js` yourself |
| `templates/zig` | Zig 0.13 | Copied in by `build.mjs` from the installed SDK |
| `templates/go` | Go | Copied in by `build.mjs` from the installed SDK |

```bash theme={"system"}
git clone https://github.com/opengamehq/opengame
cp -R opengame/templates/zig my-game
cd my-game
```

```bash theme={"system"}
npm i @opengamehq/sdk@latest
```

## Load the SDK

Every language here reaches the SDK through `window.OpenGame`. Ship `opengame-global.js` and its `.LEGAL.txt` notice in the build, and load the script before the module, as [Platform services](https://docs.opengame.io/engines/services.md#load-the-page-global) shows:

```html theme={"system"}
<script src="opengame-global.js"></script>
```

A build with threads also gets the SDK at `/_og/sdk.js` from OpenGame. A build without threads gets no added script, so ship a copy.

## Raw WebAssembly

Write `index.html` and a loader, and call the SDK from JavaScript:

```html index.html theme={"system"}
<script src="opengame-global.js"></script>
<script type="module">
  const og = window.OpenGame;
  await og?.init();
  const { instance } = await WebAssembly.instantiateStreaming(
    fetch("./game.wasm"),
    { env: { submitScore: (n) => og?.leaderboard("points").submit(n) } },
  );
  instance.exports.start();
  // After the first frame the player can control:
  og?.ready();
</script>
```

The imports are yours to name. Keep `game.wasm` beside `index.html`, or fetch it by a path relative to the page.

## C and C++ with Emscripten

Build with Emscripten, with its environment active:

```bash theme={"system"}
emcc main.c -O2 -sALLOW_MEMORY_GROWTH=1 -o dist/index.html
```

* **Output:** Emscripten writes `index.html`, `index.js` and `index.wasm`, plus any `.data` file the build preloads. Upload the whole folder.
* **Libraries:** build each native library with Emscripten too. A desktop library does not link into a web build.
* **Main loop:** pass your frame function to `emscripten_set_main_loop`, so each frame returns control to the browser.
* **Threads:** optional. Build with `-pthread`, and OpenGame serves the build isolated.
* **Memory:** `-sALLOW_MEMORY_GROWTH=1` lets the heap grow. If JavaScript keeps a view of the heap, create it again after growth.
* **C++ exports:** put each function you mark `EMSCRIPTEN_KEEPALIVE` inside `extern "C"`, so JavaScript can call it by its plain name.

The OpenGame C package, `integrations/c` in the repository, calls the SDK from C or C++. Copy `opengame.c`, `opengame.h` and `opengame.js` into the project, and link them:

```bash theme={"system"}
emcc main.c opengame.c -O2 -sALLOW_MEMORY_GROWTH=1 \
  --js-library opengame.js \
  -sEXPORTED_FUNCTIONS='["_main","_og_alloc","_og_free","_og_dispatch"]' \
  -o dist/index.html
```

```c main.c theme={"system"}
#include <string.h>
#include "opengame.h"

/* Pointers are borrowed until this returns. */
static void on_message(int kind, og_request_id id,
    const char *name, size_t name_len,
    const char *json, size_t json_len, void *user) {
  if (kind == OG_RESULT && strcmp(name, "init") == 0)
    og_ready(); /* after the first frame */
}

int main(void) {
  /* 0 means no SDK on the page: play on without it. */
  if (og_connect(on_message, NULL))
    og_request("init", "{}", on_message, NULL);
  /* ... */
}
```

`og_request` takes a bridge operation and its JSON arguments, and the result arrives later through the callback. [Platform services](https://docs.opengame.io/engines/services.md#native-bridge) lists the operations. Emscripten rewrites `index.html` on each build, so add the `opengame-global.js` script tag after the build, or pass a shell file with `--shell-file` that already has it.

[Emscripten builds](https://docs.opengame.io/engines/emscripten.md) covers a larger codebase, a port or a decompilation: the build flags, shorthand calls such as `og_track` and `og_board_submit`, saves that last between visits, and what the player does for fullscreen, sound and input.

## Rust

Add the wasm target, then build with Trunk or with Cargo:

```bash theme={"system"}
rustup target add wasm32-unknown-unknown
trunk build --release
```

* **Trunk:** `init` sets `trunk build --release` as the build command when the project has `Trunk.toml`, or an `index.html` that uses `data-trunk`. Trunk writes `dist/`.
* **wasm-bindgen:** install the `wasm-bindgen` CLI at the version of the `wasm-bindgen` crate in `Cargo.lock`.
* **Threads:** a build whose module uses shared memory is served isolated.

The `opengame` crate is `integrations/rust` in the repository, used as a path dependency:

```toml Cargo.toml theme={"system"}
[dependencies.opengame]
path = "../opengame/integrations/rust"
```

```rust theme={"system"}
async fn enter_game() -> opengame::Result<()> {
    let env = opengame::init().await?;
    opengame::ready()?; // after the first playable frame
    if env.connected {
        let best = opengame::leaderboard("best").top(Some(10)).await?;
    }
    Ok(())
}
```

The crate also has `track`, `achievements::unlock`, `achievements::list`, `sign_in`, `open_link`, `fullscreen`, `player` and `subscribe` for pause, mute and player changes. It uses wasm-bindgen by default. With `default-features = false` and `features = ["raw-import"]`, it uses raw imports, and the page loads it with `imports.mjs`, `host.mjs` and `lifecycle.mjs` from `integrations/c`.

To add the SDK in a Trunk project, copy both files with Trunk and load the script before Trunk's module:

```html index.html theme={"system"}
<link data-trunk rel="copy-file" href="opengame-global.js" />
<link data-trunk rel="copy-file" href="opengame-global.js.LEGAL.txt" />
<script src="opengame-global.js"></script>
<link data-trunk rel="rust" />
```

## Zig

Build for `wasm32-freestanding` with Zig 0.13:

```bash theme={"system"}
zig build-exe main.zig -target wasm32-freestanding \
  -fno-entry -rdynamic --export-memory \
  -O ReleaseSmall -femit-bin=dist/game.wasm
```

In `build.zig`, the same settings are `entry = .disabled`, `rdynamic = true` and `export_memory = true`. The OpenGame Zig package, `integrations/zig`, has a Zig module and `opengame.mjs`, which builds the imports the module needs:

```js theme={"system"}
import { createOpenGameImports } from "./opengame.mjs";

let instance;
const host = createOpenGameImports(() => instance);
({ instance } = await WebAssembly.instantiateStreaming(
  fetch("./game.wasm"), host.imports));
instance.exports.start();
```

Keep `opengame.mjs` and `lifecycle.js` beside the page. Call no export until `instance` is assigned, and call `host.dispose()` on `pagehide`. The Zig package expects one memory that is not shared, so use it in a single-thread build.

## Go

Build with the standard Go compiler:

```bash theme={"system"}
GOOS=js GOARCH=wasm go build -o dist/game.wasm .
```

* **Runtime glue:** copy `wasm_exec.js` from the Go you built with. It is in `$(go env GOROOT)/lib/wasm` on Go 1.24 and later, and in `misc/wasm` before that.
* **Page:** load `opengame-global.js`, then `lifecycle.js`, then `wasm_exec.js`, and start the module with `new Go()` and `go.run(instance)`.
* **Threads:** Go's `js/wasm` port runs every goroutine on the browser's main thread.

The OpenGame Go module is `integrations/go` in the repository. Point your `go.mod` at it:

```bash theme={"system"}
m=github.com/opengamehq/opengame-go
go mod edit -require $m@v0.0.0
go mod edit -replace $m=../opengame/integrations/go
```

Copy `integrations/go/web/lifecycle.js` into the build. Drain the module's message channel continuously, and never block the JavaScript event loop while you wait for a result.

## Deploy

```bash theme={"system"}
opengame init .
opengame dev . --build
opengame check . --build
opengame deploy .
```

`deploy` uploads the build and prints the address of its deploy page, where Play appears once the checks pass. [Export and deploy](https://docs.opengame.io/engines/workflow.md) covers each step and `opengame submit`.

## Memory and callbacks

* A module's declared maximum memory is a limit it reserves, not memory it uses. Measure the running game.
* Recreate typed-array views of wasm memory after it grows.
* The OpenGame packages hand callbacks borrowed pointers or slices. Copy what you keep before the callback returns.
* Call the SDK from the browser's main thread. A worker thread has no `window.OpenGame`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.