> ## 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.

# Emscripten builds

> Upload an Emscripten build of a C or C++ engine, port or decompilation: build flags, the C API, saves, and how the player handles fullscreen and sound.

OpenGame hosts the files Emscripten writes. It does not compile your code, so any C or C++ engine, port or decompilation that runs from a folder of files in a browser can be uploaded the same way, raylib included. The [WebAssembly page](https://docs.opengame.io/engines/webassembly.md#starters) starts from a small starter. This page is for a codebase you already build with `emcc` or `em++`.

## Build flags

Build with the flags your engine already needs, plus these:

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

* `-o dist/index.html` puts `index.html` at the top of the folder, which the upload needs. Use `--shell-file` to supply your own page.
* `-sALLOW_MEMORY_GROWTH=1` lets the heap grow, so a big level does not stop the game.
* `-sENVIRONMENT=web` drops the Node and shell code a browser never runs.
* `-lidbfs.js` is needed for [saves](#saves).
* `--js-library opengame.js` is the JavaScript half of the OpenGame C package, for [platform services](#the-c-api).
* `-sEXPORTED_FUNCTIONS` exports the functions the package calls. Add yours to the list.

`-sEXPORTED_RUNTIME_METHODS` lists only what your JavaScript calls, such as `ccall` or `FS`. The package needs none. With `-sMODULARIZE=1`, your page starts the game by calling the factory function Emscripten exports.

Upload the folder as Emscripten wrote it, with `index.js`, `index.wasm` and the `.data` file from `--preload-file` next to `index.html`. Emscripten loads them by paths relative to the page.

A `.br` or `.gz` copy is served with the matching `Content-Encoding`. You need none. If you ship one, make it from the file next to it, or the check reports `compressed-asset-mismatch`. Minify and strip debug output in your build, because OpenGame does not rewrite your files.

### Size

An upload can be up to 4 GiB, with any one file up to 1 GiB. `opengame check` reports `size-warn` above 50 MiB unpacked, because a player waits for the download before the first frame. A decompilation that needs the original game's data can send that data separately, and [upload a large game](https://docs.opengame.io/guides/packaging.md#upload-a-large-game) explains how. Code and `.wasm` go in the archive.

### Load fast

The module and every file packed with `--preload-file` load before `main()` runs. `opengame check` reports `boot-download` when they take more than 3 s on a 50 Mbps connection.

* Build release with `-O3` or `-Oz`. Emscripten runs `wasm-opt` at those levels.
* Keep the default loader. OpenGame sends a `.wasm` with the type `application/wasm`, so it compiles while it downloads; a loader that fetches the module into an `ArrayBuffer` first waits for the whole file.
* Preload only what the first screen needs, and fetch the rest after the game starts.

### Threads

Threaded builds (`-pthread`) work. When the check notes `engine-threads`, OpenGame serves the release cross-origin isolated, so workers get `SharedArrayBuffer`, and you change nothing. A private preview of a threaded build plays only in Chrome or Edge 137 or later, which isolate the game's frame by themselves. Firefox and Safari need the page around the frame isolated too, which OpenGame does only on the published game page. Set `-sPTHREAD_POOL_SIZE` to the number of threads the game starts at once, because Emscripten starts a thread outside the pool only after the main thread returns to the browser. Call the OpenGame C package, saves included, from the main thread. [Threads and WebGPU](https://docs.opengame.io/engines/threads.md) shows how to check the game frame.

## The C API

The OpenGame C package is `opengame.h`, `opengame.c` and `opengame.js`, from `integrations/c` in the [OpenGame repository](https://github.com/opengamehq/opengame). Compile `opengame.c` with your game, link with `--js-library opengame.js`, and include the header. The package calls `window.OpenGame` through Emscripten's JavaScript library mechanism, and adds no protocol or network code.

Ship the SDK with the game, as [Load the SDK](https://docs.opengame.io/engines/webassembly.md#load-the-sdk) shows: copy `opengame-global.js` next to `index.html` and load it before the engine. OpenGame adds the SDK only to a build that uses threads.

| Call | What it does |
| - | - |
| `og_connect(handler, user)` | Connects to the SDK. Returns 1 when it connects, on OpenGame or anywhere else. Returns 0 when the page has no SDK, when the package is already connected, or when it cannot attach. |
| `og_init(callback, user)` | Starts the session. |
| `og_ready()` | Says the first playable frame is on screen. |
| `og_track(event, props_json, callback, user)` | Records an event. `props_json` is a JSON object or `NULL`. |
| `og_board_submit(board, score, callback, user)` | Submits a score to a leaderboard. |
| `og_board_top(board, limit, callback, user)` | Reads the top scores. |
| `og_achievement_unlock(id, callback, user)` | Unlocks an achievement. |
| `og_fullscreen(callback, user)` | Asks for fullscreen. Call it while handling a press or a key. |
| `og_player_json()` | The player, as JSON. Free it with `og_free_json`. |
| `og_saves_mount(path, done, user)` | Mounts a save folder. See [Saves](#saves). |
| `og_saves_flush()` | Writes the save folder to the browser's storage. |

Without the SDK, `og_connect` returns 0 and every other call does nothing. With the SDK and away from OpenGame, the calls still run. Under `opengame dev` the SDK runs services as a local mock: a local player and scores kept in this browser. On any other server, `init` returns `ok` with no services, and leaderboard and achievement requests fail with `unavailable`.

A request returns an id, or 0 when it did not start, and then no callback runs. Results come later as JSON with `ok` and `value`, or `ok` false and `error`. The calls above escape the strings they put into JSON. For any other operation, call `og_request` with JSON you write. [Services from any engine](https://docs.opengame.io/engines/services.md) lists the operations.

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

static void started(int kind, og_request_id id,
    const char *name, size_t name_len,
    const char *json, size_t json_len,
    void *user) {
  /* json is {"ok":true,...} or {"ok":false,...}.
     On ok, and once the first playable frame is drawn, call og_ready(). */
}

void on_first_frame(void) {
  if (og_connect(NULL, NULL)) og_init(started, NULL);
}

void on_level_won(int level, double score) {
  char props[32];
  snprintf(props, sizeof props, "{\"level\":%d}", level);
  og_track("level_won", props, NULL, NULL);
  og_board_submit("high", score, NULL, NULL);
}
```

Call `og_ready()` once the game has drawn the first playable frame and `init` has returned `ok`.

## Saves

Emscripten holds files in memory, so a file the game writes is lost when the tab closes. The C package stores one folder in IndexedDB instead, through Emscripten's IDBFS:

```c theme={"system"}
static void saves_ready(int ok, void *user) {
  /* Read your save files now. ok is 0 when the
     browser's storage was not available. */
}

int main(void) {
  og_saves_mount("/save", saves_ready, NULL);
  /* start the main loop */
}

void write_save(void) {
  FILE *f = fopen("/save/slot1.dat", "wb");
  /* write */
  fclose(f);
  og_saves_flush();
}
```

The rules:

* Read saves only after `done` runs. Mounting loads what was stored, and replaces any files the folder had.
* Call `og_saves_flush()` after closing each file you want to keep. Calls close together become one write, and a pending write runs at once when the player switches tabs or closes the page. A file still open at that moment may be lost.
* When loading fails, `done` gets 0 and the package does not write, so the player's old saves are not touched.
* Only that folder is stored. Files in other folders are held in memory.
* Don't call `FS.syncfs` yourself while the folder is mounted. It would load the stored copy over a save that has not been written yet.

Saves belong to the player's browser, for this game. A reload or a new release of the game does not lose them, because each release is served from the same game address. A player on another browser or device starts fresh, and so does one who clears site data.

## In the player

The player loads your `index.html` in a frame on the game's address, inside the game page. Size your canvas from the window, not a fixed number of pixels, because the frame changes size, for example in fullscreen or when a phone turns.

We checked fullscreen and sound below, and saves above, in Chromium, the engine of Chrome and Edge. Play your game in Firefox and Safari too: the private preview, or the published game for a threaded build.

* **Fullscreen.** Call your engine's fullscreen, such as `SDL_SetWindowFullscreen`, `emscripten_request_fullscreen` or `Module.requestFullscreen`, while handling a press or a key. The player takes the game page fullscreen with the game in it, and your canvas resizes to fill it. The player's fullscreen button exits fullscreen. On a computer, Chrome and Edge send a tap of Esc to the game, and holding Esc exits. In Firefox and Safari a tap of Esc exits. An iPhone has no fullscreen for a page, so the game stays in the page. A request without a press fails, as it does in any browser.
* **Sound.** A browser pauses audio that a game opens before the first press, and SDL, OpenAL and most engines open audio while loading. The player starts that audio when the person presses Play, or presses a key or the screen in the game. While the page has the game muted, the audio waits.
* **Pointer lock.** `requestPointerLock` works, called from a click, as in any page.
* **Gamepads.** `navigator.getGamepads` works, and SDL's game controller support uses it.
* **Keyboard.** The game gets keys once it has focus. The player focuses it when it opens, and a click in the game focuses it again.

## Decompilations and ports

A decompilation or a recompilation of someone else's game is a `decomp` in `opengame.json`, with `basedOn` naming the original, as [packaging](https://docs.opengame.io/guides/packaging.md#write-opengame-json) describes. A decomp cannot enter the jam. It runs the original game's data, so upload only what you have the right to publish. The first time you submit, you certify that you have the rights to what you publish, that data included.

## Test it locally

`opengame dev . --build` serves the build with the game page's headers. To check the player behaviour on this page, [deploy a private preview](https://docs.opengame.io/engines/workflow.md) and play it. Press Play and listen, go fullscreen, save, then reload and check that the save loads. [Threads and WebGPU](https://docs.opengame.io/engines/threads.md) has the frame check for a threaded build.


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