doom-engine.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /**
  2. * DOOM Engine - WebAssembly wrapper for doomgeneric
  3. */
  4. import { existsSync, readFileSync } from "node:fs";
  5. import { createRequire } from "node:module";
  6. import { dirname, join } from "node:path";
  7. import { fileURLToPath } from "node:url";
  8. export interface DoomModule {
  9. _doomgeneric_Create: (argc: number, argv: number) => void;
  10. _doomgeneric_Tick: () => void;
  11. _DG_GetFrameBuffer: () => number;
  12. _DG_GetScreenWidth: () => number;
  13. _DG_GetScreenHeight: () => number;
  14. _DG_PushKeyEvent: (pressed: number, key: number) => void;
  15. _malloc: (size: number) => number;
  16. _free: (ptr: number) => void;
  17. HEAPU8: Uint8Array;
  18. HEAPU32: Uint32Array;
  19. FS_createDataFile: (parent: string, name: string, data: number[], canRead: boolean, canWrite: boolean) => void;
  20. FS_createPath: (parent: string, path: string, canRead: boolean, canWrite: boolean) => string;
  21. setValue: (ptr: number, value: number, type: string) => void;
  22. getValue: (ptr: number, type: string) => number;
  23. }
  24. export class DoomEngine {
  25. private module: DoomModule | null = null;
  26. private frameBufferPtr: number = 0;
  27. private initialized = false;
  28. private wadPath: string;
  29. private _width = 640;
  30. private _height = 400;
  31. constructor(wadPath: string) {
  32. this.wadPath = wadPath;
  33. }
  34. get width(): number {
  35. return this._width;
  36. }
  37. get height(): number {
  38. return this._height;
  39. }
  40. async init(): Promise<void> {
  41. // Locate WASM build
  42. const __dirname = dirname(fileURLToPath(import.meta.url));
  43. const buildDir = join(__dirname, "doom", "build");
  44. const doomJsPath = join(buildDir, "doom.js");
  45. if (!existsSync(doomJsPath)) {
  46. throw new Error(`WASM not found at ${doomJsPath}. Run ./doom/build.sh first`);
  47. }
  48. // Read WAD file
  49. const wadData = readFileSync(this.wadPath);
  50. const wadArray = Array.from(new Uint8Array(wadData));
  51. // Load WASM module - eval to bypass jiti completely
  52. const doomJsCode = readFileSync(doomJsPath, "utf-8");
  53. const moduleExports: { exports: unknown } = { exports: {} };
  54. const nativeRequire = createRequire(doomJsPath);
  55. const moduleFunc = new Function("module", "exports", "__dirname", "__filename", "require", doomJsCode);
  56. moduleFunc(moduleExports, moduleExports.exports, buildDir, doomJsPath, nativeRequire);
  57. const createDoomModule = moduleExports.exports as (config: unknown) => Promise<DoomModule>;
  58. const moduleConfig = {
  59. locateFile: (path: string) => {
  60. if (path.endsWith(".wasm")) {
  61. return join(buildDir, path);
  62. }
  63. return path;
  64. },
  65. print: () => {},
  66. printErr: () => {},
  67. preRun: [
  68. (module: DoomModule) => {
  69. // Create /doom directory and add WAD
  70. module.FS_createPath("/", "doom", true, true);
  71. module.FS_createDataFile("/doom", "doom1.wad", wadArray, true, false);
  72. },
  73. ],
  74. };
  75. this.module = await createDoomModule(moduleConfig);
  76. if (!this.module) {
  77. throw new Error("Failed to initialize DOOM module");
  78. }
  79. // Initialize DOOM
  80. this.initDoom();
  81. // Get framebuffer info
  82. this.frameBufferPtr = this.module._DG_GetFrameBuffer();
  83. this._width = this.module._DG_GetScreenWidth();
  84. this._height = this.module._DG_GetScreenHeight();
  85. this.initialized = true;
  86. }
  87. private initDoom(): void {
  88. if (!this.module) return;
  89. const args = ["doom", "-iwad", "/doom/doom1.wad"];
  90. const argPtrs: number[] = [];
  91. for (const arg of args) {
  92. const ptr = this.module._malloc(arg.length + 1);
  93. for (let i = 0; i < arg.length; i++) {
  94. this.module.setValue(ptr + i, arg.charCodeAt(i), "i8");
  95. }
  96. this.module.setValue(ptr + arg.length, 0, "i8");
  97. argPtrs.push(ptr);
  98. }
  99. const argvPtr = this.module._malloc(argPtrs.length * 4);
  100. for (let i = 0; i < argPtrs.length; i++) {
  101. this.module.setValue(argvPtr + i * 4, argPtrs[i]!, "i32");
  102. }
  103. this.module._doomgeneric_Create(args.length, argvPtr);
  104. for (const ptr of argPtrs) {
  105. this.module._free(ptr);
  106. }
  107. this.module._free(argvPtr);
  108. }
  109. /**
  110. * Run one game tick
  111. */
  112. tick(): void {
  113. if (!this.module || !this.initialized) return;
  114. this.module._doomgeneric_Tick();
  115. }
  116. /**
  117. * Get current frame as RGBA pixel data
  118. * DOOM outputs ARGB, we convert to RGBA
  119. */
  120. getFrameRGBA(): Uint8Array {
  121. if (!this.module || !this.initialized) {
  122. return new Uint8Array(this._width * this._height * 4);
  123. }
  124. const pixels = this._width * this._height;
  125. const buffer = new Uint8Array(pixels * 4);
  126. for (let i = 0; i < pixels; i++) {
  127. const argb = this.module.getValue(this.frameBufferPtr + i * 4, "i32");
  128. const offset = i * 4;
  129. buffer[offset + 0] = (argb >> 16) & 0xff; // R
  130. buffer[offset + 1] = (argb >> 8) & 0xff; // G
  131. buffer[offset + 2] = argb & 0xff; // B
  132. buffer[offset + 3] = 255; // A
  133. }
  134. return buffer;
  135. }
  136. /**
  137. * Push a key event
  138. */
  139. pushKey(pressed: boolean, key: number): void {
  140. if (!this.module || !this.initialized) return;
  141. this.module._DG_PushKeyEvent(pressed ? 1 : 0, key);
  142. }
  143. isInitialized(): boolean {
  144. return this.initialized;
  145. }
  146. }