✦ som
Learn
Introduction A tour of som
Guides
Errors Compile-time code dyn Shaders The web
Elsewhere
GitHub Examples

The web

A som program can be built for the web: WebAssembly, with WASI's C library, run in a browser or by node. It needs zig (zig cc builds it); running it outside a browser needs node.

som build --target web prog     # prog/.build/wasm32-wasi/: prog.wasm, index.html, som.js
som run --target web prog       # serves that folder on this machine, and opens a browser
som test --target web prog      # runs its @tests under node, results here

--target web is wasm32-wasi. The build folder is a page as it is: any static web server can serve it. som run serves it from port 8000 up; arguments after -- reach the program through the address (?arg=one&arg=two).

In a page of your own

The build folder's som.js runs programs in any page, as many as it likes, each in the element it's given. Serve each program's build folder, and start each:

import { start } from './tracer/som.js';

const tracer = start('tracer/pathtracer.wasm', { canvas: document.querySelector('#tracer') });
const life = start('life/life.wasm', { canvas: document.querySelector('#life') });
const fib = start('fib/fibonacci.wasm', { output: document.querySelector('#fib') });

await fib.exited;   // its exit code
tracer.stop();      // when the page is done with it: `exited` gives null

start(url, options) gives the program at once, running: exited, a promise of its exit code, and stop(), which stops it the next time it pauses (a frame's end, for a game). run(url, options) is start(url, options).exited. The options:

option
args its arguments, after its name
env its environment variables
output the element what it writes goes in; without one, the console's
anything what its JavaScript modules read: libs/wgpu's canvas

The options go to its JavaScript modules as they are, so a program without a window doesn't need a canvas, and a library can read whatever it needs.

What a program has there

  • Output goes to the page and the browser's console (under node, to the terminal).
  • Arguments, the time, and random numbers work as elsewhere.
  • Files: under node, the whole file system, relative to where it was started. In a browser there are none: opening one fails.
  • @fail stops it with exit code 134, as an aborted native program has in a shell.
  • som test runs every test in one process, as on Windows: there's no fork, so a test that fails stops the rest.

Pointers, usize and isize are 32 bits. mem::size_of, struct layouts and usize::MAX are the web's while compiling too. A constant can call C while compiling only if no pointer or usize crosses: the compiler's own C is 64-bit.

@if WEB { … } else { … } is code for the web alone, as @if WINDOWS is for Windows; what only some systems have is checked as for them. Around items, it picks what a file declares: the other branch isn't even read, so it can name headers and libraries only other systems have.

@if WEB {
    use extern "webgpu.js" from "webgpu.h";
} else {
    use extern "wgpu_native" from "webgpu.h";
}

JavaScript

An extern block naming a .js file declares functions a JavaScript module gives the program. The module sits beside the .som file that names it, and is copied beside the program when it's built; the page (or node) loads it.

extern "page.js" {
    fn set_title(text: cstr);
    fn now() -> f64;
}

fn main() {
    @if WEB {
        page::set_title("hello");
    }
}
// page.js
export function set_title(text) {
    document.title = som.text(text);
}

export function now() {
    return performance.now();
}

Its functions are the web's alone: calling one elsewhere needs an @if WEB, and a constant can't call one while compiling.

A module's functions are named as som names them: fn set_title is export function set_title. extern "canvas.js" from "canvas.h" takes the declarations from a C header instead, which sits beside the .som file too; its functions are exported by their som names, wgpu_create_instance for wgpuCreateInstance.

What crosses is WebAssembly's numbers: integers up to 32 bits, f32 and f64 are JavaScript numbers; i64 and u64 are BigInts; bool is 0 or 1. A pointer is a number, a place in the program's memory, which the global som reads. A struct is passed as a pointer to it, unless it has one field, which is passed as that field.

som.
text(pointer) the text a cstr points to
bytes(pointer, length) a Uint8Array over that memory
view() a DataView over all of it
memory the WebAssembly.Memory
call(pointer, …args) calls the program's function f as * is
alloc(length), free(pointer) memory of its own, as malloc gives
read(name, pointer) the struct name there, each field read
write(name, pointer, values) writes the fields values has
array(name, count, pointer) count of them, one after another
layout(name) its size, alignment, and fields' offsets

Take text as a cstr (text.c_str), and other memory as a pointer and a length, or as a struct: som.read('Rect', rect) reads one laid out as the program lays it out, which it says itself (a struct is named as in som, Rect, or shapes::Rect where two share a name). A nested struct is an object; a 64-bit integer is a number where it's exactly one, else a BigInt.

A module that keeps anything, or reads its program's options, exports a function instead, which is called for each program with its som and its options, and gives the functions:

export default function ({ som, options }) {
    let frames = 0;
    return {
        frame: () => ++frames,
        set_title: (text) => (options.title.textContent = som.text(text)),
    };
}

Each program then has its own of what it keeps. A module of plain exports is shared by the programs on the page, and reads the one calling it from the global som.

An async function pauses the program until it's done, and the page goes on meanwhile:

export async function sleep(ms) {
    await new Promise((done) => setTimeout(done, ms));
}

A program pauses with WebAssembly's JavaScript Promise Integration (JSPI), which Chrome and Edge have; elsewhere, a page whose program has an async function says it can't run it.

The GPU

libs/wgpu runs in a browser that has WebGPU and JSPI. Its window is the canvas it's started with, as big as the page makes it, or else a canvas filling the page (the build folder's index.html, which writes the program's output over it). Either way it follows its size, as a native window is resized when it's dragged bigger: Gpu::open's size is only for a canvas the page doesn't size. Its keys are those pressed while its canvas has focus, which clicking it gives; its mouse, the page's over it. What's drawn is WebGPU's, the browser's own. webgpu.js gives it WebGPU's C API (webgpu.h, beside it) on navigator.gpu, and sdl.js the part of SDL it uses. A loop of frames pauses at each gpu.present() until the browser draws the next, so the page goes on; what wgpu-native waits for, a device or a buffer read back, the program pauses for.

The mouse can only be grabbed (gpu.grab_mouse()) once the canvas is clicked: a page can't before. Escape ends the program, as it closes the window elsewhere: only the one whose canvas has focus.

Edit this page on GitHub