summaryrefslogtreecommitdiffstats
path: root/site/robo.mjs
blob: 530292057ce139494a7a21e1425f77b64ffd1b5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import init, { make_vm } from './wasm/automathon.js';

let vm;

function compile(text) {
    const start = performance.now();
    const res = vm.compile(text);
    const end = performance.now();
    console.info(`compile took ${end-start} ms`);
    postMessage({ kind: 'compile', res, trans: vm.trans() });
}

function tick() {
    if (!vm.tick()) {
        vm.reset_ip();
    }
    postMessage({ kind: 'tick', trans: vm.trans() });
}

let mod;
async function initWasm() {
    if (mod === undefined) {
        console.debug('worker running init');
        mod = await init();
        console.debug('worker init done');
        vm = make_vm();
        console.debug('worker vm made');
    }
}

async function messageHandler(e) {
    await initWasm();
    const { kind } = e.data;
    switch (kind) {
    case 'compile':
        compile(e.data.text);
        break;
    case 'tick':
        tick();
        break;
    case 'setHeading':
        vm.setheading(e.data.heading);
        break;
    default:
        console.error('invalid message to robo worker', e.data);
        postMessage({ kind: 'error', error: 'badmsg' });
    }
}

self.addEventListener('message', messageHandler);