Back to DOOM
SOURCE / PINNED RELEASE

Made of little things.

DOOM

Release
f8a5db646fdc…
Author-recorded commit
d8e055796675…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-37af437f0e6

Archive hash verified: 66555ff880270ca9…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/engine.ts
import wasmData from '../vendor/doom/doom.wasm?inline';

export const KEY = {
  left: 172,
  right: 174,
  up: 173,
  down: 175,
  strafeLeft: 160,
  strafeRight: 161,
  fire: 163,
  use: 162,
  shift: 182,
  map: 9,
  escape: 27,
  enter: 13,
  backspace: 127,
  yes: 121,
  no: 110,
  save: 188,
  load: 189,
} as const;
export type Action = keyof typeof KEY;
interface DoomExports extends WebAssembly.Exports {
  memory: WebAssembly.Memory;
  initGame: () => void;
  tickGame: () => void;
  reportKeyDown: (key: number) => void;
  reportKeyUp: (key: number) => void;
}
export function toBase64(bytes: Uint8Array): string {
  let text = '';
  for (let i = 0; i < bytes.length; i += 8192)
    text += String.fromCharCode(...bytes.subarray(i, i + 8192));
  return btoa(text);
}
export function fromBase64(value: string): Uint8Array<ArrayBuffer> {
  return Uint8Array.from(atob(value), (c) => c.charCodeAt(0));
}
let compiled: Promise<WebAssembly.Module> | undefined;
export class DoomEngine {
  private api!: DoomExports;
  private frame!: ImageData;
  private timer = 0;
  private pausedAt = performance.now();
  private timeOffset = 0;
  private held = new Map<number, Set<string>>();
  private disposed = false;
  private serial: Promise<void> = Promise.resolve();
  frames = 0;
  constructor(
    private canvas: HTMLCanvasElement,
    readonly saves: Map<number, Uint8Array>,
    private onSave: (slot: number, bytes: Uint8Array) => void,
    private onError: (message: string) => void,
  ) {}
  async initialize() {
    compiled ??= WebAssembly.compile(
      fromBase64(wasmData.slice(wasmData.indexOf(',') + 1)),
    );
    const context = this.canvas.getContext('2d', { alpha: false });
    if (!context) throw new Error('Canvas rendering is unavailable.');
    const readText = (ptr: number, length: number) =>
      new TextDecoder().decode(
        new Uint8Array(this.api.memory.buffer, ptr, length),
      );
    const instance = await WebAssembly.instantiate(await compiled, {
      loading: {
        onGameInit: (w: number, h: number) => {
          this.canvas.width = w;
          this.canvas.height = h;
          this.frame = context.createImageData(w, h);
        },
        wadSizes: () => {},
        readWads: () => {},
      },
      runtimeControl: {
        timeInMilliseconds: () =>
          BigInt(Math.floor(performance.now() - this.timeOffset)),
      },
      ui: {
        drawFrame: (ptr: number) => {
          const source = new Uint8Array(
              this.api.memory.buffer,
              ptr,
              this.frame.data.length,
            ),
            target = this.frame.data;
          for (let i = 0; i < target.length; i += 4) {
            target[i] = source[i + 2];
            target[i + 1] = source[i + 1];
            target[i + 2] = source[i];
            target[i + 3] = 255;
          }
          context.putImageData(this.frame, 0, 0);
          this.frames++;
        },
      },
      console: {
        onInfoMessage: () => {},
        onErrorMessage: (ptr: number, length: number) =>
          this.onError(readText(ptr, length)),
      },
      gameSaving: {
        sizeOfSaveGame: (slot: number) => this.saves.get(slot)?.length ?? 0,
        readSaveGame: (slot: number, ptr: number) => {
          const data = this.saves.get(slot);
          if (!data) return 0;
          new Uint8Array(this.api.memory.buffer, ptr, data.length).set(data);
          return data.length;
        },
        writeSaveGame: (slot: number, ptr: number, length: number) => {
          if (slot < 0 || slot > 5 || length > 96000) return 0;
          const data = new Uint8Array(
            this.api.memory.buffer,
            ptr,
            length,
          ).slice();
          this.saves.set(slot, data);
          this.onSave(slot, data);
          return length;
        },
      },
    });
    this.api = instance.exports as DoomExports;
    this.api.initGame();
    this.api.tickGame();
    this.pausedAt = performance.now();
  }
  resume() {
    if (this.timer || this.disposed) return;
    this.timeOffset += performance.now() - this.pausedAt;
    this.timer = window.setInterval(() => {
      try {
        this.api.tickGame();
      } catch (error) {
        this.pause();
        this.onError(String(error));
      }
    }, 1000 / 35);
  }
  pause() {
    this.releaseAll();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = 0;
      this.pausedAt = performance.now();
    }
  }
  setKey(key: number, pressed: boolean, source = 'keyboard') {
    if (this.disposed) return;
    const owners = this.held.get(key) ?? new Set<string>();
    if (pressed) owners.add(source);
    else owners.delete(source);
    if (owners.size) {
      this.held.set(key, owners);
      this.api.reportKeyDown(key);
    } else {
      this.held.delete(key);
      this.api.reportKeyUp(key);
    }
  }
  releaseAll() {
    if (!this.api) return;
    for (const key of this.held.keys()) this.api.reportKeyUp(key);
    this.held.clear();
  }
  tap(key: number) {
    return this.sequence([key]);
  }
  sequence(keys: number[]) {
    this.serial = this.serial.then(async () => {
      for (const key of keys) {
        if (this.disposed) return;
        this.setKey(key, true, 'sequence');
        await new Promise((r) => setTimeout(r, 65));
        this.setKey(key, false, 'sequence');
        await new Promise((r) => setTimeout(r, 65));
      }
    });
    return this.serial;
  }
  dispose() {
    this.pause();
    this.disposed = true;
  }
}