Skip to content

Commit

Permalink
Add functional demo that runs on wasm
Browse files Browse the repository at this point in the history
  • Loading branch information
W2Wizard committed Oct 8, 2024
1 parent 838167b commit cb69a47
Show file tree
Hide file tree
Showing 5 changed files with 280 additions and 0 deletions.
91 changes: 91 additions & 0 deletions web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Web

MLX42 supports compilation towards [WASM](https://webassembly.org/). What this means is you can run any application written in C directly in the browser!
This overcomes a lot of issues with for instance showing projects towards others or have an environment where building natively just won't work.

In this README you will learn how to compile your project towards Webassembly and later deploy it on github!

## Pre-requisites

- [Emscripten](https://emscripten.org/), you can install this via brew or read the instructions they provide for [Windows or Linux](https://emscripten.org/docs/getting_started/downloads.html)

## Building

Once you made sure you have emscripten installed (check if `emcc` and `emcake` work).

Run:
```bash
emcmake cmake -B build && cmake --build build --parallel
```

## Modifications

You're only required to do a few modifications to your `main.c`.
For this we will use the demo main provided in the root [readme](../README.md).

Add the following headers at the top:
```c
#include <emscripten/html5.h>
#include <emscripten/emscripten.h>
```

Modify your main:
```c
// Invoked instead of mlx_loop directly.
void emscripten_main_loop() {
mlx_loop(mlx);
}

int32_t main(int argc, char **argv)
{
// Gotta error check this stuff
if (!(mlx = mlx_init(WIDTH, HEIGHT, "MLX42", true)))
{
puts(mlx_strerror(mlx_errno));
return(EXIT_FAILURE);
}
if (!(image = mlx_new_image(mlx, 128, 128)))
{
mlx_close_window(mlx);
puts(mlx_strerror(mlx_errno));
return(EXIT_FAILURE);
}
if (mlx_image_to_window(mlx, image, 0, 0) == -1)
{
mlx_close_window(mlx);
puts(mlx_strerror(mlx_errno));
return(EXIT_FAILURE);
}

mlx_loop_hook(mlx, ft_randomize, mlx);
mlx_loop_hook(mlx, ft_hook, mlx);

// This function will set up the main loop
emscripten_set_main_loop(emscripten_main_loop, 0, true);
mlx_terminate(mlx);
return (EXIT_SUCCESS);
}
```
Thats actually it! It may or may not be necessary to modify your own source code depending on what you do but that's most often not the case.
It is that easy to just re-deploy your own app into webassembly.
## Building
```bash
# Compile C into JS/WASM
emcc -O3 -I include -I mlx -pthread main.c \
-o ./web/demo.js \
./build/libmlx42.a \
-s USE_GLFW=3 -s USE_WEBGL2=1 -s FULL_ES3=1 -s WASM=1 \
-s NO_EXIT_RUNTIME=1 -s EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' \
-s ALLOW_MEMORY_GROWTH
# Navigate into the web folder (if you're running this directly from this repo)
cd web
# Launch local webserver, this is required to make the service worker function.
python3 -m http.server 8000
```

Once the server is up and running all you need to do now is go to [localhost](http://localhost:8000/index.html)
146 changes: 146 additions & 0 deletions web/coi-serviceworker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/*! coi-serviceworker v0.1.7 - Guido Zuidhof and contributors, licensed under MIT */
let coepCredentialless = false;
if (typeof window === 'undefined') {
self.addEventListener("install", () => self.skipWaiting());
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));

self.addEventListener("message", (ev) => {
if (!ev.data) {
return;
} else if (ev.data.type === "deregister") {
self.registration
.unregister()
.then(() => {
return self.clients.matchAll();
})
.then(clients => {
clients.forEach((client) => client.navigate(client.url));
});
} else if (ev.data.type === "coepCredentialless") {
coepCredentialless = ev.data.value;
}
});

self.addEventListener("fetch", function (event) {
const r = event.request;
if (r.cache === "only-if-cached" && r.mode !== "same-origin") {
return;
}

const request = (coepCredentialless && r.mode === "no-cors")
? new Request(r, {
credentials: "omit",
})
: r;
event.respondWith(
fetch(request)
.then((response) => {
if (response.status === 0) {
return response;
}

const newHeaders = new Headers(response.headers);
newHeaders.set("Cross-Origin-Embedder-Policy",
coepCredentialless ? "credentialless" : "require-corp"
);
if (!coepCredentialless) {
newHeaders.set("Cross-Origin-Resource-Policy", "cross-origin");
}
newHeaders.set("Cross-Origin-Opener-Policy", "same-origin");

return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders,
});
})
.catch((e) => console.error(e))
);
});

} else {
(() => {
const reloadedBySelf = window.sessionStorage.getItem("coiReloadedBySelf");
window.sessionStorage.removeItem("coiReloadedBySelf");
const coepDegrading = (reloadedBySelf == "coepdegrade");

// You can customize the behavior of this script through a global `coi` variable.
const coi = {
shouldRegister: () => !reloadedBySelf,
shouldDeregister: () => false,
coepCredentialless: () => true,
coepDegrade: () => true,
doReload: () => window.location.reload(),
quiet: false,
...window.coi
};

const n = navigator;
const controlling = n.serviceWorker && n.serviceWorker.controller;

// Record the failure if the page is served by serviceWorker.
if (controlling && !window.crossOriginIsolated) {
window.sessionStorage.setItem("coiCoepHasFailed", "true");
}
const coepHasFailed = window.sessionStorage.getItem("coiCoepHasFailed");

if (controlling) {
// Reload only on the first failure.
const reloadToDegrade = coi.coepDegrade() && !(
coepDegrading || window.crossOriginIsolated
);
n.serviceWorker.controller.postMessage({
type: "coepCredentialless",
value: (reloadToDegrade || coepHasFailed && coi.coepDegrade())
? false
: coi.coepCredentialless(),
});
if (reloadToDegrade) {
!coi.quiet && console.log("Reloading page to degrade COEP.");
window.sessionStorage.setItem("coiReloadedBySelf", "coepdegrade");
coi.doReload("coepdegrade");
}

if (coi.shouldDeregister()) {
n.serviceWorker.controller.postMessage({ type: "deregister" });
}
}

// If we're already coi: do nothing. Perhaps it's due to this script doing its job, or COOP/COEP are
// already set from the origin server. Also if the browser has no notion of crossOriginIsolated, just give up here.
if (window.crossOriginIsolated !== false || !coi.shouldRegister()) return;

if (!window.isSecureContext) {
!coi.quiet && console.log("COOP/COEP Service Worker not registered, a secure context is required.");
return;
}

// In some environments (e.g. Firefox private mode) this won't be available
if (!n.serviceWorker) {
!coi.quiet && console.error("COOP/COEP Service Worker not registered, perhaps due to private mode.");
return;
}

n.serviceWorker.register(window.document.currentScript.src).then(
(registration) => {
!coi.quiet && console.log("COOP/COEP Service Worker registered", registration.scope);

registration.addEventListener("updatefound", () => {
!coi.quiet && console.log("Reloading page to make use of updated COOP/COEP Service Worker.");
window.sessionStorage.setItem("coiReloadedBySelf", "updatefound");
coi.doReload();
});

// If the registration is active, but it's not controlling the page
if (registration.active && !n.serviceWorker.controller) {
!coi.quiet && console.log("Reloading page to make use of COOP/COEP Service Worker.");
window.sessionStorage.setItem("coiReloadedBySelf", "notcontrolling");
coi.doReload();
}
},
(err) => {
!coi.quiet && console.error("COOP/COEP Service Worker failed to register:", err);
}
);
})();
}
1 change: 1 addition & 0 deletions web/demo.js

Large diffs are not rendered by default.

Binary file added web/demo.wasm
Binary file not shown.
42 changes: 42 additions & 0 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebAssembly Test</title>
<style>
body {
margin: 0;
width: 100%;
min-height: 100dvh; /* Fallback for browsers not supporting viewport height */
background-color: black; /* Set background color to black */
}
</style>
</head>
<body>
<script src="coi-serviceworker.js"></script>
<span class="load">Loading...</span>
<canvas width="1024" height="1024" id="canvas"></canvas>
<script>
var Module = {
onRuntimeInitialized: function() {
// This is called when the Emscripten module is ready
console.log("Emscripten module initialized");

// Hide loading text when canvas is fully loaded
var loadingText = document.querySelector('.load');
loadingText.style.display = 'none';
},
canvas: (function() {
var canvas = document.getElementById('canvas');
canvas.addEventListener("webglcontextlost", function(e) {
alert('WebGL context lost. Reload the page.');
e.preventDefault();
}, false);
return canvas;
})()
};
</script>
<script src="demo.js"></script>
</body>
</html>

0 comments on commit cb69a47

Please sign in to comment.