summaryrefslogtreecommitdiff
path: root/index.htm
blob: d4729bfda4ea6db2600d14dc8129ad1b6acb5564 (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
<!DOCTYPE html>
<html style="height: 100%; overflow: hidden; overflow-x: hidden;">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel='icon' type='image/gif' href='/favicon.gif'>
    <title> Reduced System Layer </title>
  </head>
  <body style="margin: 0; height: 100%; overflow: hidden; overflow-x: hidden;">
    <canvas style="margin: 0; width: 100%; height: 100%;" id="frame" oncontextmenu="event.preventDefault()"></canvas>
    <script type="worklet">
      registerProcessor(
        'Sound_Ring',
        class Sound_Ring extends AudioWorkletProcessor {
          constructor(options) {
            super();

            this.ring = options.processorOptions.ring;

            this.position       = 0;
            this.max_num_frames = this.ring.byteLength / 4;
          }

          process(input, output, parameters) {
            let num_channels = output[0].length;
            let num_samples  = output[0][0].length;
            let num_frames   = num_samples * num_channels;

            if (num_frames > this.max_num_frames) {
              console.error("Sound buffer overflow");
              return true;
            }

            let frames = new Float32Array(this.ring);

            if (num_frames <= this.max_num_frames - this.position)
              for (let j = 0; j < num_channels; ++j)
                for (let i = 0; i < num_samples; ++i)
                  output[0][j][i] = frames[this.position + i * num_channels + j];
            else {
              let part_one = this.max_num_frames - this.position;
              let part_two = num_frames          - part_one;

              for (let j = 0; j < num_channels; ++j) {
                for (let i = 0; i < part_one; ++i)
                  output[0][j][i] = frames[this.position + i * num_channels + j];
                for (let i = 0; i < part_two; ++i)
                  output[0][j][part_one + i] = frames[i * num_channels + j];
              }
            }

            this.position = (this.position + num_frames) % this.max_num_frames;
            return true;
          }
        }
      );
    </script>
    <script type="text/javascript">
      function key_from_code(code) {
        switch (code) {
          case "Backspace":    return 8;
          case "Tab":          return 9;
          case "Enter":        return 10;
          case "ControlLeft":  return 11;
          case "ControlRight": return 12;
          case "ShiftLeft":    return 13;
          case "ShiftRight":   return 14;
          case "AltLeft":      return 15;
          case "AltRight":     return 16;
          case "ArrowLeft":    return 17;
          case "ArrowRight":   return 18;
          case "ArrowUp":      return 19;
          case "ArrowDown":    return 20;
          case "Pause":        return 21;
          case "Insert":       return 22;
          case "Home":         return 23;
          case "End":          return 24;
          case "PageUp":       return 25;
          case "PageDown":     return 26;
          case "Escape":       return 27;
          case "PrintScreen":  return 28;
          case "Space":        return 32;
          case "MetaLeft":     return 33;
          case "MetaRight":    return 34;
          case "Quote":        return 39;
          case "Comma":        return 44;
          case "Minus":        return 45;
          case "Period":       return 46;
          case "Slash":        return 47;
          case "Digit0":       return 48;
          case "Digit1":       return 49;
          case "Digit2":       return 50;
          case "Digit3":       return 51;
          case "Digit4":       return 52;
          case "Digit5":       return 53;
          case "Digit6":       return 54;
          case "Digit7":       return 55;
          case "Digit8":       return 56;
          case "Digit9":       return 57;
          case "Semicolon":    return 59;
          case "Equal":        return 61;
          case "BracketLeft":  return 91;
          case "Backslash":    return 92;
          case "BracketRight": return 93;
          case "Backquote":    return 96;
          case "KeyA":         return 97;
          case "KeyB":         return 98;
          case "KeyC":         return 99;
          case "KeyD":         return 100;
          case "KeyE":         return 101;
          case "KeyF":         return 102;
          case "KeyG":         return 103;
          case "KeyH":         return 104;
          case "KeyI":         return 105;
          case "KeyJ":         return 106;
          case "KeyK":         return 107;
          case "KeyL":         return 108;
          case "KeyM":         return 109;
          case "KeyN":         return 110;
          case "KeyO":         return 111;
          case "KeyP":         return 112;
          case "KeyQ":         return 113;
          case "KeyR":         return 114;
          case "KeyS":         return 115;
          case "KeyT":         return 116;
          case "KeyU":         return 117;
          case "KeyV":         return 118;
          case "KeyW":         return 119;
          case "KeyX":         return 120;
          case "KeyY":         return 121;
          case "KeyZ":         return 122;
          case "Delete":       return 127;
          case "F1":           return 145;
          case "F2":           return 146;
          case "F3":           return 147;
          case "F4":           return 148;
          case "F5":           return 149;
          case "F6":           return 150;
          case "F7":           return 151;
          case "F8":           return 152;
          case "F9":           return 153;
          case "F10":          return 154;
          case "F11":          return 155;
          case "F12":          return 156;
          case "F13":          return 157;
          case "F14":          return 158;
          case "F15":          return 159;
          case "F16":          return 160;
          case "F17":          return 161;
          case "F18":          return 162;
          case "F19":          return 163;
          case "F20":          return 164;
          case "F21":          return 165;
          case "F22":          return 166;
          case "F23":          return 167;
          case "F24":          return 168;
        }
        return 0;
      };

      function mod_from_event(ev) {
        let mod = 0;
        if (ev.ctrlKey)  mod |= 1;
        if (ev.shiftKey) mod |= 2;
        if (ev.altKey)   mod |= 4;
        if (ev.metaKey)  mod |= 8;
        return mod;
      };

      function string_from_memory(bytes, offset) {
        let len = 0;
        while (bytes[offset + len] != 0)
          ++len;
        return new TextDecoder("utf8").decode(bytes.subarray(offset, offset + len));
      }

      async function run(attrs) {
        let wait_for_events = false;
        let sleep_duration  = 0;

        let canvas;
        let program;
        let memory;
        let pixels_address;
        let context;
        let animation_frame;

        let sound_ready = false;
        let sound_context;
        let sound_init;
        let sound_node;
        let sound_num_channels;
        let sound_buffer_address;
        let sound_max_num_frames;

        let sound_shared_ring;
        let sound_position = 0;

        canvas  = attrs.canvas;
        context = canvas.getContext("2d");

        sound_init = async () => {
          if (sound_ready || sound_context !== undefined)
            return;

          sound_context = new AudioContext({
            sampleRate : program.instance.exports.js_sample_rate(),
          });

          let blob = new Blob(
            [ document.querySelector("script[type=worklet]").innerText ],
            { type : "application/javascript", }
          );

          await sound_context.audioWorklet.addModule(URL.createObjectURL(blob));

          sound_num_channels   = program.instance.exports.js_num_channels();
          sound_max_num_frames = program.instance.exports.js_max_num_audio_frames();
          sound_buffer_address = program.instance.exports.js_sound_buffer();

          sound_shared_ring = new SharedArrayBuffer(sound_max_num_frames * 4);

          sound_node = new AudioWorkletNode(
            sound_context,
            "Sound_Ring",
            { numberOfInputs     :                             0,
              outputChannelCount : [        sound_num_channels ],
              processorOptions   : { ring : sound_shared_ring, }, }
          );

          sound_node.connect(sound_context.destination);

          program.instance.exports.js_sound_sync();

          sound_ready = true;
        };

        program = await WebAssembly.instantiateStreaming(
          attrs.wasm,
          {
            "wasi_snapshot_preview1" : {
              clock_time_get : () => { return Date.now(); },
              args_sizes_get : () => { throw new Error("Unexpected args_sizes_get call"); },
              args_get       : () => { throw new Error("Unexpected args_get call"); },
              proc_exit      : () => { throw new Error("Unexpected proc_exit call"); },
              fd_close       : () => { throw new Error("Unexpected fd_close call"); },
              fd_write       : () => { throw new Error("Unexpected fd_write call"); },
              fd_seek        : () => { throw new Error("Unexpected fd_seek call"); },
            },
            "env" : {
              p_init : () => {
                program.instance.exports.js_init();
                memory         = new Uint8Array(program.instance.exports.memory.buffer);
                pixels_address = program.instance.exports.js_pixels();
                document.title = string_from_memory(memory, program.instance.exports.js_title());
              },
              p_render_frame_impl : () => {
                let data = new ImageData(
                  new Uint8ClampedArray(
                    memory.subarray(
                      pixels_address,
                      pixels_address + 4 * canvas.width * canvas.height
                    )
                  ),
                  canvas.width,
                  canvas.height
                );

                context.putImageData(data, 0, 0);
              },
              p_clipboard_write : (size, text) => {
                navigator.clipboard.writeText(
                  new TextDecoder().decode(memory.subarray(text, text + size))
                ).catch((e) => { console.error(e); });
              },
              p_cleanup          : ()     => {},
              p_wait_events_impl : ()     => { wait_for_events = true; },
              p_sleep_for_impl   : (time) => { sleep_duration += time; },
              p_time_impl        : Date.now,

              p_handle_audio_impl : (samples_elapsed) => {
                if (!sound_ready)
                  return;

                let num_frames = samples_elapsed * sound_num_channels;

                if (num_frames > sound_max_num_frames) {
                  console.error("Sound buffer overflow");
                  return;
                }

                let dst = new Float32Array(sound_shared_ring);
                let src = new Float32Array(memory.subarray(sound_buffer_address, sound_buffer_address + sound_max_num_frames * 4));

                if (num_frames <= sound_max_num_frames - sound_position)
                  for (let i = 0; i < num_frames; ++i) {
                    dst[sound_position + i] = src[sound_position + i];
                    src[sound_position + i] = 0.0;
                  }
                else {
                  let part_one = sound_max_num_frames - sound_position;
                  let part_two = num_frames           - part_one;

                  for (let i = 0; i < part_one; ++i) {
                    dst[sound_position + i] = src[sound_position + i];
                    src[sound_position + i] = 0.0;
                  }
                  for (let i = 0; i < part_two; ++i) {
                    dst[i] = src[i];
                    src[i] = 0.0;
                  }
                }

                sound_position = (sound_position + samples_elapsed * sound_num_channels) % sound_max_num_frames;
              },

              floor : Math.floor,
              ceil  : Math.ceil,
              sqrt  : Math.sqrt,
              pow   : Math.pow,
              log   : Math.log,
              log2  : Math.log2,
              log10 : Math.log10,
              exp   : Math.exp,
              sin   : Math.sin,
              cos   : Math.cos,
              tan   : Math.tan,
              asin  : Math.asin,
              acos  : Math.acos,
              atan  : Math.atan,
              atan2 : Math.atan2,

              memset : (dst, val, num) => { program.instance.exports.js_memset(dst, val, num); },
              memcpy : (dst, src, num) => { program.instance.exports.js_memcpy(dst, src, num); },
            },
          }
        );

        program.instance.exports.js_main(document.location.href);

        animation_frame = (time) => {
          if (attrs.fit_window) {
            canvas.width  = window.innerWidth;
            canvas.height = window.innerHeight;
          }

          wait_for_events = false;
          program.instance.exports.js_frame(canvas.width, canvas.height);

          if (!wait_for_events) {
            if (sleep_duration > 0) {
              let timeout    = sleep_duration;
              sleep_duration = 0;
              setTimeout(() => {
                window.requestAnimationFrame(animation_frame);
              }, timeout);
            } else
              window.requestAnimationFrame(animation_frame);
          }
        };

        window.addEventListener("resize", (ev) => {
          window.requestAnimationFrame(animation_frame);
        });

        canvas.addEventListener("mousedown", (ev) => {
          sound_init();
          program.instance.exports.js_mousedown(ev.buttons);
          window.requestAnimationFrame(animation_frame);
        });

        canvas.addEventListener("mouseup", (ev) => {
          program.instance.exports.js_mouseup(ev.buttons);
          window.requestAnimationFrame(animation_frame);
        });

        canvas.addEventListener("mousemove", (ev) => {
          program.instance.exports.js_mousemove(ev.clientX, ev.clientY);
          window.requestAnimationFrame(animation_frame);
        });

        window.addEventListener("keydown", (ev) => {
          ev.preventDefault();
          if (!ev.repeat) {
            let mod = mod_from_event(ev);
            let key = key_from_code(ev.code);
            if (key != 0)
              program.instance.exports.js_keydown(key, mod);
            window.requestAnimationFrame(animation_frame);
          }
        });

        window.addEventListener("keyup", (ev) => {
          ev.preventDefault();
          if (!ev.repeat) {
            let mod = mod_from_event(ev);
            let key = key_from_code(ev.code);
            if (key != 0)
              program.instance.exports.js_keyup(key, mod);
            window.requestAnimationFrame(animation_frame);
          }
        });

        window.requestAnimationFrame(animation_frame);
      }

      run({
        canvas     : document.getElementById("frame"),
        wasm       : fetch("index.wasm"),
        fit_window : true,
      }).catch((e) => console.error(e));
    </script>
  </body>
</html>