quake2ts 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/apps/viewer/dist/browser/index.global.js +2 -0
  2. package/apps/viewer/dist/browser/index.global.js.map +1 -0
  3. package/apps/viewer/dist/cjs/index.cjs +1087 -0
  4. package/apps/viewer/dist/cjs/index.cjs.map +1 -0
  5. package/apps/viewer/dist/esm/index.js +1060 -0
  6. package/apps/viewer/dist/esm/index.js.map +1 -0
  7. package/apps/viewer/dist/tsconfig.tsbuildinfo +1 -0
  8. package/apps/viewer/dist/types/index.d.ts +7 -0
  9. package/apps/viewer/dist/types/index.d.ts.map +1 -0
  10. package/package.json +107 -0
  11. package/packages/client/dist/browser/index.global.js +2 -0
  12. package/packages/client/dist/browser/index.global.js.map +1 -0
  13. package/packages/client/dist/cjs/index.cjs +57 -0
  14. package/packages/client/dist/cjs/index.cjs.map +1 -0
  15. package/packages/client/dist/esm/index.js +32 -0
  16. package/packages/client/dist/esm/index.js.map +1 -0
  17. package/packages/client/dist/tsconfig.tsbuildinfo +1 -0
  18. package/packages/client/dist/types/index.d.ts +14 -0
  19. package/packages/client/dist/types/index.d.ts.map +1 -0
  20. package/packages/engine/dist/browser/index.global.js +2 -0
  21. package/packages/engine/dist/browser/index.global.js.map +1 -0
  22. package/packages/engine/dist/cjs/index.cjs +1823 -0
  23. package/packages/engine/dist/cjs/index.cjs.map +1 -0
  24. package/packages/engine/dist/esm/index.js +1764 -0
  25. package/packages/engine/dist/esm/index.js.map +1 -0
  26. package/packages/engine/dist/tsconfig.tsbuildinfo +1 -0
  27. package/packages/engine/dist/types/assets/browserIngestion.d.ts +7 -0
  28. package/packages/engine/dist/types/assets/browserIngestion.d.ts.map +1 -0
  29. package/packages/engine/dist/types/assets/bsp.d.ts +157 -0
  30. package/packages/engine/dist/types/assets/bsp.d.ts.map +1 -0
  31. package/packages/engine/dist/types/assets/cache.d.ts +17 -0
  32. package/packages/engine/dist/types/assets/cache.d.ts.map +1 -0
  33. package/packages/engine/dist/types/assets/ingestion.d.ts +31 -0
  34. package/packages/engine/dist/types/assets/ingestion.d.ts.map +1 -0
  35. package/packages/engine/dist/types/assets/md2.d.ts +73 -0
  36. package/packages/engine/dist/types/assets/md2.d.ts.map +1 -0
  37. package/packages/engine/dist/types/assets/pak.d.ts +28 -0
  38. package/packages/engine/dist/types/assets/pak.d.ts.map +1 -0
  39. package/packages/engine/dist/types/assets/vfs.d.ts +23 -0
  40. package/packages/engine/dist/types/assets/vfs.d.ts.map +1 -0
  41. package/packages/engine/dist/types/configstrings.d.ts +34 -0
  42. package/packages/engine/dist/types/configstrings.d.ts.map +1 -0
  43. package/packages/engine/dist/types/cvars.d.ts +43 -0
  44. package/packages/engine/dist/types/cvars.d.ts.map +1 -0
  45. package/packages/engine/dist/types/host.d.ts +42 -0
  46. package/packages/engine/dist/types/host.d.ts.map +1 -0
  47. package/packages/engine/dist/types/index.d.ts +37 -0
  48. package/packages/engine/dist/types/index.d.ts.map +1 -0
  49. package/packages/engine/dist/types/loop.d.ts +40 -0
  50. package/packages/engine/dist/types/loop.d.ts.map +1 -0
  51. package/packages/engine/dist/types/render/bsp.d.ts +49 -0
  52. package/packages/engine/dist/types/render/bsp.d.ts.map +1 -0
  53. package/packages/engine/dist/types/render/context.d.ts +36 -0
  54. package/packages/engine/dist/types/render/context.d.ts.map +1 -0
  55. package/packages/engine/dist/types/render/resources.d.ts +56 -0
  56. package/packages/engine/dist/types/render/resources.d.ts.map +1 -0
  57. package/packages/engine/dist/types/render/shaderProgram.d.ts +18 -0
  58. package/packages/engine/dist/types/render/shaderProgram.d.ts.map +1 -0
  59. package/packages/engine/dist/types/runtime.d.ts +15 -0
  60. package/packages/engine/dist/types/runtime.d.ts.map +1 -0
  61. package/packages/game/dist/browser/index.global.js +2 -0
  62. package/packages/game/dist/browser/index.global.js.map +1 -0
  63. package/packages/game/dist/cjs/index.cjs +758 -0
  64. package/packages/game/dist/cjs/index.cjs.map +1 -0
  65. package/packages/game/dist/esm/index.js +725 -0
  66. package/packages/game/dist/esm/index.js.map +1 -0
  67. package/packages/game/dist/tsconfig.tsbuildinfo +1 -0
  68. package/packages/game/dist/types/entities/entity.d.ts +92 -0
  69. package/packages/game/dist/types/entities/entity.d.ts.map +1 -0
  70. package/packages/game/dist/types/entities/index.d.ts +3 -0
  71. package/packages/game/dist/types/entities/index.d.ts.map +1 -0
  72. package/packages/game/dist/types/entities/pool.d.ts +18 -0
  73. package/packages/game/dist/types/entities/pool.d.ts.map +1 -0
  74. package/packages/game/dist/types/entities/system.d.ts +18 -0
  75. package/packages/game/dist/types/entities/system.d.ts.map +1 -0
  76. package/packages/game/dist/types/entities/thinkScheduler.d.ts +8 -0
  77. package/packages/game/dist/types/entities/thinkScheduler.d.ts.map +1 -0
  78. package/packages/game/dist/types/index.d.ts +26 -0
  79. package/packages/game/dist/types/index.d.ts.map +1 -0
  80. package/packages/game/dist/types/level.d.ts +14 -0
  81. package/packages/game/dist/types/level.d.ts.map +1 -0
  82. package/packages/game/dist/types/loop.d.ts +29 -0
  83. package/packages/game/dist/types/loop.d.ts.map +1 -0
  84. package/packages/shared/dist/browser/index.global.js +2 -0
  85. package/packages/shared/dist/browser/index.global.js.map +1 -0
  86. package/packages/shared/dist/cjs/index.cjs +2793 -0
  87. package/packages/shared/dist/cjs/index.cjs.map +1 -0
  88. package/packages/shared/dist/esm/index.js +2594 -0
  89. package/packages/shared/dist/esm/index.js.map +1 -0
  90. package/packages/shared/dist/tsconfig.tsbuildinfo +1 -0
  91. package/packages/shared/dist/types/bsp/collision.d.ts +112 -0
  92. package/packages/shared/dist/types/bsp/collision.d.ts.map +1 -0
  93. package/packages/shared/dist/types/bsp/contents.d.ts +71 -0
  94. package/packages/shared/dist/types/bsp/contents.d.ts.map +1 -0
  95. package/packages/shared/dist/types/index.d.ts +25 -0
  96. package/packages/shared/dist/types/index.d.ts.map +1 -0
  97. package/packages/shared/dist/types/math/angles.d.ts +17 -0
  98. package/packages/shared/dist/types/math/angles.d.ts.map +1 -0
  99. package/packages/shared/dist/types/math/color.d.ts +12 -0
  100. package/packages/shared/dist/types/math/color.d.ts.map +1 -0
  101. package/packages/shared/dist/types/math/random.d.ts +48 -0
  102. package/packages/shared/dist/types/math/random.d.ts.map +1 -0
  103. package/packages/shared/dist/types/math/vec3.d.ts +76 -0
  104. package/packages/shared/dist/types/math/vec3.d.ts.map +1 -0
  105. package/packages/shared/dist/types/pmove/categorize.d.ts +36 -0
  106. package/packages/shared/dist/types/pmove/categorize.d.ts.map +1 -0
  107. package/packages/shared/dist/types/pmove/constants.d.ts +75 -0
  108. package/packages/shared/dist/types/pmove/constants.d.ts.map +1 -0
  109. package/packages/shared/dist/types/pmove/currents.d.ts +58 -0
  110. package/packages/shared/dist/types/pmove/currents.d.ts.map +1 -0
  111. package/packages/shared/dist/types/pmove/dimensions.d.ts +14 -0
  112. package/packages/shared/dist/types/pmove/dimensions.d.ts.map +1 -0
  113. package/packages/shared/dist/types/pmove/duck.d.ts +39 -0
  114. package/packages/shared/dist/types/pmove/duck.d.ts.map +1 -0
  115. package/packages/shared/dist/types/pmove/fly.d.ts +34 -0
  116. package/packages/shared/dist/types/pmove/fly.d.ts.map +1 -0
  117. package/packages/shared/dist/types/pmove/jump.d.ts +26 -0
  118. package/packages/shared/dist/types/pmove/jump.d.ts.map +1 -0
  119. package/packages/shared/dist/types/pmove/move.d.ts +58 -0
  120. package/packages/shared/dist/types/pmove/move.d.ts.map +1 -0
  121. package/packages/shared/dist/types/pmove/pmove.d.ts +36 -0
  122. package/packages/shared/dist/types/pmove/pmove.d.ts.map +1 -0
  123. package/packages/shared/dist/types/pmove/slide.d.ts +63 -0
  124. package/packages/shared/dist/types/pmove/slide.d.ts.map +1 -0
  125. package/packages/shared/dist/types/pmove/snap.d.ts +40 -0
  126. package/packages/shared/dist/types/pmove/snap.d.ts.map +1 -0
  127. package/packages/shared/dist/types/pmove/special.d.ts +39 -0
  128. package/packages/shared/dist/types/pmove/special.d.ts.map +1 -0
  129. package/packages/shared/dist/types/pmove/stuck.d.ts +21 -0
  130. package/packages/shared/dist/types/pmove/stuck.d.ts.map +1 -0
  131. package/packages/shared/dist/types/pmove/types.d.ts +48 -0
  132. package/packages/shared/dist/types/pmove/types.d.ts.map +1 -0
  133. package/packages/shared/dist/types/pmove/view.d.ts +19 -0
  134. package/packages/shared/dist/types/pmove/view.d.ts.map +1 -0
  135. package/packages/shared/dist/types/pmove/water.d.ts +21 -0
  136. package/packages/shared/dist/types/pmove/water.d.ts.map +1 -0
  137. package/packages/shared/dist/types/protocol/configstrings.d.ts +51 -0
  138. package/packages/shared/dist/types/protocol/configstrings.d.ts.map +1 -0
  139. package/packages/shared/dist/types/protocol/cvar.d.ts +15 -0
  140. package/packages/shared/dist/types/protocol/cvar.d.ts.map +1 -0
  141. package/packages/tools/dist/browser/index.global.js +2 -0
  142. package/packages/tools/dist/browser/index.global.js.map +1 -0
  143. package/packages/tools/dist/cjs/index.cjs +33 -0
  144. package/packages/tools/dist/cjs/index.cjs.map +1 -0
  145. package/packages/tools/dist/esm/index.js +8 -0
  146. package/packages/tools/dist/esm/index.js.map +1 -0
  147. package/packages/tools/dist/tsconfig.tsbuildinfo +1 -0
  148. package/packages/tools/dist/types/index.d.ts +7 -0
  149. package/packages/tools/dist/types/index.d.ts.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/index.ts","../../../../packages/client/src/index.ts","../../../../packages/engine/src/loop.ts","../../../../packages/engine/src/host.ts","../../../../packages/shared/src/math/vec3.ts","../../../../packages/shared/src/math/angles.ts","../../../../packages/shared/src/math/color.ts","../../../../packages/shared/src/math/random.ts","../../../../packages/shared/src/bsp/contents.ts","../../../../packages/shared/src/bsp/collision.ts","../../../../packages/shared/src/protocol/cvar.ts","../../../../packages/shared/src/protocol/configstrings.ts","../../../../packages/shared/src/pmove/constants.ts","../../../../packages/shared/src/pmove/pmove.ts","../../../../packages/shared/src/pmove/slide.ts","../../../../packages/shared/src/pmove/stuck.ts","../../../../packages/shared/src/pmove/currents.ts","../../../../packages/shared/src/pmove/fly.ts","../../../../packages/shared/src/pmove/water.ts","../../../../packages/shared/src/pmove/jump.ts","../../../../packages/shared/src/pmove/dimensions.ts","../../../../packages/shared/src/pmove/duck.ts","../../../../packages/shared/src/pmove/categorize.ts","../../../../packages/shared/src/pmove/move.ts","../../../../packages/shared/src/pmove/special.ts","../../../../packages/shared/src/pmove/snap.ts","../../../../packages/shared/src/pmove/view.ts","../../../../packages/engine/src/configstrings.ts","../../../../packages/engine/src/runtime.ts","../../../../packages/engine/src/cvars.ts","../../../../packages/engine/src/assets/pak.ts","../../../../packages/engine/src/assets/vfs.ts","../../../../packages/engine/src/assets/ingestion.ts","../../../../packages/engine/src/assets/cache.ts","../../../../packages/engine/src/assets/browserIngestion.ts","../../../../packages/engine/src/assets/md2.ts","../../../../packages/engine/src/render/context.ts","../../../../packages/engine/src/render/shaderProgram.ts","../../../../packages/engine/src/render/resources.ts","../../../../packages/engine/src/render/bsp.ts","../../../../packages/engine/src/index.ts","../../../../packages/shared/src/math/vec3.ts","../../../../packages/shared/src/math/angles.ts","../../../../packages/shared/src/math/color.ts","../../../../packages/shared/src/math/random.ts","../../../../packages/shared/src/bsp/contents.ts","../../../../packages/shared/src/bsp/collision.ts","../../../../packages/shared/src/protocol/cvar.ts","../../../../packages/shared/src/protocol/configstrings.ts","../../../../packages/shared/src/pmove/constants.ts","../../../../packages/shared/src/pmove/pmove.ts","../../../../packages/shared/src/pmove/slide.ts","../../../../packages/shared/src/pmove/stuck.ts","../../../../packages/shared/src/pmove/currents.ts","../../../../packages/shared/src/pmove/fly.ts","../../../../packages/shared/src/pmove/water.ts","../../../../packages/shared/src/pmove/jump.ts","../../../../packages/shared/src/pmove/dimensions.ts","../../../../packages/shared/src/pmove/duck.ts","../../../../packages/shared/src/pmove/categorize.ts","../../../../packages/shared/src/pmove/move.ts","../../../../packages/shared/src/pmove/special.ts","../../../../packages/shared/src/pmove/snap.ts","../../../../packages/shared/src/pmove/view.ts","../../../../packages/game/src/entities/entity.ts","../../../../packages/game/src/entities/pool.ts","../../../../packages/game/src/entities/thinkScheduler.ts","../../../../packages/game/src/entities/system.ts","../../../../packages/game/src/loop.ts","../../../../packages/game/src/level.ts","../../../../packages/game/src/index.ts","../../../../packages/shared/src/math/vec3.ts","../../../../packages/shared/src/math/angles.ts","../../../../packages/shared/src/math/color.ts","../../../../packages/shared/src/math/random.ts","../../../../packages/shared/src/bsp/contents.ts","../../../../packages/shared/src/bsp/collision.ts","../../../../packages/shared/src/protocol/cvar.ts","../../../../packages/shared/src/protocol/configstrings.ts","../../../../packages/shared/src/pmove/constants.ts","../../../../packages/shared/src/pmove/pmove.ts","../../../../packages/shared/src/pmove/slide.ts","../../../../packages/shared/src/pmove/stuck.ts","../../../../packages/shared/src/pmove/currents.ts","../../../../packages/shared/src/pmove/fly.ts","../../../../packages/shared/src/pmove/water.ts","../../../../packages/shared/src/pmove/jump.ts","../../../../packages/shared/src/pmove/dimensions.ts","../../../../packages/shared/src/pmove/duck.ts","../../../../packages/shared/src/pmove/categorize.ts","../../../../packages/shared/src/pmove/move.ts","../../../../packages/shared/src/pmove/special.ts","../../../../packages/shared/src/pmove/snap.ts","../../../../packages/shared/src/pmove/view.ts"],"sourcesContent":["import { createClient } from '@quake2ts/client';\nimport { createEngine, createEngineRuntime } from '@quake2ts/engine';\nimport { createGame } from '@quake2ts/game';\nimport { ZERO_VEC3 } from '@quake2ts/shared';\n\nexport function bootstrapViewer() {\n const engine = createEngine({\n trace(start, end) {\n return { start, end, fraction: 1 };\n },\n });\n\n const game = createGame({\n trace(start, end) {\n return { start, end, fraction: 1 };\n },\n }, { gravity: ZERO_VEC3 });\n\n const client = createClient({ engine: { trace: () => ({ start: ZERO_VEC3, end: ZERO_VEC3, fraction: 1 }) } });\n\n const runtime = createEngineRuntime(engine, game, client);\n runtime.start();\n\n return { engine, game, client, runtime };\n}\n","import type {\n ClientRenderer,\n EngineImports,\n GameFrameResult,\n GameRenderSample,\n} from '@quake2ts/engine';\nimport type { Vec3 } from '@quake2ts/shared';\n\nexport interface ClientImports {\n readonly engine: EngineImports;\n}\n\nexport interface PredictionState {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n}\n\nexport interface ClientExports extends ClientRenderer<PredictionState> {\n predict(next: PredictionState): PredictionState;\n}\n\nexport function createClient(imports: ClientImports): ClientExports {\n let latestFrame: GameFrameResult<PredictionState> | undefined;\n\n return {\n init(initial) {\n latestFrame = initial;\n void imports.engine.trace({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });\n },\n predict(next: PredictionState): PredictionState {\n const { origin, velocity } = next;\n return {\n origin: {\n x: origin.x + velocity.x,\n y: origin.y + velocity.y,\n z: origin.z + velocity.z,\n },\n velocity,\n };\n },\n render(sample: GameRenderSample<PredictionState>): void {\n latestFrame = sample.latest ?? latestFrame;\n void sample;\n },\n shutdown() {\n latestFrame = undefined;\n },\n };\n}\n","export interface FixedStepContext {\n readonly frame: number;\n readonly deltaMs: number;\n readonly nowMs: number;\n}\n\nexport interface RenderContext {\n readonly alpha: number;\n readonly nowMs: number;\n readonly accumulatorMs: number;\n readonly frame: number;\n}\n\nexport interface LoopCallbacks {\n simulate(step: FixedStepContext): void;\n render?(sample: RenderContext): void;\n}\n\nexport interface LoopOptions {\n readonly fixedDeltaMs: number;\n readonly maxSubSteps: number;\n readonly maxDeltaMs: number;\n readonly startTimeMs?: number;\n readonly now: () => number;\n readonly schedule: (tick: () => void) => unknown;\n}\n\nconst DEFAULT_FIXED_DELTA_MS = 25;\nconst DEFAULT_MAX_SUBSTEPS = 5;\n\nconst defaultNow = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());\n\nconst defaultScheduler = (tick: () => void) => {\n if (typeof requestAnimationFrame === 'function') {\n requestAnimationFrame(() => tick());\n } else {\n setTimeout(tick, DEFAULT_FIXED_DELTA_MS);\n }\n};\n\nexport class FixedTimestepLoop {\n private readonly options: LoopOptions;\n private accumulatorMs = 0;\n private frame = 0;\n private lastTimeMs: number | undefined;\n private running = false;\n\n constructor(private readonly callbacks: LoopCallbacks, options: Partial<LoopOptions> = {}) {\n const fixedDeltaMs = options.fixedDeltaMs ?? DEFAULT_FIXED_DELTA_MS;\n const maxSubSteps = options.maxSubSteps ?? DEFAULT_MAX_SUBSTEPS;\n this.options = {\n fixedDeltaMs,\n maxSubSteps,\n maxDeltaMs: options.maxDeltaMs ?? fixedDeltaMs * maxSubSteps,\n startTimeMs: options.startTimeMs,\n now: options.now ?? defaultNow,\n schedule: options.schedule ?? defaultScheduler,\n } satisfies LoopOptions;\n }\n\n start(): void {\n if (this.running) return;\n this.running = true;\n this.lastTimeMs = this.options.startTimeMs ?? this.options.now();\n this.options.schedule(this.tick);\n }\n\n stop(): void {\n this.running = false;\n }\n\n pump(elapsedMs: number): void {\n const nowMs = (this.lastTimeMs ?? 0) + elapsedMs;\n this.lastTimeMs = nowMs;\n this.advance(elapsedMs, nowMs);\n }\n\n isRunning(): boolean {\n return this.running;\n }\n\n get frameNumber(): number {\n return this.frame;\n }\n\n private tick = (): void => {\n if (!this.running) return;\n\n const nowMs = this.options.now();\n const elapsed = this.lastTimeMs === undefined ? 0 : nowMs - this.lastTimeMs;\n this.lastTimeMs = nowMs;\n\n this.advance(elapsed, nowMs);\n\n if (this.running) {\n this.options.schedule(this.tick);\n }\n };\n\n private advance(elapsedMs: number, nowMs: number): void {\n const clampedDelta = Math.min(Math.max(elapsedMs, 0), this.options.maxDeltaMs);\n this.accumulatorMs = Math.min(\n this.accumulatorMs + clampedDelta,\n this.options.fixedDeltaMs * this.options.maxSubSteps,\n );\n\n let steps = 0;\n while (this.accumulatorMs >= this.options.fixedDeltaMs && steps < this.options.maxSubSteps) {\n this.frame += 1;\n this.callbacks.simulate({ frame: this.frame, deltaMs: this.options.fixedDeltaMs, nowMs });\n this.accumulatorMs -= this.options.fixedDeltaMs;\n steps += 1;\n }\n\n const alpha = this.options.fixedDeltaMs === 0 ? 0 : this.accumulatorMs / this.options.fixedDeltaMs;\n this.callbacks.render?.({ alpha, nowMs, accumulatorMs: this.accumulatorMs, frame: this.frame });\n }\n}\n","import {\n FixedTimestepLoop,\n type FixedStepContext,\n type LoopOptions,\n type RenderContext,\n} from './loop.js';\n\nexport interface GameFrameResult<FrameState = unknown> {\n readonly frame: number;\n readonly timeMs: number;\n readonly state?: FrameState;\n}\n\nexport interface GameSimulation<FrameState = unknown> {\n init(startTimeMs: number): GameFrameResult<FrameState> | void;\n frame(step: FixedStepContext): GameFrameResult<FrameState>;\n shutdown(): void;\n}\n\nexport interface GameRenderSample<FrameState = unknown> extends RenderContext {\n readonly previous?: GameFrameResult<FrameState>;\n readonly latest?: GameFrameResult<FrameState>;\n}\n\nexport interface ClientRenderer<FrameState = unknown> {\n init(initial?: GameFrameResult<FrameState>): void;\n render(sample: GameRenderSample<FrameState>): void;\n shutdown(): void;\n}\n\nexport interface EngineHostOptions {\n readonly loop?: Partial<LoopOptions>;\n readonly startTimeMs?: number;\n}\n\nexport class EngineHost<FrameState = unknown> {\n private readonly loop: FixedTimestepLoop;\n private readonly startTimeMs: number;\n private previousFrame?: GameFrameResult<FrameState>;\n private latestFrame?: GameFrameResult<FrameState>;\n private started = false;\n\n constructor(\n private readonly game: GameSimulation<FrameState>,\n private readonly client?: ClientRenderer<FrameState>,\n options: EngineHostOptions = {},\n ) {\n const now = options.loop?.now?.() ?? Date.now();\n this.startTimeMs = options.startTimeMs ?? options.loop?.startTimeMs ?? now;\n this.loop = new FixedTimestepLoop(\n {\n simulate: this.stepSimulation,\n render: this.renderClient,\n },\n { ...options.loop, startTimeMs: this.startTimeMs },\n );\n }\n\n start(): void {\n if (this.started) return;\n\n this.latestFrame = this.game.init(this.startTimeMs) ?? this.latestFrame;\n this.client?.init(this.latestFrame);\n\n this.started = true;\n this.loop.start();\n }\n\n stop(): void {\n if (!this.started) return;\n\n this.loop.stop();\n this.client?.shutdown();\n this.game.shutdown();\n this.previousFrame = undefined;\n this.latestFrame = undefined;\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.loop.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.latestFrame;\n }\n\n isRunning(): boolean {\n return this.loop.isRunning();\n }\n\n private stepSimulation = (step: FixedStepContext): void => {\n this.previousFrame = this.latestFrame;\n this.latestFrame = this.game.frame(step);\n };\n\n private renderClient = (renderContext: RenderContext): void => {\n if (!this.client) return;\n this.client.render({\n ...renderContext,\n previous: this.previousFrame,\n latest: this.latestFrame,\n });\n };\n}\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) trace.allsolid = true;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n","import {\n ConfigStringIndex,\n CS_MAX_STRING_LENGTH,\n MAX_CONFIGSTRINGS,\n MAX_GENERAL,\n MAX_IMAGES,\n MAX_ITEMS,\n MAX_LIGHTSTYLES,\n MAX_MODELS,\n MAX_CLIENTS,\n MAX_SHADOW_LIGHTS,\n MAX_SOUNDS,\n MAX_WHEEL_ITEMS,\n configStringSize,\n} from '@quake2ts/shared';\n\nexport type ConfigStringEntry = Readonly<{ index: number; value: string }>;\n\nfunction assertWithinBounds(index: number): void {\n if (index < 0 || index >= ConfigStringIndex.MaxConfigStrings) {\n throw new RangeError(`Configstring index ${index} is out of range (0-${ConfigStringIndex.MaxConfigStrings - 1})`);\n }\n}\n\nfunction assertLength(index: number, value: string): void {\n const maxLength = configStringSize(index);\n if (value.length > maxLength) {\n throw new RangeError(\n `Configstring ${index} exceeds maximum length (${value.length} > ${maxLength}); limit is ${CS_MAX_STRING_LENGTH} chars per slot`,\n );\n }\n}\n\n/**\n * Minimal configstring/config index registry that mirrors the rerelease asset\n * indexing routines (`modelindex`, `soundindex`, etc.). The registry maintains\n * deterministic ordering within each configstring range and enforces the same\n * length/slot limits as the C++ helpers.\n */\nexport class ConfigStringRegistry {\n private readonly values = new Map<number, string>();\n private modelCursor = ConfigStringIndex.Models;\n private soundCursor = ConfigStringIndex.Sounds;\n private imageCursor = ConfigStringIndex.Images;\n private lightCursor = ConfigStringIndex.Lights;\n private shadowLightCursor = ConfigStringIndex.ShadowLights;\n private itemCursor = ConfigStringIndex.Items;\n private playerSkinCursor = ConfigStringIndex.PlayerSkins;\n private generalCursor = ConfigStringIndex.General;\n\n set(index: number, value: string): number {\n assertWithinBounds(index);\n assertLength(index, value);\n this.values.set(index, value);\n return index;\n }\n\n get(index: number): string | undefined {\n return this.values.get(index);\n }\n\n getAll(): string[] {\n const result: string[] = new Array(MAX_CONFIGSTRINGS).fill('');\n for (const [index, value] of this.values.entries()) {\n result[index] = value;\n }\n return result;\n }\n\n modelIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Models, MAX_MODELS, 'modelCursor');\n }\n\n soundIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Sounds, MAX_SOUNDS, 'soundCursor');\n }\n\n imageIndex(path: string): number {\n return this.register(path, ConfigStringIndex.Images, MAX_IMAGES, 'imageCursor');\n }\n\n lightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.Lights, MAX_LIGHTSTYLES, 'lightCursor');\n }\n\n shadowLightIndex(definition: string): number {\n return this.register(definition, ConfigStringIndex.ShadowLights, MAX_SHADOW_LIGHTS, 'shadowLightCursor');\n }\n\n itemIndex(name: string): number {\n return this.register(name, ConfigStringIndex.Items, MAX_ITEMS, 'itemCursor');\n }\n\n playerSkinIndex(name: string): number {\n return this.register(name, ConfigStringIndex.PlayerSkins, MAX_CLIENTS, 'playerSkinCursor');\n }\n\n generalIndex(value: string): number {\n return this.register(value, ConfigStringIndex.General, MAX_GENERAL, 'generalCursor');\n }\n\n private register(\n value: string,\n start: ConfigStringIndex,\n maxCount: number,\n cursorKey:\n | 'modelCursor'\n | 'soundCursor'\n | 'imageCursor'\n | 'lightCursor'\n | 'shadowLightCursor'\n | 'itemCursor'\n | 'playerSkinCursor'\n | 'generalCursor',\n ): number {\n // Reuse an existing slot if the caller tries to register the same value in the same range.\n for (let i = start; i < start + maxCount; i += 1) {\n if (this.values.get(i) === value) {\n return i;\n }\n }\n\n const next = this[cursorKey];\n const limit = start + maxCount;\n if (next >= limit) {\n throw new RangeError(`Out of configstring slots for range starting at ${start}`);\n }\n\n assertLength(next, value);\n this.values.set(next, value);\n this[cursorKey] = next + 1;\n return next;\n }\n}\n","import type { EngineExports } from './index.js';\nimport { EngineHost, type ClientRenderer, type EngineHostOptions, type GameFrameResult, type GameSimulation } from './host.js';\n\nexport class EngineRuntime<FrameState = unknown> {\n private started = false;\n\n constructor(private readonly engine: EngineExports, private readonly host: EngineHost<FrameState>) {}\n\n start(): void {\n if (this.started) return;\n this.engine.init();\n this.host.start();\n this.started = true;\n }\n\n stop(): void {\n if (!this.started) return;\n this.host.stop();\n this.engine.shutdown();\n this.started = false;\n }\n\n pump(elapsedMs: number): void {\n this.host.pump(elapsedMs);\n }\n\n getLatestFrame(): GameFrameResult<FrameState> | undefined {\n return this.host.getLatestFrame();\n }\n\n isRunning(): boolean {\n return this.started && this.host.isRunning();\n }\n}\n\nexport function createEngineRuntime<FrameState = unknown>(\n engine: EngineExports,\n game: GameSimulation<FrameState>,\n client?: ClientRenderer<FrameState>,\n options?: EngineHostOptions,\n): EngineRuntime<FrameState> {\n return new EngineRuntime(engine, new EngineHost(game, client, options));\n}\n","import { CvarFlags } from '@quake2ts/shared';\n\nexport type CvarChangeHandler = (cvar: Cvar, previousValue: string) => void;\n\nexport class Cvar {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags: CvarFlags;\n private _value: string;\n private latched?: string;\n private onChange?: CvarChangeHandler;\n modifiedCount = 0;\n\n constructor({\n name,\n defaultValue,\n description,\n flags = CvarFlags.None,\n onChange,\n }: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }) {\n this.name = name;\n this.defaultValue = defaultValue;\n this.description = description;\n this.flags = flags;\n this._value = defaultValue;\n this.onChange = onChange;\n }\n\n get string(): string {\n return this._value;\n }\n\n get number(): number {\n return Number(this._value);\n }\n\n get integer(): number {\n return Math.trunc(this.number);\n }\n\n get boolean(): boolean {\n return Boolean(this.integer);\n }\n\n set(value: string): void {\n if (this.flags & CvarFlags.Latch) {\n if (value === this._value) {\n this.latched = undefined;\n return;\n }\n\n if (this.latched === value) {\n return;\n }\n\n if (this.latched !== value) {\n this.latched = value;\n }\n return;\n }\n\n this.apply(value);\n }\n\n reset(): void {\n this.latched = undefined;\n this.apply(this.defaultValue);\n }\n\n applyLatched(): boolean {\n if (this.latched === undefined) {\n return false;\n }\n\n const pending = this.latched;\n this.latched = undefined;\n if (pending === this._value) {\n return false;\n }\n this.apply(pending);\n return true;\n }\n\n private apply(next: string): void {\n if (this._value === next) {\n return;\n }\n\n const previous = this._value;\n this._value = next;\n this.modifiedCount += 1;\n this.onChange?.(this, previous);\n }\n}\n\nexport class CvarRegistry {\n private readonly cvars = new Map<string, Cvar>();\n\n register(def: {\n name: string;\n defaultValue: string;\n description?: string;\n flags?: CvarFlags;\n onChange?: CvarChangeHandler;\n }): Cvar {\n const existing = this.cvars.get(def.name);\n if (existing) {\n return existing;\n }\n\n const cvar = new Cvar(def);\n this.cvars.set(def.name, cvar);\n return cvar;\n }\n\n get(name: string): Cvar | undefined {\n return this.cvars.get(name);\n }\n\n setValue(name: string, value: string): Cvar {\n const cvar = this.get(name);\n if (!cvar) {\n throw new Error(`Unknown cvar: ${name}`);\n }\n\n cvar.set(value);\n return cvar;\n }\n\n resetAll(): void {\n for (const cvar of this.cvars.values()) {\n cvar.reset();\n }\n }\n\n applyLatched(): boolean {\n let changed = false;\n for (const cvar of this.cvars.values()) {\n changed = cvar.applyLatched() || changed;\n }\n return changed;\n }\n\n list(): Cvar[] {\n return [...this.cvars.values()].sort((a, b) => a.name.localeCompare(b.name));\n }\n}\n","const PAK_MAGIC = 'PACK';\nconst HEADER_SIZE = 12;\nconst DIRECTORY_ENTRY_SIZE = 64;\n\nexport interface PakDirectoryEntry {\n readonly name: string;\n readonly offset: number;\n readonly length: number;\n}\n\nexport interface PakValidationResult {\n readonly checksum: number;\n readonly entries: readonly PakDirectoryEntry[];\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const codes: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) {\n break;\n }\n codes.push(code);\n }\n return String.fromCharCode(...codes);\n}\n\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/').replace(/^\\/+/, '').toLowerCase();\n}\n\nfunction createCrcTable(): Uint32Array {\n const table = new Uint32Array(256);\n for (let i = 0; i < 256; i += 1) {\n let crc = i;\n for (let j = 0; j < 8; j += 1) {\n crc = (crc & 1) !== 0 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;\n }\n table[i] = crc >>> 0;\n }\n return table;\n}\n\nconst CRC_TABLE = createCrcTable();\n\nfunction crc32(data: Uint8Array): number {\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i += 1) {\n const byte = data[i];\n crc = CRC_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n\nexport class PakParseError extends Error {}\n\nexport class PakArchive {\n static fromArrayBuffer(name: string, buffer: ArrayBuffer): PakArchive {\n const view = new DataView(buffer);\n if (buffer.byteLength < HEADER_SIZE) {\n throw new PakParseError('PAK buffer too small to contain header');\n }\n\n const magic = String.fromCharCode(\n view.getUint8(0),\n view.getUint8(1),\n view.getUint8(2),\n view.getUint8(3),\n );\n\n if (magic !== PAK_MAGIC) {\n throw new PakParseError(`Invalid PAK header magic: ${magic}`);\n }\n\n const dirOffset = view.getInt32(4, true);\n const dirLength = view.getInt32(8, true);\n\n if (dirOffset < HEADER_SIZE) {\n throw new PakParseError(`Invalid directory offset: ${dirOffset}`);\n }\n\n if (dirLength <= 0 || dirLength % DIRECTORY_ENTRY_SIZE !== 0) {\n throw new PakParseError(`Invalid directory length: ${dirLength}`);\n }\n\n const dirEnd = dirOffset + dirLength;\n if (dirEnd > buffer.byteLength) {\n throw new PakParseError('Directory exceeds buffer length');\n }\n\n const entryCount = dirLength / DIRECTORY_ENTRY_SIZE;\n const entries: PakDirectoryEntry[] = [];\n const dedupe = new Map<string, PakDirectoryEntry>();\n\n for (let i = 0; i < entryCount; i += 1) {\n const offset = dirOffset + i * DIRECTORY_ENTRY_SIZE;\n const rawName = readCString(view, offset, 56);\n const normalized = normalizePath(rawName);\n\n const fileOffset = view.getInt32(offset + 56, true);\n const fileLength = view.getInt32(offset + 60, true);\n\n if (fileOffset < 0 || fileLength < 0 || fileOffset + fileLength > buffer.byteLength) {\n throw new PakParseError(\n `Invalid entry bounds for ${rawName || '<unnamed>'} (offset=${fileOffset}, length=${fileLength})`,\n );\n }\n\n if (!normalized) {\n throw new PakParseError(`Entry ${i} has an empty name`);\n }\n\n const entry: PakDirectoryEntry = { name: normalized, offset: fileOffset, length: fileLength };\n dedupe.set(normalized, entry);\n }\n\n entries.push(...dedupe.values());\n\n return new PakArchive(name, buffer, entries, crc32(new Uint8Array(buffer)));\n }\n\n readonly entries: ReadonlyMap<string, PakDirectoryEntry>;\n readonly checksum: number;\n readonly size: number;\n\n private constructor(\n readonly name: string,\n private readonly buffer: ArrayBuffer,\n entries: PakDirectoryEntry[],\n checksum: number,\n ) {\n this.entries = new Map(entries.map((entry) => [entry.name, entry]));\n this.checksum = checksum;\n this.size = buffer.byteLength;\n }\n\n getEntry(path: string): PakDirectoryEntry | undefined {\n return this.entries.get(normalizePath(path));\n }\n\n listEntries(): PakDirectoryEntry[] {\n return Array.from(this.entries.values());\n }\n\n readFile(path: string): Uint8Array {\n const entry = this.getEntry(path);\n if (!entry) {\n throw new PakParseError(`File not found in PAK: ${path}`);\n }\n return new Uint8Array(this.buffer, entry.offset, entry.length);\n }\n\n validate(): PakValidationResult {\n return {\n checksum: this.checksum,\n entries: this.listEntries(),\n };\n }\n}\n\nexport function calculatePakChecksum(buffer: ArrayBuffer): number {\n return crc32(new Uint8Array(buffer));\n}\n\nexport { normalizePath };\n","import { PakArchive, PakDirectoryEntry, normalizePath } from './pak.js';\n\ntype VfsSource = { archive: PakArchive; entry: PakDirectoryEntry };\n\nexport interface VirtualFileHandle {\n readonly path: string;\n readonly size: number;\n readonly sourcePak: string;\n}\n\nexport interface DirectoryListing {\n readonly files: VirtualFileHandle[];\n readonly directories: string[];\n}\n\nexport class VirtualFileSystem {\n private readonly mounts: PakArchive[] = [];\n private readonly files = new Map<string, VfsSource>();\n\n constructor(archives: PakArchive[] = []) {\n archives.forEach((archive) => this.mountPak(archive));\n }\n\n mountPak(archive: PakArchive): void {\n this.mounts.push(archive);\n for (const entry of archive.listEntries()) {\n const key = normalizePath(entry.name);\n this.files.set(key, { archive, entry });\n }\n }\n\n get mountedPaks(): readonly PakArchive[] {\n return [...this.mounts];\n }\n\n hasFile(path: string): boolean {\n return this.files.has(normalizePath(path));\n }\n\n stat(path: string): VirtualFileHandle | undefined {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n return undefined;\n }\n return { path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name };\n }\n\n async readFile(path: string): Promise<Uint8Array> {\n const source = this.files.get(normalizePath(path));\n if (!source) {\n throw new Error(`File not found in VFS: ${path}`);\n }\n return source.archive.readFile(path);\n }\n\n list(directory = ''): DirectoryListing {\n const dir = normalizePath(directory).replace(/\\/+$|^\\//g, '');\n const files: VirtualFileHandle[] = [];\n const directories = new Set<string>();\n const prefix = dir ? `${dir}/` : '';\n\n for (const source of this.files.values()) {\n if (dir && !source.entry.name.startsWith(prefix)) {\n continue;\n }\n const relative = dir ? source.entry.name.slice(prefix.length) : source.entry.name;\n const separatorIndex = relative.indexOf('/');\n if (separatorIndex === -1) {\n files.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n } else {\n directories.add(relative.slice(0, separatorIndex));\n }\n }\n\n files.sort((a, b) => a.path.localeCompare(b.path));\n\n return { files, directories: [...directories].sort() };\n }\n\n findByExtension(extension: string): VirtualFileHandle[] {\n const normalizedExt = extension.startsWith('.') ? extension.toLowerCase() : `.${extension.toLowerCase()}`;\n const results: VirtualFileHandle[] = [];\n for (const source of this.files.values()) {\n if (source.entry.name.toLowerCase().endsWith(normalizedExt)) {\n results.push({ path: source.entry.name, size: source.entry.length, sourcePak: source.archive.name });\n }\n }\n return results.sort((a, b) => a.path.localeCompare(b.path));\n }\n}\n","import { PakArchive } from './pak.js';\nimport { VirtualFileSystem } from './vfs.js';\n\nexport interface PakSource {\n readonly name: string;\n readonly data: ArrayBuffer | Blob | ArrayBufferView;\n}\n\nexport interface PakIngestionProgress {\n readonly file: string;\n readonly loadedBytes: number;\n readonly totalBytes: number;\n readonly state: 'reading' | 'parsed' | 'error';\n}\n\nexport interface PakIngestionResult {\n readonly archive: PakArchive;\n readonly mounted: boolean;\n}\n\nexport interface PakIngestionOptions {\n readonly onProgress?: (progress: PakIngestionProgress) => void;\n readonly onError?: (file: string, error: unknown) => void;\n /**\n * Whether ingestion should abort when a single PAK fails to parse or mount.\n * Defaults to false to allow partial success in multi-PAK scenarios.\n */\n readonly stopOnError?: boolean;\n}\n\nexport class PakIngestionError extends Error {\n constructor(readonly file: string, cause: unknown) {\n super(`Failed to ingest PAK: ${file}`);\n this.name = 'PakIngestionError';\n if (cause instanceof Error && cause.stack) {\n this.stack = cause.stack;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this as any).cause = cause;\n }\n}\n\nasync function readBlobWithProgress(source: Blob, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (typeof source.arrayBuffer === 'function') {\n const buffer = await source.arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof FileReader !== 'undefined') {\n return new Promise<ArrayBuffer>((resolve, reject) => {\n const reader = new FileReader();\n reader.onerror = () => reject(reader.error ?? new Error('Unknown FileReader error'));\n reader.onprogress = (event) => {\n onProgress?.({\n file: 'blob',\n loadedBytes: event.loaded,\n totalBytes: event.total || source.size,\n state: 'reading',\n });\n };\n reader.onload = () => {\n const result = reader.result;\n if (result instanceof ArrayBuffer) {\n resolve(result);\n } else {\n reject(new Error('Unexpected FileReader result'));\n }\n };\n reader.readAsArrayBuffer(source);\n });\n }\n\n if (typeof Response !== 'undefined') {\n const buffer = await new Response(source).arrayBuffer();\n onProgress?.({ file: 'blob', loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n }\n\n if (typeof source.stream === 'function') {\n const reader = (source.stream() as ReadableStream<Uint8Array>).getReader();\n const chunks: Uint8Array[] = [];\n let loaded = 0;\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n if (!value) {\n continue;\n }\n\n const chunk = value as Uint8Array;\n\n chunks.push(chunk);\n loaded += chunk.byteLength;\n onProgress?.({ file: 'blob', loadedBytes: loaded, totalBytes: source.size, state: 'reading' });\n }\n\n const result = new Uint8Array(loaded);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result.buffer;\n }\n\n throw new PakIngestionError('blob', new Error('Unsupported Blob type'));\n}\n\nasync function toArrayBuffer(source: PakSource, onProgress?: (progress: PakIngestionProgress) => void): Promise<ArrayBuffer> {\n if (source.data instanceof ArrayBuffer) {\n onProgress?.({ file: source.name, loadedBytes: source.data.byteLength, totalBytes: source.data.byteLength, state: 'reading' });\n return source.data;\n }\n if (source.data instanceof Blob) {\n const totalBytes = source.data.size;\n return readBlobWithProgress(source.data, (progress) =>\n onProgress?.({ ...progress, file: source.name, totalBytes }),\n );\n }\n\n const buffer = source.data.buffer.slice(source.data.byteOffset, source.data.byteOffset + source.data.byteLength) as ArrayBuffer;\n onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'reading' });\n return buffer;\n}\n\nexport async function ingestPaks(\n vfs: VirtualFileSystem,\n sources: PakSource[],\n onProgressOrOptions?: PakIngestionOptions | ((progress: PakIngestionProgress) => void),\n): Promise<PakIngestionResult[]> {\n const options: PakIngestionOptions =\n typeof onProgressOrOptions === 'function' ? { onProgress: onProgressOrOptions } : onProgressOrOptions ?? {};\n\n const results: PakIngestionResult[] = [];\n\n for (const source of sources) {\n try {\n const buffer = await toArrayBuffer(source, options.onProgress);\n const archive = PakArchive.fromArrayBuffer(source.name, buffer);\n vfs.mountPak(archive);\n options.onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'parsed' });\n results.push({ archive, mounted: true });\n } catch (error) {\n options.onProgress?.({ file: source.name, loadedBytes: 0, totalBytes: 0, state: 'error' });\n options.onError?.(source.name, error);\n\n if (options.stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n\n return results;\n}\n","export interface CacheEntry<T> {\n key: string;\n value: T;\n}\n\nexport class LruCache<T> {\n private readonly map = new Map<string, T>();\n\n constructor(private readonly capacity: number) {\n if (capacity <= 0) {\n throw new RangeError('LRU cache capacity must be greater than zero');\n }\n }\n\n get size(): number {\n return this.map.size;\n }\n\n has(key: string): boolean {\n return this.map.has(key);\n }\n\n get(key: string): T | undefined {\n const value = this.map.get(key);\n if (value === undefined) {\n return undefined;\n }\n this.map.delete(key);\n this.map.set(key, value);\n return value;\n }\n\n set(key: string, value: T): void {\n if (this.map.has(key)) {\n this.map.delete(key);\n }\n this.map.set(key, value);\n if (this.map.size > this.capacity) {\n const oldestKey = this.map.keys().next();\n if (!oldestKey.done) {\n this.map.delete(oldestKey.value);\n }\n }\n }\n\n delete(key: string): boolean {\n return this.map.delete(key);\n }\n\n clear(): void {\n this.map.clear();\n }\n\n entries(): CacheEntry<T>[] {\n return Array.from(this.map.entries()).reverse().map(([key, value]) => ({ key, value }));\n }\n}\n","import { ingestPaks, type PakIngestionOptions, type PakIngestionResult, type PakSource } from './ingestion.js';\nimport { VirtualFileSystem } from './vfs.js';\n\nfunction toArray(files: Iterable<File>): File[] {\n return Array.isArray(files) ? files : Array.from(files);\n}\n\nexport function filesToPakSources(files: Iterable<File>): PakSource[] {\n return toArray(files).map((file) => ({ name: file.name, data: file }));\n}\n\nexport async function ingestPakFiles(\n vfs: VirtualFileSystem,\n files: Iterable<File>,\n options?: PakIngestionOptions,\n): Promise<PakIngestionResult[]> {\n const sources = filesToPakSources(files);\n return ingestPaks(vfs, sources, options ?? {});\n}\n\nexport function wireDropTarget(\n element: HTMLElement,\n handler: (files: File[]) => void,\n): () => void {\n const onDragOver = (event: DragEvent) => {\n event.preventDefault();\n event.dataTransfer?.dropEffect && (event.dataTransfer.dropEffect = 'copy');\n };\n\n const onDrop = (event: DragEvent) => {\n event.preventDefault();\n const droppedFiles = event.dataTransfer?.files;\n if (droppedFiles && droppedFiles.length > 0) {\n handler(Array.from(droppedFiles));\n }\n };\n\n element.addEventListener('dragover', onDragOver);\n element.addEventListener('drop', onDrop);\n\n return () => {\n element.removeEventListener('dragover', onDragOver);\n element.removeEventListener('drop', onDrop);\n };\n}\n\nexport function wireFileInput(\n input: HTMLInputElement,\n handler: (files: FileList) => void,\n): () => void {\n const onChange = (event: Event) => {\n const target = event.target as HTMLInputElement | null;\n if (!target || !target.files || target.files.length === 0) {\n return;\n }\n handler(target.files);\n target.value = '';\n };\n\n input.addEventListener('change', onChange);\n return () => input.removeEventListener('change', onChange);\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD2_MAGIC = 844121161; // 'IDP2'\nconst MD2_VERSION = 8;\nconst HEADER_SIZE = 17 * 4;\nconst MD2_NORMALS: ReadonlyArray<Vec3> = [\n { x: -0.525731, y: 0.0, z: 0.850651 },\n { x: -0.442863, y: 0.238856, z: 0.864188 },\n { x: -0.295242, y: 0.0, z: 0.955423 },\n { x: -0.309017, y: 0.5, z: 0.809017 },\n { x: -0.16246, y: 0.262866, z: 0.951056 },\n { x: 0.0, y: 0.0, z: 1.0 },\n { x: 0.0, y: 0.850651, z: 0.525731 },\n { x: -0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.147621, y: 0.716567, z: 0.681718 },\n { x: 0.0, y: 0.525731, z: 0.850651 },\n { x: 0.309017, y: 0.5, z: 0.809017 },\n { x: 0.525731, y: 0.0, z: 0.850651 },\n { x: 0.295242, y: 0.0, z: 0.955423 },\n { x: 0.442863, y: 0.238856, z: 0.864188 },\n { x: 0.16246, y: 0.262866, z: 0.951056 },\n { x: -0.681718, y: 0.147621, z: 0.716567 },\n { x: -0.809017, y: 0.309017, z: 0.5 },\n { x: -0.587785, y: 0.425325, z: 0.688191 },\n { x: -0.850651, y: 0.525731, z: 0.0 },\n { x: -0.864188, y: 0.442863, z: 0.238856 },\n { x: -0.716567, y: 0.681718, z: 0.147621 },\n { x: -0.688191, y: 0.587785, z: 0.425325 },\n { x: -0.5000, y: 0.809017, z: 0.309017 },\n { x: -0.238856, y: 0.864188, z: 0.442863 },\n { x: -0.425325, y: 0.688191, z: 0.587785 },\n { x: -0.716567, y: 0.681718, z: -0.147621 },\n { x: -0.5000, y: 0.809017, z: -0.309017 },\n { x: -0.525731, y: 0.850651, z: 0.0 },\n { x: 0.0, y: 0.850651, z: -0.525731 },\n { x: -0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.0, y: 0.955423, z: -0.295242 },\n { x: -0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.0, y: 1.0, z: 0.0 },\n { x: 0.0, y: 0.955423, z: 0.295242 },\n { x: -0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.238856, y: 0.864188, z: 0.442863 },\n { x: 0.262866, y: 0.951056, z: 0.16246 },\n { x: 0.5, y: 0.809017, z: 0.309017 },\n { x: 0.238856, y: 0.864188, z: -0.442863 },\n { x: 0.262866, y: 0.951056, z: -0.16246 },\n { x: 0.5, y: 0.809017, z: -0.309017 },\n { x: 0.850651, y: 0.525731, z: 0.0 },\n { x: 0.716567, y: 0.681718, z: 0.147621 },\n { x: 0.716567, y: 0.681718, z: -0.147621 },\n { x: 0.525731, y: 0.850651, z: 0.0 },\n { x: 0.425325, y: 0.688191, z: 0.587785 },\n { x: 0.864188, y: 0.442863, z: 0.238856 },\n { x: 0.688191, y: 0.587785, z: 0.425325 },\n { x: 0.809017, y: 0.309017, z: 0.5 },\n { x: 0.681718, y: 0.147621, z: 0.716567 },\n { x: 0.587785, y: 0.425325, z: 0.688191 },\n { x: 0.955423, y: 0.295242, z: 0.0 },\n { x: 1.0, y: 0.0, z: 0.0 },\n { x: 0.951056, y: 0.16246, z: 0.262866 },\n { x: 0.850651, y: -0.525731, z: 0.0 },\n { x: 0.955423, y: -0.295242, z: 0.0 },\n { x: 0.864188, y: -0.442863, z: 0.238856 },\n { x: 0.951056, y: -0.16246, z: 0.262866 },\n { x: 0.809017, y: -0.309017, z: 0.5 },\n { x: 0.681718, y: -0.147621, z: 0.716567 },\n { x: 0.850651, y: 0.0, z: 0.525731 },\n { x: 0.864188, y: 0.442863, z: -0.238856 },\n { x: 0.809017, y: 0.309017, z: -0.5 },\n { x: 0.951056, y: 0.16246, z: -0.262866 },\n { x: 0.525731, y: 0.0, z: -0.850651 },\n { x: 0.681718, y: 0.147621, z: -0.716567 },\n { x: 0.681718, y: -0.147621, z: -0.716567 },\n { x: 0.850651, y: 0.0, z: -0.525731 },\n { x: 0.809017, y: -0.309017, z: -0.5 },\n { x: 0.864188, y: -0.442863, z: -0.238856 },\n { x: 0.951056, y: -0.16246, z: -0.262866 },\n { x: 0.147621, y: 0.716567, z: -0.681718 },\n { x: 0.309017, y: 0.5, z: -0.809017 },\n { x: 0.425325, y: 0.688191, z: -0.587785 },\n { x: 0.442863, y: 0.238856, z: -0.864188 },\n { x: 0.587785, y: 0.425325, z: -0.688191 },\n { x: 0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.147621, y: 0.716567, z: -0.681718 },\n { x: -0.309017, y: 0.5, z: -0.809017 },\n { x: 0.0, y: 0.525731, z: -0.850651 },\n { x: -0.525731, y: 0.0, z: -0.850651 },\n { x: -0.442863, y: 0.238856, z: -0.864188 },\n { x: -0.295242, y: 0.0, z: -0.955423 },\n { x: -0.16246, y: 0.262866, z: -0.951056 },\n { x: 0.0, y: 0.0, z: -1.0 },\n { x: 0.295242, y: 0.0, z: -0.955423 },\n { x: 0.16246, y: 0.262866, z: -0.951056 },\n { x: -0.442863, y: -0.238856, z: -0.864188 },\n { x: -0.309017, y: -0.5, z: -0.809017 },\n { x: -0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.0, y: -0.850651, z: -0.525731 },\n { x: -0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.147621, y: -0.716567, z: -0.681718 },\n { x: 0.0, y: -0.525731, z: -0.850651 },\n { x: 0.309017, y: -0.5, z: -0.809017 },\n { x: 0.442863, y: -0.238856, z: -0.864188 },\n { x: 0.16246, y: -0.262866, z: -0.951056 },\n { x: 0.238856, y: -0.864188, z: -0.442863 },\n { x: 0.5, y: -0.809017, z: -0.309017 },\n { x: 0.425325, y: -0.688191, z: -0.587785 },\n { x: 0.716567, y: -0.681718, z: -0.147621 },\n { x: 0.688191, y: -0.587785, z: -0.425325 },\n { x: 0.587785, y: -0.425325, z: -0.688191 },\n { x: 0.0, y: -0.955423, z: -0.295242 },\n { x: 0.0, y: -1.0, z: 0.0 },\n { x: 0.262866, y: -0.951056, z: -0.16246 },\n { x: 0.0, y: -0.850651, z: 0.525731 },\n { x: 0.0, y: -0.955423, z: 0.295242 },\n { x: 0.238856, y: -0.864188, z: 0.442863 },\n { x: 0.262866, y: -0.951056, z: 0.16246 },\n { x: 0.5, y: -0.809017, z: 0.309017 },\n { x: 0.716567, y: -0.681718, z: 0.147621 },\n { x: 0.525731, y: -0.850651, z: 0.0 },\n { x: -0.238856, y: -0.864188, z: -0.442863 },\n { x: -0.5, y: -0.809017, z: -0.309017 },\n { x: -0.262866, y: -0.951056, z: -0.16246 },\n { x: -0.850651, y: -0.525731, z: 0.0 },\n { x: -0.716567, y: -0.681718, z: -0.147621 },\n { x: -0.716567, y: -0.681718, z: 0.147621 },\n { x: -0.525731, y: -0.850651, z: 0.0 },\n { x: -0.5, y: -0.809017, z: 0.309017 },\n { x: -0.238856, y: -0.864188, z: 0.442863 },\n { x: -0.262866, y: -0.951056, z: 0.16246 },\n { x: -0.864188, y: -0.442863, z: 0.238856 },\n { x: -0.809017, y: -0.309017, z: 0.5 },\n { x: -0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.681718, y: -0.147621, z: 0.716567 },\n { x: -0.442863, y: -0.238856, z: 0.864188 },\n { x: -0.587785, y: -0.425325, z: 0.688191 },\n { x: -0.309017, y: -0.5, z: 0.809017 },\n { x: -0.147621, y: -0.716567, z: 0.681718 },\n { x: -0.425325, y: -0.688191, z: 0.587785 },\n { x: -0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.442863, y: -0.238856, z: 0.864188 },\n { x: 0.16246, y: -0.262866, z: 0.951056 },\n { x: 0.309017, y: -0.5, z: 0.809017 },\n { x: 0.147621, y: -0.716567, z: 0.681718 },\n { x: 0.0, y: -0.525731, z: 0.850651 },\n { x: 0.425325, y: -0.688191, z: 0.587785 },\n { x: 0.587785, y: -0.425325, z: 0.688191 },\n { x: 0.688191, y: -0.587785, z: 0.425325 },\n { x: -0.955423, y: 0.295242, z: 0.0 },\n { x: -0.951056, y: 0.16246, z: 0.262866 },\n { x: -1.0, y: 0.0, z: 0.0 },\n { x: -0.850651, y: 0.0, z: 0.525731 },\n { x: -0.955423, y: -0.295242, z: 0.0 },\n { x: -0.951056, y: -0.16246, z: 0.262866 },\n { x: -0.864188, y: 0.442863, z: -0.238856 },\n { x: -0.951056, y: 0.16246, z: -0.262866 },\n { x: -0.809017, y: 0.309017, z: -0.5 },\n { x: -0.864188, y: -0.442863, z: -0.238856 },\n { x: -0.951056, y: -0.16246, z: -0.262866 },\n { x: -0.809017, y: -0.309017, z: -0.5 },\n { x: -0.681718, y: 0.147621, z: -0.716567 },\n { x: -0.681718, y: -0.147621, z: -0.716567 },\n { x: -0.850651, y: 0.0, z: -0.525731 },\n { x: -0.688191, y: 0.587785, z: -0.425325 },\n { x: -0.587785, y: 0.425325, z: -0.688191 },\n { x: -0.425325, y: 0.688191, z: -0.587785 },\n { x: -0.425325, y: -0.688191, z: -0.587785 },\n { x: -0.587785, y: -0.425325, z: -0.688191 },\n { x: -0.688191, y: -0.587785, z: -0.425325 },\n];\n\nexport interface Md2Header {\n readonly ident: number;\n readonly version: number;\n readonly skinWidth: number;\n readonly skinHeight: number;\n readonly frameSize: number;\n readonly numSkins: number;\n readonly numVertices: number;\n readonly numTexCoords: number;\n readonly numTriangles: number;\n readonly numGlCommands: number;\n readonly numFrames: number;\n readonly offsetSkins: number;\n readonly offsetTexCoords: number;\n readonly offsetTriangles: number;\n readonly offsetFrames: number;\n readonly offsetGlCommands: number;\n readonly offsetEnd: number;\n}\n\nexport interface Md2Skin {\n readonly name: string;\n}\n\nexport interface Md2TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md2Triangle {\n readonly vertexIndices: [number, number, number];\n readonly texCoordIndices: [number, number, number];\n}\n\nexport interface Md2Vertex {\n readonly position: Vec3;\n readonly normalIndex: number;\n readonly normal: Vec3;\n}\n\nexport interface Md2Frame {\n readonly name: string;\n readonly vertices: readonly Md2Vertex[];\n}\n\nexport interface Md2GlCommandVertex {\n readonly s: number;\n readonly t: number;\n readonly vertexIndex: number;\n}\n\nexport interface Md2GlCommand {\n readonly mode: 'strip' | 'fan';\n readonly vertices: readonly Md2GlCommandVertex[];\n}\n\nexport interface Md2Model {\n readonly header: Md2Header;\n readonly skins: readonly Md2Skin[];\n readonly texCoords: readonly Md2TexCoord[];\n readonly triangles: readonly Md2Triangle[];\n readonly frames: readonly Md2Frame[];\n readonly glCommands: readonly Md2GlCommand[];\n}\n\nexport interface Md2Animation {\n readonly name: string;\n readonly firstFrame: number;\n readonly lastFrame: number;\n}\n\nexport class Md2ParseError extends Error {}\n\nexport class Md2Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md2Model> {\n const bytes = await this.vfs.readFile(path);\n const copy = new Uint8Array(bytes.byteLength);\n copy.set(bytes);\n return parseMd2(copy.buffer);\n }\n}\n\nfunction readCString(view: DataView, offset: number, maxLength: number): string {\n const chars: number[] = [];\n for (let i = 0; i < maxLength; i += 1) {\n const code = view.getUint8(offset + i);\n if (code === 0) break;\n chars.push(code);\n }\n return String.fromCharCode(...chars);\n}\n\nfunction validateSection(buffer: ArrayBuffer, offset: number, length: number, label: string): void {\n if (length === 0) return;\n if (offset < HEADER_SIZE || offset + length > buffer.byteLength) {\n throw new Md2ParseError(`${label} section is out of bounds`);\n }\n}\n\nfunction parseHeader(buffer: ArrayBuffer): Md2Header {\n if (buffer.byteLength < HEADER_SIZE) {\n throw new Md2ParseError('MD2 buffer too small to contain header');\n }\n\n const view = new DataView(buffer);\n const ident = view.getInt32(0, true);\n const version = view.getInt32(4, true);\n\n if (ident !== MD2_MAGIC) {\n throw new Md2ParseError(`Invalid MD2 ident: ${ident}`);\n }\n if (version !== MD2_VERSION) {\n throw new Md2ParseError(`Unsupported MD2 version: ${version}`);\n }\n\n const header: Md2Header = {\n ident,\n version,\n skinWidth: view.getInt32(8, true),\n skinHeight: view.getInt32(12, true),\n frameSize: view.getInt32(16, true),\n numSkins: view.getInt32(20, true),\n numVertices: view.getInt32(24, true),\n numTexCoords: view.getInt32(28, true),\n numTriangles: view.getInt32(32, true),\n numGlCommands: view.getInt32(36, true),\n numFrames: view.getInt32(40, true),\n offsetSkins: view.getInt32(44, true),\n offsetTexCoords: view.getInt32(48, true),\n offsetTriangles: view.getInt32(52, true),\n offsetFrames: view.getInt32(56, true),\n offsetGlCommands: view.getInt32(60, true),\n offsetEnd: view.getInt32(64, true),\n };\n\n const expectedFrameSize = 40 + header.numVertices * 4;\n if (header.frameSize !== expectedFrameSize) {\n throw new Md2ParseError(`Unexpected frame size ${header.frameSize}, expected ${expectedFrameSize}`);\n }\n\n if (header.offsetEnd > buffer.byteLength) {\n throw new Md2ParseError('MD2 offset_end exceeds buffer length');\n }\n\n return header;\n}\n\nfunction parseSkins(buffer: ArrayBuffer, header: Md2Header): Md2Skin[] {\n const size = header.numSkins * 64;\n validateSection(buffer, header.offsetSkins, size, 'skins');\n const view = new DataView(buffer, header.offsetSkins, size);\n const skins: Md2Skin[] = [];\n for (let i = 0; i < header.numSkins; i += 1) {\n skins.push({ name: readCString(view, i * 64, 64) });\n }\n return skins;\n}\n\nfunction parseTexCoords(buffer: ArrayBuffer, header: Md2Header): Md2TexCoord[] {\n const size = header.numTexCoords * 4;\n validateSection(buffer, header.offsetTexCoords, size, 'texcoords');\n const view = new DataView(buffer, header.offsetTexCoords, size);\n const texCoords: Md2TexCoord[] = [];\n for (let i = 0; i < header.numTexCoords; i += 1) {\n const base = i * 4;\n texCoords.push({ s: view.getInt16(base, true), t: view.getInt16(base + 2, true) });\n }\n return texCoords;\n}\n\nfunction parseTriangles(buffer: ArrayBuffer, header: Md2Header): Md2Triangle[] {\n const size = header.numTriangles * 12;\n validateSection(buffer, header.offsetTriangles, size, 'triangles');\n const view = new DataView(buffer, header.offsetTriangles, size);\n const triangles: Md2Triangle[] = [];\n\n for (let i = 0; i < header.numTriangles; i += 1) {\n const base = i * 12;\n const vertexIndices: [number, number, number] = [\n view.getUint16(base, true),\n view.getUint16(base + 2, true),\n view.getUint16(base + 4, true),\n ];\n const texCoordIndices: [number, number, number] = [\n view.getUint16(base + 6, true),\n view.getUint16(base + 8, true),\n view.getUint16(base + 10, true),\n ];\n\n if (vertexIndices.some((v) => v >= header.numVertices) || texCoordIndices.some((t) => t >= header.numTexCoords)) {\n throw new Md2ParseError('Triangle references out of range vertex or texcoord');\n }\n\n triangles.push({ vertexIndices, texCoordIndices });\n }\n\n return triangles;\n}\n\nfunction parseFrames(buffer: ArrayBuffer, header: Md2Header): Md2Frame[] {\n const size = header.numFrames * header.frameSize;\n validateSection(buffer, header.offsetFrames, size, 'frames');\n const frames: Md2Frame[] = [];\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.offsetFrames + i * header.frameSize;\n const view = new DataView(buffer, base, header.frameSize);\n const scale: Vec3 = { x: view.getFloat32(0, true), y: view.getFloat32(4, true), z: view.getFloat32(8, true) };\n const translate: Vec3 = {\n x: view.getFloat32(12, true),\n y: view.getFloat32(16, true),\n z: view.getFloat32(20, true),\n };\n const name = readCString(view, 24, 16);\n const vertices: Md2Vertex[] = [];\n\n for (let v = 0; v < header.numVertices; v += 1) {\n const offset = 40 + v * 4;\n const position: Vec3 = {\n x: view.getUint8(offset) * scale.x + translate.x,\n y: view.getUint8(offset + 1) * scale.y + translate.y,\n z: view.getUint8(offset + 2) * scale.z + translate.z,\n };\n const normalIndex = view.getUint8(offset + 3);\n const normal = MD2_NORMALS[normalIndex];\n if (!normal) {\n throw new Md2ParseError(`Invalid normal index ${normalIndex} in frame ${name}`);\n }\n vertices.push({ position, normalIndex, normal });\n }\n\n frames.push({ name, vertices });\n }\n\n return frames;\n}\n\nfunction parseGlCommands(buffer: ArrayBuffer, header: Md2Header): Md2GlCommand[] {\n const size = header.numGlCommands * 4;\n validateSection(buffer, header.offsetGlCommands, size, 'gl commands');\n if (size === 0) {\n return [];\n }\n const view = new DataView(buffer, header.offsetGlCommands, size);\n const commands: Md2GlCommand[] = [];\n let cursor = 0;\n\n while (true) {\n if (cursor + 4 > size) {\n throw new Md2ParseError('GL command list ended unexpectedly');\n }\n const count = view.getInt32(cursor, true);\n cursor += 4;\n if (count === 0) break;\n const vertexCount = Math.abs(count);\n const vertices: Md2GlCommandVertex[] = [];\n const bytesNeeded = vertexCount * 12;\n if (cursor + bytesNeeded > size) {\n throw new Md2ParseError('GL command vertex block exceeds buffer');\n }\n for (let i = 0; i < vertexCount; i += 1) {\n const s = view.getFloat32(cursor, true);\n const t = view.getFloat32(cursor + 4, true);\n const vertexIndex = view.getInt32(cursor + 8, true);\n cursor += 12;\n if (vertexIndex < 0 || vertexIndex >= header.numVertices) {\n throw new Md2ParseError('GL command references invalid vertex index');\n }\n vertices.push({ s, t, vertexIndex });\n }\n commands.push({ mode: count > 0 ? 'strip' : 'fan', vertices });\n }\n\n if (cursor !== size) {\n throw new Md2ParseError('GL command list did not consume expected data');\n }\n\n return commands;\n}\n\nexport function parseMd2(buffer: ArrayBuffer): Md2Model {\n const header = parseHeader(buffer);\n const skins = parseSkins(buffer, header);\n const texCoords = parseTexCoords(buffer, header);\n const triangles = parseTriangles(buffer, header);\n const frames = parseFrames(buffer, header);\n const glCommands = parseGlCommands(buffer, header);\n\n return { header, skins, texCoords, triangles, frames, glCommands };\n}\n\nexport function groupMd2Animations(frames: readonly Md2Frame[]): Md2Animation[] {\n const animations: Md2Animation[] = [];\n let index = 0;\n while (index < frames.length) {\n const name = frames[index].name;\n const base = name.replace(/\\d+$/, '') || name;\n let end = index;\n while (end + 1 < frames.length) {\n const nextBase = frames[end + 1].name.replace(/\\d+$/, '') || frames[end + 1].name;\n if (nextBase !== base) break;\n end += 1;\n }\n animations.push({ name: base, firstFrame: index, lastFrame: end });\n index = end + 1;\n }\n return animations;\n}\n","export interface WebGLContextInitOptions {\n /**\n * Options passed to `canvas.getContext`. Defaults to antialias enabled to match the rerelease renderer's smoothing.\n */\n readonly contextAttributes?: WebGLContextAttributes;\n /**\n * Extensions that must be present. Missing entries throw during construction so callers can fall back early.\n */\n readonly requiredExtensions?: readonly string[];\n /**\n * Extensions that will be queried if available. Missing optional extensions are ignored.\n */\n readonly optionalExtensions?: readonly string[];\n}\n\nexport interface WebGLContextState {\n readonly gl: WebGL2RenderingContext;\n readonly extensions: Map<string, unknown>;\n /**\n * Returns true once a `webglcontextlost` event has been observed.\n */\n isLost(): boolean;\n /**\n * Registers a callback that fires on context loss. Returns an unsubscribe function.\n */\n onLost(callback: () => void): () => void;\n /**\n * Registers a callback that fires on context restoration. Returns an unsubscribe function.\n */\n onRestored(callback: () => void): () => void;\n /**\n * Remove event listeners and release references.\n */\n dispose(): void;\n}\n\nfunction configureDefaultGLState(gl: WebGL2RenderingContext): void {\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.enable(gl.CULL_FACE);\n gl.cullFace(gl.BACK);\n gl.enable(gl.BLEND);\n gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n}\n\nfunction queryExtensions(\n gl: WebGL2RenderingContext,\n required: readonly string[],\n optional: readonly string[],\n collector: Map<string, unknown>\n): void {\n for (const name of required) {\n const ext = gl.getExtension(name);\n if (!ext) {\n throw new Error(`Missing required WebGL extension: ${name}`);\n }\n collector.set(name, ext);\n }\n\n for (const name of optional) {\n const ext = gl.getExtension(name);\n if (ext) {\n collector.set(name, ext);\n }\n }\n}\n\nexport function createWebGLContext(\n canvas: HTMLCanvasElement,\n options: WebGLContextInitOptions = {}\n): WebGLContextState {\n const { contextAttributes, requiredExtensions = [], optionalExtensions = [] } = options;\n const gl = canvas.getContext('webgl2', contextAttributes ?? { antialias: true });\n if (!gl) {\n throw new Error('WebGL2 not supported or failed to initialize');\n }\n\n configureDefaultGLState(gl);\n\n const extensions = new Map<string, unknown>();\n queryExtensions(gl, requiredExtensions, optionalExtensions, extensions);\n\n let lost = false;\n const lostCallbacks = new Set<() => void>();\n const restoreCallbacks = new Set<() => void>();\n\n const lostListener = (event: Event): void => {\n lost = true;\n event.preventDefault();\n for (const callback of lostCallbacks) {\n callback();\n }\n };\n const restoreListener = (): void => {\n lost = false;\n for (const callback of restoreCallbacks) {\n callback();\n }\n };\n\n canvas.addEventListener('webglcontextlost', lostListener);\n canvas.addEventListener('webglcontextrestored', restoreListener);\n\n return {\n gl,\n extensions,\n isLost: () => lost,\n onLost(callback: () => void) {\n lostCallbacks.add(callback);\n return () => lostCallbacks.delete(callback);\n },\n onRestored(callback: () => void) {\n restoreCallbacks.add(callback);\n return () => restoreCallbacks.delete(callback);\n },\n dispose() {\n canvas.removeEventListener('webglcontextlost', lostListener);\n canvas.removeEventListener('webglcontextrestored', restoreListener);\n lostCallbacks.clear();\n restoreCallbacks.clear();\n extensions.clear();\n },\n };\n}\n","export interface ShaderSources {\n readonly vertex: string;\n readonly fragment: string;\n}\n\nfunction compileShader(gl: WebGL2RenderingContext, type: GLenum, source: string): WebGLShader {\n const shader = gl.createShader(type);\n if (!shader) {\n throw new Error('Failed to allocate shader');\n }\n\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n const ok = gl.getShaderParameter(shader, gl.COMPILE_STATUS) as boolean;\n if (!ok) {\n const log = gl.getShaderInfoLog(shader) ?? 'Unknown shader compile failure';\n gl.deleteShader(shader);\n throw new Error(log);\n }\n\n return shader;\n}\n\nfunction linkProgram(\n gl: WebGL2RenderingContext,\n vertexShader: WebGLShader,\n fragmentShader: WebGLShader,\n attributeLocations?: Record<string, number>\n): WebGLProgram {\n const program = gl.createProgram();\n if (!program) {\n throw new Error('Failed to allocate shader program');\n }\n\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n\n if (attributeLocations) {\n for (const [name, location] of Object.entries(attributeLocations)) {\n gl.bindAttribLocation(program, location, name);\n }\n }\n\n gl.linkProgram(program);\n const ok = gl.getProgramParameter(program, gl.LINK_STATUS) as boolean;\n if (!ok) {\n const log = gl.getProgramInfoLog(program) ?? 'Unknown shader link failure';\n gl.deleteProgram(program);\n throw new Error(log);\n }\n\n return program;\n}\n\nexport class ShaderProgram {\n readonly gl: WebGL2RenderingContext;\n readonly program: WebGLProgram;\n private readonly uniformLocations = new Map<string, WebGLUniformLocation | null>();\n private readonly attributeLocations = new Map<string, number>();\n\n private constructor(gl: WebGL2RenderingContext, program: WebGLProgram) {\n this.gl = gl;\n this.program = program;\n }\n\n static create(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n ): ShaderProgram {\n const vertexShader = compileShader(gl, gl.VERTEX_SHADER, sources.vertex);\n const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, sources.fragment);\n try {\n const program = linkProgram(gl, vertexShader, fragmentShader, attributeLocations);\n return new ShaderProgram(gl, program);\n } finally {\n gl.deleteShader(vertexShader);\n gl.deleteShader(fragmentShader);\n }\n }\n\n use(): void {\n this.gl.useProgram(this.program);\n }\n\n getUniformLocation(name: string): WebGLUniformLocation | null {\n if (!this.uniformLocations.has(name)) {\n const location = this.gl.getUniformLocation(this.program, name);\n this.uniformLocations.set(name, location);\n }\n\n return this.uniformLocations.get(name) ?? null;\n }\n\n getAttributeLocation(name: string): number {\n if (!this.attributeLocations.has(name)) {\n const location = this.gl.getAttribLocation(this.program, name);\n this.attributeLocations.set(name, location);\n }\n\n return this.attributeLocations.get(name) ?? -1;\n }\n\n dispose(): void {\n this.gl.deleteProgram(this.program);\n this.uniformLocations.clear();\n this.attributeLocations.clear();\n }\n}\n\nexport function createProgramFromSources(\n gl: WebGL2RenderingContext,\n sources: ShaderSources,\n attributeLocations?: Record<string, number>\n): ShaderProgram {\n return ShaderProgram.create(gl, sources, attributeLocations);\n}\n","export type BufferUsage = GLenum;\n\nexport interface VertexAttributeLayout {\n readonly index: number;\n readonly size: number;\n readonly type: GLenum;\n readonly normalized?: boolean;\n readonly stride?: number;\n readonly offset?: number;\n readonly divisor?: number;\n}\n\nexport class VertexBuffer {\n readonly gl: WebGL2RenderingContext;\n readonly buffer: WebGLBuffer;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW, target?: GLenum) {\n this.gl = gl;\n this.target = target ?? gl.ARRAY_BUFFER;\n const buffer = gl.createBuffer();\n if (!buffer) {\n throw new Error('Failed to allocate buffer');\n }\n this.buffer = buffer;\n gl.bindBuffer(this.target, this.buffer);\n gl.bufferData(this.target, 0, usage);\n }\n\n bind(): void {\n this.gl.bindBuffer(this.target, this.buffer);\n }\n\n upload(data: BufferSource, usage: BufferUsage = this.gl.STATIC_DRAW): void {\n this.bind();\n this.gl.bufferData(this.target, data, usage);\n }\n\n update(data: BufferSource, offset = 0): void {\n this.bind();\n this.gl.bufferSubData(this.target, offset, data);\n }\n\n dispose(): void {\n this.gl.deleteBuffer(this.buffer);\n }\n}\n\nexport class IndexBuffer extends VertexBuffer {\n constructor(gl: WebGL2RenderingContext, usage: BufferUsage = gl.STATIC_DRAW) {\n super(gl, usage, gl.ELEMENT_ARRAY_BUFFER);\n }\n}\n\nexport class VertexArray {\n readonly gl: WebGL2RenderingContext;\n readonly vao: WebGLVertexArrayObject;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const vao = gl.createVertexArray();\n if (!vao) {\n throw new Error('Failed to allocate vertex array object');\n }\n this.vao = vao;\n }\n\n bind(): void {\n this.gl.bindVertexArray(this.vao);\n }\n\n configureAttributes(layouts: readonly VertexAttributeLayout[], buffer?: VertexBuffer): void {\n this.bind();\n if (buffer) {\n buffer.bind();\n }\n\n for (const layout of layouts) {\n this.gl.enableVertexAttribArray(layout.index);\n this.gl.vertexAttribPointer(\n layout.index,\n layout.size,\n layout.type,\n layout.normalized ?? false,\n layout.stride ?? 0,\n layout.offset ?? 0\n );\n if (layout.divisor !== undefined) {\n this.gl.vertexAttribDivisor(layout.index, layout.divisor);\n }\n }\n }\n\n dispose(): void {\n this.gl.deleteVertexArray(this.vao);\n }\n}\n\nexport interface TextureParameters {\n readonly wrapS?: GLenum;\n readonly wrapT?: GLenum;\n readonly minFilter?: GLenum;\n readonly magFilter?: GLenum;\n}\n\nexport class Texture2D {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext, target: GLenum = gl.TEXTURE_2D) {\n this.gl = gl;\n this.target = target;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate texture');\n }\n this.texture = texture;\n }\n\n bind(unit = 0): void {\n this.gl.activeTexture(this.gl.TEXTURE0 + unit);\n this.gl.bindTexture(this.target, this.texture);\n }\n\n setParameters(params: TextureParameters): void {\n this.bind();\n if (params.wrapS !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_S, params.wrapS);\n }\n if (params.wrapT !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_WRAP_T, params.wrapT);\n }\n if (params.minFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MIN_FILTER, params.minFilter);\n }\n if (params.magFilter !== undefined) {\n this.gl.texParameteri(this.target, this.gl.TEXTURE_MAG_FILTER, params.magFilter);\n }\n }\n\n uploadImage(\n level: number,\n internalFormat: GLenum,\n width: number,\n height: number,\n border: number,\n format: GLenum,\n type: GLenum,\n data: ArrayBufferView | null\n ): void {\n this.bind();\n this.gl.texImage2D(this.target, level, internalFormat, width, height, border, format, type, data);\n }\n\n dispose(): void {\n this.gl.deleteTexture(this.texture);\n }\n}\n\nexport class Framebuffer {\n readonly gl: WebGL2RenderingContext;\n readonly framebuffer: WebGLFramebuffer;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n const framebuffer = gl.createFramebuffer();\n if (!framebuffer) {\n throw new Error('Failed to allocate framebuffer');\n }\n this.framebuffer = framebuffer;\n }\n\n bind(target: GLenum = this.gl.FRAMEBUFFER): void {\n this.gl.bindFramebuffer(target, this.framebuffer);\n }\n\n attachTexture2D(attachment: GLenum, texture: Texture2D, level = 0): void {\n this.bind();\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, attachment, texture.target, texture.texture, level);\n }\n\n dispose(): void {\n this.gl.deleteFramebuffer(this.framebuffer);\n }\n}\n","import { SURF_NONE, type SurfaceFlag } from '@quake2ts/shared';\nimport {\n IndexBuffer,\n Texture2D,\n VertexArray,\n VertexBuffer,\n type VertexAttributeLayout,\n} from './resources.js';\n\nexport interface BspLightmapData {\n readonly width: number;\n readonly height: number;\n readonly samples: Uint8Array;\n}\n\nexport interface BspSurfaceInput {\n readonly vertices: ReadonlyArray<number> | Float32Array;\n readonly textureCoords: ReadonlyArray<number> | Float32Array;\n readonly lightmapCoords?: ReadonlyArray<number> | Float32Array;\n readonly indices?: ReadonlyArray<number> | Uint16Array | Uint32Array;\n readonly texture: string;\n readonly surfaceFlags?: SurfaceFlag;\n readonly lightmap?: BspLightmapData;\n}\n\nexport interface LightmapPlacement {\n readonly atlasIndex: number;\n readonly offset: [number, number];\n readonly scale: [number, number];\n}\n\nexport interface BspSurfaceGeometry {\n readonly vao: VertexArray;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly indexCount: number;\n readonly texture: string;\n readonly surfaceFlags: SurfaceFlag;\n readonly lightmap?: LightmapPlacement;\n // CPU copies retained for deterministic tests and debugging.\n readonly vertexData: Float32Array;\n readonly indexData: Uint16Array;\n}\n\nexport interface LightmapAtlas {\n readonly texture: Texture2D;\n readonly width: number;\n readonly height: number;\n readonly pixels: Uint8Array;\n}\n\nexport interface BspBuildOptions {\n readonly atlasSize?: number;\n readonly lightmapPadding?: number;\n}\n\nexport interface BspGeometryBuildResult {\n readonly surfaces: readonly BspSurfaceGeometry[];\n readonly lightmaps: readonly LightmapAtlas[];\n}\n\nconst FLOAT_BYTES = 4;\nconst STRIDE = 7 * FLOAT_BYTES;\n\nexport const BSP_VERTEX_LAYOUT: readonly VertexAttributeLayout[] = [\n // Position\n { index: 0, size: 3, type: 0x1406, stride: STRIDE, offset: 0 },\n // Diffuse UV\n { index: 1, size: 2, type: 0x1406, stride: STRIDE, offset: 3 * FLOAT_BYTES },\n // Lightmap UV\n { index: 2, size: 2, type: 0x1406, stride: STRIDE, offset: 5 * FLOAT_BYTES },\n];\n\ninterface LightmapPlacementInfo {\n readonly atlasIndex: number;\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\ninterface AtlasBuilder {\n readonly width: number;\n readonly height: number;\n readonly padding: number;\n readonly data: Uint8Array;\n cursorX: number;\n cursorY: number;\n rowHeight: number;\n}\n\nfunction createAtlasBuilder(size: number, padding: number): AtlasBuilder {\n const channelCount = 4; // We upload as RGBA for compatibility.\n return {\n width: size,\n height: size,\n padding,\n data: new Uint8Array(size * size * channelCount),\n cursorX: 0,\n cursorY: 0,\n rowHeight: 0,\n };\n}\n\nfunction detectChannels(lightmap: BspLightmapData): number {\n const pixels = lightmap.width * lightmap.height;\n if (pixels === 0) {\n throw new Error('Invalid lightmap with zero area');\n }\n const channels = lightmap.samples.byteLength / pixels;\n if (!Number.isInteger(channels) || channels < 3 || channels > 4) {\n throw new Error('Unsupported lightmap channel count');\n }\n return channels;\n}\n\nfunction writeLightmapIntoAtlas(\n atlas: AtlasBuilder,\n placement: LightmapPlacementInfo,\n lightmap: BspLightmapData\n): void {\n const channels = detectChannels(lightmap);\n const stride = atlas.width * 4;\n const startX = placement.x + atlas.padding;\n const startY = placement.y + atlas.padding;\n let srcIndex = 0;\n\n for (let y = 0; y < lightmap.height; y++) {\n const destRow = (startY + y) * stride + startX * 4;\n for (let x = 0; x < lightmap.width; x++) {\n const dest = destRow + x * 4;\n atlas.data[dest] = lightmap.samples[srcIndex];\n atlas.data[dest + 1] = lightmap.samples[srcIndex + 1];\n atlas.data[dest + 2] = lightmap.samples[srcIndex + 2];\n atlas.data[dest + 3] = channels === 4 ? lightmap.samples[srcIndex + 3] : 255;\n srcIndex += channels;\n }\n }\n}\n\nfunction placeLightmap(\n builders: AtlasBuilder[],\n lightmap: BspLightmapData,\n options: Required<BspBuildOptions>\n): { placement: LightmapPlacementInfo; atlas: AtlasBuilder } {\n const paddedWidth = lightmap.width + options.lightmapPadding * 2;\n const paddedHeight = lightmap.height + options.lightmapPadding * 2;\n if (paddedWidth > options.atlasSize || paddedHeight > options.atlasSize) {\n throw new Error('Lightmap too large for atlas');\n }\n\n for (const atlas of builders) {\n if (atlas.cursorX + paddedWidth > atlas.width) {\n atlas.cursorX = 0;\n atlas.cursorY += atlas.rowHeight + options.lightmapPadding;\n atlas.rowHeight = 0;\n }\n\n if (atlas.cursorY + paddedHeight > atlas.height) {\n continue;\n }\n\n const placement: LightmapPlacementInfo = {\n atlasIndex: builders.indexOf(atlas),\n x: atlas.cursorX,\n y: atlas.cursorY,\n width: lightmap.width,\n height: lightmap.height,\n };\n\n atlas.cursorX += paddedWidth + options.lightmapPadding;\n atlas.rowHeight = Math.max(atlas.rowHeight, paddedHeight);\n return { placement, atlas };\n }\n\n const atlas = createAtlasBuilder(options.atlasSize, options.lightmapPadding);\n builders.push(atlas);\n const placement: LightmapPlacementInfo = { atlasIndex: builders.length - 1, x: 0, y: 0, width: lightmap.width, height: lightmap.height };\n atlas.cursorX = paddedWidth + options.lightmapPadding;\n atlas.rowHeight = paddedHeight;\n return { placement, atlas };\n}\n\nfunction ensureFloat32(array: ReadonlyArray<number> | Float32Array): Float32Array {\n return array instanceof Float32Array ? array : new Float32Array(array);\n}\n\nfunction ensureIndexArray(indices: ReadonlyArray<number> | Uint16Array | Uint32Array | undefined, vertexCount: number): Uint16Array {\n if (!indices) {\n const generated = new Uint16Array(vertexCount);\n for (let i = 0; i < vertexCount; i++) {\n generated[i] = i;\n }\n return generated;\n }\n\n const converted = indices instanceof Uint16Array ? indices : new Uint16Array(indices);\n return converted;\n}\n\nfunction remapLightmapCoords(\n coords: Float32Array,\n placement: LightmapPlacement,\n): Float32Array {\n const remapped = new Float32Array(coords.length);\n for (let i = 0; i < coords.length; i += 2) {\n remapped[i] = placement.offset[0] + coords[i] * placement.scale[0];\n remapped[i + 1] = placement.offset[1] + coords[i + 1] * placement.scale[1];\n }\n return remapped;\n}\n\nfunction buildVertexData(\n surface: BspSurfaceInput,\n placement: LightmapPlacement | undefined\n): Float32Array {\n const vertices = ensureFloat32(surface.vertices);\n const texCoords = ensureFloat32(surface.textureCoords);\n const lightmapCoords = placement\n ? remapLightmapCoords(ensureFloat32(surface.lightmapCoords ?? surface.textureCoords), placement)\n : ensureFloat32(surface.lightmapCoords ?? new Float32Array(texCoords.length));\n\n const vertexCount = vertices.length / 3;\n if (texCoords.length / 2 !== vertexCount) {\n throw new Error('Texture coordinates count mismatch');\n }\n if (lightmapCoords.length / 2 !== vertexCount) {\n throw new Error('Lightmap coordinates count mismatch');\n }\n\n const interleaved = new Float32Array(vertexCount * 7);\n for (let i = 0; i < vertexCount; i++) {\n const v = i * 3;\n const t = i * 2;\n const o = i * 7;\n interleaved[o] = vertices[v];\n interleaved[o + 1] = vertices[v + 1];\n interleaved[o + 2] = vertices[v + 2];\n interleaved[o + 3] = texCoords[t];\n interleaved[o + 4] = texCoords[t + 1];\n interleaved[o + 5] = lightmapCoords[t];\n interleaved[o + 6] = lightmapCoords[t + 1];\n }\n return interleaved;\n}\n\nexport function buildBspGeometry(\n gl: WebGL2RenderingContext,\n surfaces: readonly BspSurfaceInput[],\n options: BspBuildOptions = {}\n): BspGeometryBuildResult {\n const resolved: Required<BspBuildOptions> = {\n atlasSize: options.atlasSize ?? 1024,\n lightmapPadding: options.lightmapPadding ?? 1,\n };\n\n const atlasBuilders: AtlasBuilder[] = [];\n const placements = new Map<number, LightmapPlacement>();\n\n surfaces.forEach((surface, index) => {\n if (!surface.lightmap) {\n return;\n }\n const { placement, atlas } = placeLightmap(atlasBuilders, surface.lightmap, resolved);\n writeLightmapIntoAtlas(atlas, placement, surface.lightmap);\n placements.set(index, {\n atlasIndex: placement.atlasIndex,\n offset: [\n (placement.x + resolved.lightmapPadding) / resolved.atlasSize,\n (placement.y + resolved.lightmapPadding) / resolved.atlasSize,\n ],\n scale: [placement.width / resolved.atlasSize, placement.height / resolved.atlasSize],\n });\n });\n\n const lightmaps: LightmapAtlas[] = atlasBuilders.map((builder) => {\n const texture = new Texture2D(gl);\n texture.setParameters({\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n });\n texture.uploadImage(0, gl.RGBA, builder.width, builder.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, builder.data);\n return { texture, width: builder.width, height: builder.height, pixels: builder.data };\n });\n\n const results: BspSurfaceGeometry[] = surfaces.map((surface, index) => {\n const placement = placements.get(index);\n const vertexData = buildVertexData(surface, placement);\n const indexData = ensureIndexArray(surface.indices, vertexData.length / 7);\n\n const vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW, gl.ARRAY_BUFFER);\n vertexBuffer.upload(vertexData as unknown as BufferSource);\n\n const indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n indexBuffer.upload(indexData as unknown as BufferSource);\n\n const vao = new VertexArray(gl);\n vao.configureAttributes(BSP_VERTEX_LAYOUT, vertexBuffer);\n\n return {\n vao,\n vertexBuffer,\n indexBuffer,\n indexCount: indexData.length,\n texture: surface.texture,\n surfaceFlags: surface.surfaceFlags ?? SURF_NONE,\n lightmap: placement,\n vertexData,\n indexData,\n };\n });\n\n return { surfaces: results, lightmaps };\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n} from './host.js';\nimport { ConfigStringRegistry } from './configstrings.js';\nimport { FixedTimestepLoop, type LoopCallbacks, type LoopOptions } from './loop.js';\nimport { EngineRuntime, createEngineRuntime } from './runtime.js';\n\nexport interface TraceResult {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly fraction: number;\n readonly hit?: Vec3;\n}\n\nexport interface EngineImports {\n trace(start: Vec3, end: Vec3): TraceResult;\n}\n\nexport interface EngineExports {\n init(): void;\n shutdown(): void;\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop;\n}\n\nexport function createEngine(imports: EngineImports): EngineExports {\n return {\n init() {\n void imports.trace({ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 });\n },\n shutdown() {\n /* no-op for bootstrap */\n },\n createMainLoop(callbacks: LoopCallbacks, options?: Partial<LoopOptions>): FixedTimestepLoop {\n return new FixedTimestepLoop(callbacks, options);\n },\n };\n}\n\nexport { FixedTimestepLoop };\nexport { ConfigStringRegistry };\nexport { Cvar, CvarRegistry } from './cvars.js';\nexport type { FixedStepContext, LoopCallbacks, LoopOptions, RenderContext } from './loop.js';\nexport { PakArchive, PakParseError, calculatePakChecksum } from './assets/pak.js';\nexport { VirtualFileSystem } from './assets/vfs.js';\nexport {\n ingestPaks,\n PakIngestionError,\n type PakIngestionOptions,\n type PakIngestionProgress,\n type PakIngestionResult,\n type PakSource,\n} from './assets/ingestion.js';\nexport { LruCache } from './assets/cache.js';\nexport { filesToPakSources, ingestPakFiles, wireDropTarget, wireFileInput } from './assets/browserIngestion.js';\nexport {\n Md2Loader,\n Md2ParseError,\n groupMd2Animations,\n parseMd2,\n type Md2Animation,\n type Md2Frame,\n type Md2GlCommand,\n type Md2Model,\n} from './assets/md2.js';\nexport {\n EngineHost,\n type ClientRenderer,\n type EngineHostOptions,\n type GameFrameResult,\n type GameRenderSample,\n type GameSimulation,\n};\nexport { EngineRuntime, createEngineRuntime };\nexport { createWebGLContext, type WebGLContextInitOptions, type WebGLContextState } from './render/context.js';\nexport { ShaderProgram, createProgramFromSources, type ShaderSources } from './render/shaderProgram.js';\nexport {\n Framebuffer,\n IndexBuffer,\n Texture2D,\n VertexArray,\n VertexBuffer,\n type BufferUsage,\n type TextureParameters,\n type VertexAttributeLayout,\n} from './render/resources.js';\nexport {\n BSP_VERTEX_LAYOUT,\n buildBspGeometry,\n type BspGeometryBuildResult,\n type BspLightmapData,\n type BspSurfaceGeometry,\n type BspSurfaceInput,\n type LightmapAtlas,\n type LightmapPlacement,\n} from './render/bsp.js';\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) trace.allsolid = true;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { ZERO_VEC3 } from '@quake2ts/shared';\n\nexport enum MoveType {\n None = 0,\n Noclip = 1,\n Push = 2,\n Stop = 3,\n Walk = 4,\n Step = 5,\n Fly = 6,\n Toss = 7,\n FlyMissile = 8,\n Bounce = 9,\n}\n\nexport enum Solid {\n Not = 0,\n Trigger = 1,\n BoundingBox = 2,\n Bsp = 3,\n}\n\nexport enum DeadFlag {\n Alive = 0,\n Dying = 1,\n Dead = 2,\n Respawnable = 3,\n}\n\nexport type ThinkCallback = (self: Entity) => void;\nexport type TouchCallback = (self: Entity, other: Entity | null) => void;\nexport type UseCallback = (self: Entity, other: Entity | null) => void;\nexport type PainCallback = (self: Entity, other: Entity | null, kick: number, damage: number) => void;\nexport type DieCallback = (\n self: Entity,\n inflictor: Entity | null,\n attacker: Entity | null,\n damage: number,\n) => void;\n\nexport type EntityFieldType =\n | 'int'\n | 'float'\n | 'string'\n | 'vec3'\n | 'boolean'\n | 'entity'\n | 'callback';\n\nexport interface EntityFieldDescriptor<K extends keyof Entity = keyof Entity> {\n readonly name: K;\n readonly type: EntityFieldType;\n readonly save: boolean;\n}\n\nconst ZERO: Vec3 = { ...ZERO_VEC3 } as const;\n\nfunction copyVec3(): Vec3 {\n return { ...ZERO };\n}\n\nexport class Entity {\n readonly index: number;\n\n inUse = false;\n freePending = false;\n linkPrevious: Entity | null = null;\n linkNext: Entity | null = null;\n\n classname = '';\n spawnflags = 0;\n target?: string;\n targetname?: string;\n team?: string;\n message?: string;\n\n origin: Vec3 = copyVec3();\n old_origin: Vec3 = copyVec3();\n velocity: Vec3 = copyVec3();\n avelocity: Vec3 = copyVec3();\n angles: Vec3 = copyVec3();\n\n mins: Vec3 = copyVec3();\n maxs: Vec3 = copyVec3();\n size: Vec3 = copyVec3();\n mass = 0;\n gravity = 1;\n movetype: MoveType = MoveType.None;\n\n modelindex = 0;\n frame = 0;\n skin = 0;\n effects = 0;\n renderfx = 0;\n\n health = 0;\n max_health = 0;\n takedamage = false;\n dmg = 0;\n deadflag: DeadFlag = DeadFlag.Alive;\n\n enemy: Entity | null = null;\n movetarget: Entity | null = null;\n goalentity: Entity | null = null;\n ideal_yaw = 0;\n yaw_speed = 0;\n\n groundentity: Entity | null = null;\n groundentity_linkcount = 0;\n waterlevel = 0;\n watertype = 0;\n\n nextthink = 0;\n think?: ThinkCallback;\n touch?: TouchCallback;\n use?: UseCallback;\n pain?: PainCallback;\n die?: DieCallback;\n\n solid: Solid = Solid.Not;\n flags = 0;\n svflags = 0;\n\n constructor(index: number) {\n this.index = index;\n }\n\n reset(): void {\n this.inUse = false;\n this.freePending = false;\n this.linkPrevious = null;\n this.linkNext = null;\n\n this.classname = '';\n this.spawnflags = 0;\n this.target = undefined;\n this.targetname = undefined;\n this.team = undefined;\n this.message = undefined;\n\n this.origin = copyVec3();\n this.old_origin = copyVec3();\n this.velocity = copyVec3();\n this.avelocity = copyVec3();\n this.angles = copyVec3();\n\n this.mins = copyVec3();\n this.maxs = copyVec3();\n this.size = copyVec3();\n this.mass = 0;\n this.gravity = 1;\n this.movetype = MoveType.None;\n\n this.modelindex = 0;\n this.frame = 0;\n this.skin = 0;\n this.effects = 0;\n this.renderfx = 0;\n\n this.health = 0;\n this.max_health = 0;\n this.takedamage = false;\n this.dmg = 0;\n this.deadflag = DeadFlag.Alive;\n\n this.enemy = null;\n this.movetarget = null;\n this.goalentity = null;\n this.ideal_yaw = 0;\n this.yaw_speed = 0;\n\n this.groundentity = null;\n this.groundentity_linkcount = 0;\n this.waterlevel = 0;\n this.watertype = 0;\n\n this.nextthink = 0;\n this.think = undefined;\n this.touch = undefined;\n this.use = undefined;\n this.pain = undefined;\n this.die = undefined;\n\n this.solid = Solid.Not;\n this.flags = 0;\n this.svflags = 0;\n }\n}\n\nexport const ENTITY_FIELD_METADATA: readonly EntityFieldDescriptor[] = [\n { name: 'classname', type: 'string', save: true },\n { name: 'spawnflags', type: 'int', save: true },\n { name: 'target', type: 'string', save: true },\n { name: 'targetname', type: 'string', save: true },\n { name: 'team', type: 'string', save: true },\n { name: 'message', type: 'string', save: true },\n { name: 'origin', type: 'vec3', save: true },\n { name: 'old_origin', type: 'vec3', save: true },\n { name: 'velocity', type: 'vec3', save: true },\n { name: 'avelocity', type: 'vec3', save: true },\n { name: 'angles', type: 'vec3', save: true },\n { name: 'mins', type: 'vec3', save: true },\n { name: 'maxs', type: 'vec3', save: true },\n { name: 'size', type: 'vec3', save: true },\n { name: 'mass', type: 'int', save: true },\n { name: 'gravity', type: 'float', save: true },\n { name: 'movetype', type: 'int', save: true },\n { name: 'modelindex', type: 'int', save: true },\n { name: 'frame', type: 'int', save: true },\n { name: 'skin', type: 'int', save: true },\n { name: 'effects', type: 'int', save: true },\n { name: 'renderfx', type: 'int', save: true },\n { name: 'health', type: 'int', save: true },\n { name: 'max_health', type: 'int', save: true },\n { name: 'takedamage', type: 'boolean', save: true },\n { name: 'dmg', type: 'int', save: true },\n { name: 'deadflag', type: 'int', save: true },\n { name: 'enemy', type: 'entity', save: true },\n { name: 'movetarget', type: 'entity', save: true },\n { name: 'goalentity', type: 'entity', save: true },\n { name: 'ideal_yaw', type: 'float', save: true },\n { name: 'yaw_speed', type: 'float', save: true },\n { name: 'groundentity', type: 'entity', save: true },\n { name: 'groundentity_linkcount', type: 'int', save: true },\n { name: 'waterlevel', type: 'int', save: true },\n { name: 'watertype', type: 'int', save: true },\n { name: 'nextthink', type: 'float', save: true },\n { name: 'solid', type: 'int', save: true },\n { name: 'flags', type: 'int', save: true },\n { name: 'svflags', type: 'int', save: true },\n { name: 'think', type: 'callback', save: false },\n { name: 'touch', type: 'callback', save: false },\n { name: 'use', type: 'callback', save: false },\n { name: 'pain', type: 'callback', save: false },\n { name: 'die', type: 'callback', save: false },\n];\n","import { Entity } from './entity.js';\n\nconst MAX_EDICTS = 2048;\nconst WORLD_INDEX = 0;\n\nexport class EntityPool implements Iterable<Entity> {\n private readonly entities: Entity[];\n private readonly freeList: number[] = [];\n private readonly pendingFree: number[] = [];\n private activeHead: Entity | null = null;\n\n constructor(maxEntities = MAX_EDICTS) {\n if (maxEntities < 1 || !Number.isInteger(maxEntities)) {\n throw new Error('EntityPool requires a positive integer size');\n }\n\n this.entities = new Array<Entity>(maxEntities);\n\n for (let i = 0; i < maxEntities; i += 1) {\n this.entities[i] = new Entity(i);\n if (i !== WORLD_INDEX) {\n this.freeList.push(i);\n }\n }\n\n const world = this.entities[WORLD_INDEX];\n world.inUse = true;\n world.classname = 'worldspawn';\n this.activeHead = world;\n }\n\n get world(): Entity {\n return this.entities[WORLD_INDEX];\n }\n\n get capacity(): number {\n return this.entities.length;\n }\n\n get activeCount(): number {\n let count = 0;\n for (const _ of this) {\n count += 1;\n }\n return count;\n }\n\n [Symbol.iterator](): Iterator<Entity> {\n let current = this.activeHead;\n return {\n next: () => {\n if (!current) {\n return { done: true, value: undefined } as const;\n }\n const value = current;\n current = current.linkNext;\n return { done: false, value };\n },\n };\n }\n\n spawn(): Entity {\n const index = this.freeList.pop();\n if (index === undefined) {\n throw new Error('No free entities available');\n }\n\n const entity = this.entities[index];\n entity.reset();\n entity.inUse = true;\n this.link(entity);\n return entity;\n }\n\n deferFree(entity: Entity): void {\n if (entity.index === WORLD_INDEX) {\n throw new Error('Cannot free world entity');\n }\n\n if (!entity.inUse || entity.freePending) {\n return;\n }\n\n this.unlink(entity);\n entity.inUse = false;\n entity.freePending = true;\n this.pendingFree.push(entity.index);\n }\n\n flushFreeList(): void {\n if (this.pendingFree.length === 0) {\n return;\n }\n\n for (const index of this.pendingFree) {\n const entity = this.entities[index];\n entity.reset();\n this.freeList.push(index);\n }\n\n this.pendingFree.length = 0;\n }\n\n private link(entity: Entity): void {\n entity.linkNext = this.activeHead;\n if (this.activeHead) {\n this.activeHead.linkPrevious = entity;\n }\n this.activeHead = entity;\n entity.linkPrevious = null;\n }\n\n private unlink(entity: Entity): void {\n if (entity.linkPrevious) {\n entity.linkPrevious.linkNext = entity.linkNext;\n }\n if (entity.linkNext) {\n entity.linkNext.linkPrevious = entity.linkPrevious;\n }\n if (this.activeHead === entity) {\n this.activeHead = entity.linkNext;\n }\n\n entity.linkPrevious = null;\n entity.linkNext = null;\n }\n}\n","import type { Entity } from './entity.js';\n\ninterface ScheduledThink {\n readonly time: number;\n readonly entity: Entity;\n}\n\nexport class ThinkScheduler {\n private readonly queue: ScheduledThink[] = [];\n\n schedule(entity: Entity, timeSeconds: number): void {\n entity.nextthink = timeSeconds;\n this.queue.push({ entity, time: timeSeconds });\n this.queue.sort((a, b) => (a.time === b.time ? a.entity.index - b.entity.index : a.time - b.time));\n }\n\n cancel(entity: Entity): void {\n if (this.queue.length === 0) {\n return;\n }\n for (let i = this.queue.length - 1; i >= 0; i -= 1) {\n if (this.queue[i].entity === entity) {\n this.queue.splice(i, 1);\n }\n }\n }\n\n runDueThinks(currentTimeSeconds: number): void {\n while (this.queue.length > 0) {\n const next = this.queue[0];\n if (next.time > currentTimeSeconds) {\n break;\n }\n\n this.queue.shift();\n const { entity, time } = next;\n if (!entity.inUse || entity.freePending) {\n continue;\n }\n if (!entity.think) {\n continue;\n }\n if (entity.nextthink !== time) {\n continue;\n }\n\n entity.think(entity);\n }\n }\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { Entity } from './entity.js';\nimport { EntityPool } from './pool.js';\nimport { ThinkScheduler } from './thinkScheduler.js';\n\ninterface Bounds {\n min: Vec3;\n max: Vec3;\n}\n\nfunction computeBounds(entity: Entity): Bounds {\n return {\n min: {\n x: entity.origin.x + entity.mins.x,\n y: entity.origin.y + entity.mins.y,\n z: entity.origin.z + entity.mins.z,\n },\n max: {\n x: entity.origin.x + entity.maxs.x,\n y: entity.origin.y + entity.maxs.y,\n z: entity.origin.z + entity.maxs.z,\n },\n };\n}\n\nfunction boundsIntersect(a: Bounds, b: Bounds): boolean {\n return !(\n a.min.x > b.max.x ||\n a.max.x < b.min.x ||\n a.min.y > b.max.y ||\n a.max.y < b.min.y ||\n a.min.z > b.max.z ||\n a.max.z < b.min.z\n );\n}\n\nexport class EntitySystem {\n private readonly pool: EntityPool;\n private readonly thinkScheduler: ThinkScheduler;\n private currentTimeSeconds = 0;\n\n constructor(maxEntities?: number) {\n this.pool = new EntityPool(maxEntities);\n this.thinkScheduler = new ThinkScheduler();\n }\n\n get world(): Entity {\n return this.pool.world;\n }\n\n get activeCount(): number {\n return this.pool.activeCount;\n }\n\n get timeSeconds(): number {\n return this.currentTimeSeconds;\n }\n\n forEachEntity(callback: (entity: Entity) => void): void {\n for (const entity of this.pool) {\n callback(entity);\n }\n }\n\n spawn(): Entity {\n return this.pool.spawn();\n }\n\n free(entity: Entity): void {\n this.thinkScheduler.cancel(entity);\n this.pool.deferFree(entity);\n }\n\n scheduleThink(entity: Entity, nextThinkSeconds: number): void {\n this.thinkScheduler.schedule(entity, nextThinkSeconds);\n }\n\n beginFrame(timeSeconds: number): void {\n this.currentTimeSeconds = timeSeconds;\n }\n\n runFrame(): void {\n this.thinkScheduler.runDueThinks(this.currentTimeSeconds);\n this.runTouches();\n this.pool.flushFreeList();\n }\n\n private runTouches(): void {\n const world = this.pool.world;\n const activeEntities: Entity[] = [];\n for (const entity of this.pool) {\n if (entity === world) {\n continue;\n }\n if (!entity.inUse || entity.freePending) {\n continue;\n }\n activeEntities.push(entity);\n }\n\n for (let i = 0; i < activeEntities.length; i += 1) {\n const first = activeEntities[i];\n let firstBounds: Bounds | null = null;\n for (let j = i + 1; j < activeEntities.length; j += 1) {\n const second = activeEntities[j];\n if (!first.touch && !second.touch) {\n continue;\n }\n if (!firstBounds) {\n firstBounds = computeBounds(first);\n }\n const secondBounds = computeBounds(second);\n if (!boundsIntersect(firstBounds, secondBounds)) {\n continue;\n }\n if (first.touch) {\n first.touch(first, second);\n }\n if (second.touch) {\n second.touch(second, first);\n }\n }\n }\n }\n}\n","import type { FixedStepContext } from '@quake2ts/engine';\n\nexport interface GameFrameContext extends FixedStepContext {\n readonly timeMs: number;\n readonly previousTimeMs: number;\n readonly deltaSeconds: number;\n}\n\nexport type GameFrameStageName = 'prep' | 'simulate' | 'finish';\nexport type GameFrameStage = (context: GameFrameContext) => void;\n\nexport interface GameFrameStages {\n prep?(context: GameFrameContext): void;\n simulate?(context: GameFrameContext): void;\n finish?(context: GameFrameContext): void;\n}\n\nconst orderedStageNames: readonly GameFrameStageName[] = [\n 'prep',\n 'simulate',\n 'finish',\n];\n\ntype StageBuckets = Record<GameFrameStageName, (GameFrameStage | undefined)[]>;\ntype StageCounts = Record<GameFrameStageName, number>;\ntype StageCompactionFlags = Record<GameFrameStageName, boolean>;\n\nexport class GameFrameLoop {\n private timeMs = 0;\n private frame = 0;\n private readonly stageHandlers: StageBuckets = {\n prep: [],\n simulate: [],\n finish: [],\n };\n private readonly stageCounts: StageCounts = {\n prep: 0,\n simulate: 0,\n finish: 0,\n };\n private readonly stageCompactionNeeded: StageCompactionFlags = {\n prep: false,\n simulate: false,\n finish: false,\n };\n\n constructor(initialStages?: GameFrameStages) {\n if (initialStages) {\n for (const stageName of orderedStageNames) {\n const handler = initialStages[stageName];\n if (handler) {\n this.addStage(stageName, handler);\n }\n }\n }\n }\n\n addStage(stage: GameFrameStageName, handler: GameFrameStage): () => void {\n const handlers = this.stageHandlers[stage];\n handlers.push(handler);\n this.stageCounts[stage] += 1;\n\n return () => {\n const index = handlers.indexOf(handler);\n if (index >= 0 && handlers[index]) {\n handlers[index] = undefined;\n this.stageCounts[stage] -= 1;\n this.stageCompactionNeeded[stage] = true;\n }\n };\n }\n\n reset(startTimeMs: number): void {\n this.timeMs = startTimeMs;\n this.frame = 0;\n }\n\n advance(step: FixedStepContext): GameFrameContext {\n const previousTimeMs = this.timeMs;\n this.timeMs = previousTimeMs + step.deltaMs;\n this.frame = step.frame;\n\n const context: GameFrameContext = {\n ...step,\n timeMs: this.timeMs,\n previousTimeMs,\n deltaSeconds: step.deltaMs / 1000,\n };\n\n this.runStage('prep', context);\n\n if (this.stageCounts.simulate === 0) {\n throw new Error('GameFrameLoop requires at least one simulate stage');\n }\n\n this.runStage('simulate', context);\n this.runStage('finish', context);\n\n return context;\n }\n\n private runStage(stage: GameFrameStageName, context: GameFrameContext): void {\n const handlers = this.stageHandlers[stage];\n for (let i = 0; i < handlers.length; i += 1) {\n const handler = handlers[i];\n if (!handler) {\n continue;\n }\n handler(context);\n }\n\n if (this.stageCompactionNeeded[stage]) {\n this.compactStageHandlers(stage);\n }\n }\n\n private compactStageHandlers(stage: GameFrameStageName): void {\n const handlers = this.stageHandlers[stage];\n let writeIndex = 0;\n for (let readIndex = 0; readIndex < handlers.length; readIndex += 1) {\n const handler = handlers[readIndex];\n if (handler) {\n handlers[writeIndex] = handler;\n writeIndex += 1;\n }\n }\n handlers.length = writeIndex;\n this.stageCompactionNeeded[stage] = false;\n }\n\n get time(): number {\n return this.timeMs;\n }\n\n get frameNumber(): number {\n return this.frame;\n }\n}\n","import type { GameFrameContext } from './loop.js';\n\nexport interface LevelFrameState {\n readonly frameNumber: number;\n readonly timeSeconds: number;\n readonly previousTimeSeconds: number;\n readonly deltaSeconds: number;\n}\n\nconst ZERO_STATE: LevelFrameState = {\n frameNumber: 0,\n timeSeconds: 0,\n previousTimeSeconds: 0,\n deltaSeconds: 0,\n};\n\nexport class LevelClock {\n private state: LevelFrameState = ZERO_STATE;\n\n start(startTimeMs: number): void {\n const startSeconds = startTimeMs / 1000;\n this.state = {\n frameNumber: 0,\n timeSeconds: startSeconds,\n previousTimeSeconds: startSeconds,\n deltaSeconds: 0,\n };\n }\n\n tick(context: GameFrameContext): LevelFrameState {\n this.state = {\n frameNumber: context.frame,\n timeSeconds: context.timeMs / 1000,\n previousTimeSeconds: context.previousTimeMs / 1000,\n deltaSeconds: context.deltaSeconds,\n };\n\n return this.state;\n }\n\n get current(): LevelFrameState {\n return this.state;\n }\n}\n","import type {\n GameFrameResult,\n GameSimulation,\n FixedStepContext,\n} from '@quake2ts/engine';\nimport type { Vec3 } from '@quake2ts/shared';\nimport { EntitySystem } from './entities/index.js';\nimport { GameFrameLoop } from './loop.js';\nimport { LevelClock, type LevelFrameState } from './level.js';\nexport * from './entities/index.js';\n\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 } as const;\n\nexport interface GameCreateOptions {\n gravity: Vec3;\n}\n\nexport interface GameStateSnapshot {\n readonly gravity: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly level: LevelFrameState;\n readonly entities: {\n readonly activeCount: number;\n readonly worldClassname: string;\n };\n}\n\nexport interface GameExports extends GameSimulation<GameStateSnapshot> {\n spawnWorld(): void;\n readonly entities: EntitySystem;\n}\n\nexport function createGame(\n engine: { trace(start: Vec3, end: Vec3): unknown },\n options: GameCreateOptions,\n): GameExports {\n const gravity = options.gravity;\n const levelClock = new LevelClock();\n const frameLoop = new GameFrameLoop();\n const entities = new EntitySystem();\n frameLoop.addStage('prep', (context) => {\n levelClock.tick(context);\n entities.beginFrame(levelClock.current.timeSeconds);\n });\n frameLoop.addStage('simulate', ({ deltaSeconds }) => {\n velocity = {\n x: velocity.x + gravity.x * deltaSeconds,\n y: velocity.y + gravity.y * deltaSeconds,\n z: velocity.z + gravity.z * deltaSeconds,\n };\n\n origin = {\n x: origin.x + velocity.x * deltaSeconds,\n y: origin.y + velocity.y * deltaSeconds,\n z: origin.z + velocity.z * deltaSeconds,\n };\n\n entities.runFrame();\n });\n\n let origin: Vec3 = { ...ZERO_VEC3 };\n let velocity: Vec3 = { ...ZERO_VEC3 };\n\n const snapshot = (frame: number): GameFrameResult<GameStateSnapshot> => ({\n frame,\n timeMs: frameLoop.time,\n state: {\n gravity: { ...gravity },\n origin: { ...origin },\n velocity: { ...velocity },\n level: { ...levelClock.current },\n entities: {\n activeCount: entities.activeCount,\n worldClassname: entities.world.classname,\n },\n },\n });\n\n const resetState = (startTimeMs: number) => {\n frameLoop.reset(startTimeMs);\n levelClock.start(startTimeMs);\n origin = { ...ZERO_VEC3 };\n velocity = { ...ZERO_VEC3 };\n entities.beginFrame(startTimeMs / 1000);\n entities.runFrame();\n };\n\n return {\n init(startTimeMs: number) {\n resetState(startTimeMs);\n void engine.trace({ x: 0, y: 0, z: 0 }, gravity);\n return snapshot(0);\n },\n shutdown() {\n /* placeholder shutdown */\n },\n spawnWorld() {\n /* placeholder world spawn */\n },\n frame(step: FixedStepContext) {\n const context = frameLoop.advance(step);\n return snapshot(context.frame);\n },\n entities,\n };\n}\n","export interface Vec3 {\n readonly x: number;\n readonly y: number;\n readonly z: number;\n readonly [index: number]: number;\n}\n\nexport const ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\n\n// Matches STOP_EPSILON from rerelease q_vec3.h\nexport const STOP_EPSILON = 0.1;\n\nconst DEG_TO_RAD = Math.PI / 180;\n\nexport interface Bounds3 {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n}\n\nexport type Mat3Row = readonly [number, number, number];\nexport type Mat3 = readonly [Mat3Row, Mat3Row, Mat3Row];\n\nexport function addVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x + b.x, y: a.y + b.y, z: a.z + b.z };\n}\n\nexport function subtractVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };\n}\n\nexport function multiplyVec3(a: Vec3, b: Vec3): Vec3 {\n return { x: a.x * b.x, y: a.y * b.y, z: a.z * b.z };\n}\n\nexport function scaleVec3(a: Vec3, scalar: number): Vec3 {\n return { x: a.x * scalar, y: a.y * scalar, z: a.z * scalar };\n}\n\nexport function negateVec3(a: Vec3): Vec3 {\n return scaleVec3(a, -1);\n}\n\nexport function dotVec3(a: Vec3, b: Vec3): number {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n}\n\nexport function crossVec3(a: Vec3, b: Vec3): Vec3 {\n return {\n x: a.y * b.z - a.z * b.y,\n y: a.z * b.x - a.x * b.z,\n z: a.x * b.y - a.y * b.x,\n };\n}\n\nexport function lengthSquaredVec3(a: Vec3): number {\n return dotVec3(a, a);\n}\n\nexport function lengthVec3(a: Vec3): number {\n return Math.sqrt(lengthSquaredVec3(a));\n}\n\n/**\n * Returns the normalized vector. If the vector is zero-length, the\n * input is returned to mirror the rerelease q_vec3 semantics.\n */\nexport function normalizeVec3(a: Vec3): Vec3 {\n const len = lengthVec3(a);\n return len === 0 ? a : scaleVec3(a, 1 / len);\n}\n\n/**\n * Projects a point onto a plane defined by the given normal.\n * Based on ProjectPointOnPlane in the rerelease q_vec3 helpers.\n */\nexport function projectPointOnPlane(point: Vec3, normal: Vec3): Vec3 {\n const invDenom = 1 / dotVec3(normal, normal);\n const d = dotVec3(normal, point) * invDenom;\n return subtractVec3(point, scaleVec3(normal, invDenom * d));\n}\n\n/**\n * Computes a perpendicular vector to the provided direction using the\n * smallest axial component heuristic used by the rerelease.\n * Assumes the input is normalized.\n */\nexport function perpendicularVec3(src: Vec3): Vec3 {\n let pos = 0;\n let minElement = Math.abs(src.x);\n\n if (Math.abs(src.y) < minElement) {\n pos = 1;\n minElement = Math.abs(src.y);\n }\n\n if (Math.abs(src.z) < minElement) {\n pos = 2;\n }\n\n const axis = pos === 0 ? { x: 1, y: 0, z: 0 } : pos === 1 ? { x: 0, y: 1, z: 0 } : { x: 0, y: 0, z: 1 };\n return normalizeVec3(projectPointOnPlane(axis, src));\n}\n\nexport function closestPointToBox(point: Vec3, mins: Vec3, maxs: Vec3): Vec3 {\n return {\n x: point.x < mins.x ? mins.x : point.x > maxs.x ? maxs.x : point.x,\n y: point.y < mins.y ? mins.y : point.y > maxs.y ? maxs.y : point.y,\n z: point.z < mins.z ? mins.z : point.z > maxs.z ? maxs.z : point.z,\n };\n}\n\nexport function distanceBetweenBoxesSquared(aMins: Vec3, aMaxs: Vec3, bMins: Vec3, bMaxs: Vec3): number {\n let lengthSq = 0;\n\n if (aMaxs.x < bMins.x) {\n const d = aMaxs.x - bMins.x;\n lengthSq += d * d;\n } else if (aMins.x > bMaxs.x) {\n const d = aMins.x - bMaxs.x;\n lengthSq += d * d;\n }\n\n if (aMaxs.y < bMins.y) {\n const d = aMaxs.y - bMins.y;\n lengthSq += d * d;\n } else if (aMins.y > bMaxs.y) {\n const d = aMins.y - bMaxs.y;\n lengthSq += d * d;\n }\n\n if (aMaxs.z < bMins.z) {\n const d = aMaxs.z - bMins.z;\n lengthSq += d * d;\n } else if (aMins.z > bMaxs.z) {\n const d = aMins.z - bMaxs.z;\n lengthSq += d * d;\n }\n\n return lengthSq;\n}\n\nexport function createEmptyBounds3(): Bounds3 {\n return {\n mins: { x: Number.POSITIVE_INFINITY, y: Number.POSITIVE_INFINITY, z: Number.POSITIVE_INFINITY },\n maxs: { x: Number.NEGATIVE_INFINITY, y: Number.NEGATIVE_INFINITY, z: Number.NEGATIVE_INFINITY },\n };\n}\n\nexport function addPointToBounds(point: Vec3, bounds: Bounds3): Bounds3 {\n return {\n mins: {\n x: Math.min(bounds.mins.x, point.x),\n y: Math.min(bounds.mins.y, point.y),\n z: Math.min(bounds.mins.z, point.z),\n },\n maxs: {\n x: Math.max(bounds.maxs.x, point.x),\n y: Math.max(bounds.maxs.y, point.y),\n z: Math.max(bounds.maxs.z, point.z),\n },\n };\n}\n\nexport function boxesIntersect(a: Bounds3, b: Bounds3): boolean {\n return (\n a.mins.x <= b.maxs.x &&\n a.maxs.x >= b.mins.x &&\n a.mins.y <= b.maxs.y &&\n a.maxs.y >= b.mins.y &&\n a.mins.z <= b.maxs.z &&\n a.maxs.z >= b.mins.z\n );\n}\n\n/**\n * Mirrors PM_ClipVelocity from `rerelease/p_move.cpp`: slide the incoming velocity off\n * a plane normal, applying an overbounce scale and zeroing tiny components so callers can\n * detect blocked axes using STOP_EPSILON.\n */\nexport function clipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n const backoff = dotVec3(inVel, normal) * overbounce;\n\n let outX = inVel.x - normal.x * backoff;\n let outY = inVel.y - normal.y * backoff;\n let outZ = inVel.z - normal.z * backoff;\n\n if (outX > -STOP_EPSILON && outX < STOP_EPSILON) {\n outX = 0;\n }\n\n if (outY > -STOP_EPSILON && outY < STOP_EPSILON) {\n outY = 0;\n }\n\n if (outZ > -STOP_EPSILON && outZ < STOP_EPSILON) {\n outZ = 0;\n }\n\n return { x: outX, y: outY, z: outZ };\n}\n\n/**\n * Slide a velocity across one or more clip planes using the same plane set resolution logic\n * seen in the inner loop of `PM_StepSlideMove_Generic` (rerelease `p_move.cpp`). When a single\n * plane is provided this devolves to PM_ClipVelocity; with two planes it projects onto the\n * crease defined by their cross product; with more planes it zeroes the velocity to avoid\n * oscillations.\n */\nexport function clipVelocityAgainstPlanes(\n velocity: Vec3,\n planes: readonly Vec3[],\n overbounce: number,\n primalVelocity?: Vec3,\n): Vec3 {\n if (planes.length === 0) {\n return velocity;\n }\n\n let working = velocity;\n\n for (let i = 0; i < planes.length; i++) {\n working = clipVelocityVec3(working, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) {\n continue;\n }\n\n if (dotVec3(working, planes[j]) < 0) {\n break;\n }\n }\n\n if (j === planes.length) {\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return working;\n }\n }\n\n if (planes.length === 2) {\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n const creaseVelocity = scaleVec3(dir, d);\n\n if (primalVelocity && dotVec3(creaseVelocity, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return creaseVelocity;\n }\n\n if (primalVelocity && dotVec3(working, primalVelocity) <= 0) {\n return ZERO_VEC3;\n }\n\n return ZERO_VEC3;\n}\n\n/**\n * Alias retained for ergonomics; mirrors PM_ClipVelocity semantics.\n */\nexport function slideClipVelocityVec3(inVel: Vec3, normal: Vec3, overbounce: number): Vec3 {\n return clipVelocityVec3(inVel, normal, overbounce);\n}\n\n/**\n * Project an offset from a point in forward/right(/up) space into world space.\n * Mirrors G_ProjectSource and G_ProjectSource2 in rerelease q_vec3.\n */\nexport function projectSourceVec3(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y,\n y: point.y + forward.y * distance.x + right.y * distance.y,\n z: point.z + forward.z * distance.x + right.z * distance.y + distance.z,\n };\n}\n\nexport function projectSourceVec3WithUp(point: Vec3, distance: Vec3, forward: Vec3, right: Vec3, up: Vec3): Vec3 {\n return {\n x: point.x + forward.x * distance.x + right.x * distance.y + up.x * distance.z,\n y: point.y + forward.y * distance.x + right.y * distance.y + up.y * distance.z,\n z: point.z + forward.z * distance.x + right.z * distance.y + up.z * distance.z,\n };\n}\n\n/**\n * Spherical linear interpolation between two vectors, mirroring q_vec3::slerp.\n * This is intended for direction vectors; callers should pre-normalize if needed.\n */\nexport function slerpVec3(from: Vec3, to: Vec3, t: number): Vec3 {\n const dot = dotVec3(from, to);\n let aFactor: number;\n let bFactor: number;\n\n if (Math.abs(dot) > 0.9995) {\n aFactor = 1 - t;\n bFactor = t;\n } else {\n const ang = Math.acos(dot);\n const sinOmega = Math.sin(ang);\n const sinAOmega = Math.sin((1 - t) * ang);\n const sinBOmega = Math.sin(t * ang);\n aFactor = sinAOmega / sinOmega;\n bFactor = sinBOmega / sinOmega;\n }\n\n return {\n x: from.x * aFactor + to.x * bFactor,\n y: from.y * aFactor + to.y * bFactor,\n z: from.z * aFactor + to.z * bFactor,\n };\n}\n\nexport function concatRotationMatrices(a: Mat3, b: Mat3): Mat3 {\n const row = (rowIndex: number): Mat3Row => [\n a[rowIndex][0] * b[0][0] + a[rowIndex][1] * b[1][0] + a[rowIndex][2] * b[2][0],\n a[rowIndex][0] * b[0][1] + a[rowIndex][1] * b[1][1] + a[rowIndex][2] * b[2][1],\n a[rowIndex][0] * b[0][2] + a[rowIndex][1] * b[1][2] + a[rowIndex][2] * b[2][2],\n ];\n\n const result = [row(0), row(1), row(2)] as Mat3;\n return result;\n}\n\nexport function rotatePointAroundVector(dir: Vec3, point: Vec3, degrees: number): Vec3 {\n const axisLength = lengthVec3(dir);\n if (axisLength === 0) {\n return point;\n }\n\n const vf = normalizeVec3(dir);\n const vr = perpendicularVec3(vf);\n const vup = crossVec3(vr, vf);\n\n const m: Mat3 = [\n [vr.x, vup.x, vf.x],\n [vr.y, vup.y, vf.y],\n [vr.z, vup.z, vf.z],\n ];\n\n const im: Mat3 = [\n [m[0][0], m[1][0], m[2][0]],\n [m[0][1], m[1][1], m[2][1]],\n [m[0][2], m[1][2], m[2][2]],\n ];\n\n const radians = degrees * DEG_TO_RAD;\n const cos = Math.cos(radians);\n const sin = Math.sin(radians);\n const zrot: Mat3 = [\n [cos, sin, 0],\n [-sin, cos, 0],\n [0, 0, 1],\n ];\n\n const rot = concatRotationMatrices(concatRotationMatrices(m, zrot), im);\n\n return {\n x: rot[0][0] * point.x + rot[0][1] * point.y + rot[0][2] * point.z,\n y: rot[1][0] * point.x + rot[1][1] * point.y + rot[1][2] * point.z,\n z: rot[2][0] * point.x + rot[2][1] * point.y + rot[2][2] * point.z,\n };\n}\n","import { Vec3 } from './vec3.js';\n\nexport const PITCH = 0;\nexport const YAW = 1;\nexport const ROLL = 2;\n\nconst DEG2RAD_FACTOR = Math.PI / 180;\nconst RAD2DEG_FACTOR = 180 / Math.PI;\n\nfunction axisComponent(vec: Vec3, axis: number): number {\n switch (axis) {\n case PITCH:\n return vec.x;\n case YAW:\n return vec.y;\n case ROLL:\n default:\n return vec.z;\n }\n}\n\nexport interface AngleVectorsResult {\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly up: Vec3;\n}\n\nexport function degToRad(degrees: number): number {\n return degrees * DEG2RAD_FACTOR;\n}\n\nexport function radToDeg(radians: number): number {\n return radians * RAD2DEG_FACTOR;\n}\n\nexport function lerpAngle(from: number, to: number, frac: number): number {\n let target = to;\n\n if (target - from > 180) {\n target -= 360;\n } else if (target - from < -180) {\n target += 360;\n }\n\n return from + frac * (target - from);\n}\n\nexport function angleMod(angle: number): number {\n const value = angle % 360;\n return value < 0 ? 360 + value : value;\n}\n\nexport function angleVectors(angles: Vec3): AngleVectorsResult {\n const yaw = degToRad(axisComponent(angles, YAW));\n const pitch = degToRad(axisComponent(angles, PITCH));\n const roll = degToRad(axisComponent(angles, ROLL));\n\n const sy = Math.sin(yaw);\n const cy = Math.cos(yaw);\n const sp = Math.sin(pitch);\n const cp = Math.cos(pitch);\n const sr = Math.sin(roll);\n const cr = Math.cos(roll);\n\n const forward: Vec3 = {\n x: cp * cy,\n y: cp * sy,\n z: -sp,\n };\n\n const right: Vec3 = {\n x: -sr * sp * cy - cr * -sy,\n y: -sr * sp * sy - cr * cy,\n z: -sr * cp,\n };\n\n const up: Vec3 = {\n x: cr * sp * cy - sr * -sy,\n y: cr * sp * sy - sr * cy,\n z: cr * cp,\n };\n\n return { forward, right, up };\n}\n\nexport function vectorToYaw(vec: Vec3): number {\n const pitch = axisComponent(vec, PITCH);\n const yawAxis = axisComponent(vec, YAW);\n\n if (pitch === 0) {\n if (yawAxis === 0) {\n return 0;\n }\n\n return yawAxis > 0 ? 90 : 270;\n }\n\n const yaw = radToDeg(Math.atan2(yawAxis, pitch));\n return yaw < 0 ? yaw + 360 : yaw;\n}\n\nexport function vectorToAngles(vec: Vec3): Vec3 {\n const x = vec.x;\n const y = vec.y;\n const z = vec.z;\n\n if (y === 0 && x === 0) {\n return { x: z > 0 ? -90 : -270, y: 0, z: 0 };\n }\n\n let yaw: number;\n if (x) {\n yaw = radToDeg(Math.atan2(y, x));\n } else if (y > 0) {\n yaw = 90;\n } else {\n yaw = 270;\n }\n\n if (yaw < 0) {\n yaw += 360;\n }\n\n const forward = Math.sqrt(x * x + y * y);\n let pitch = radToDeg(Math.atan2(z, forward));\n if (pitch < 0) {\n pitch += 360;\n }\n\n return { x: -pitch, y: yaw, z: 0 };\n}\n","export type Color4 = [number, number, number, number];\n\n/**\n * TypeScript port of G_AddBlend from rerelease q_std.h.\n *\n * Given an incoming RGBA color and an existing blend color, computes the new\n * blended color where alpha is accumulated and RGB is mixed proportionally\n * to the previous vs. new alpha contribution.\n *\n * This function is pure and does not mutate its inputs.\n */\nexport function addBlendColor(\n r: number,\n g: number,\n b: number,\n a: number,\n current: Color4,\n): Color4 {\n if (a <= 0) {\n return current;\n }\n\n const oldR = current[0];\n const oldG = current[1];\n const oldB = current[2];\n const oldA = current[3];\n\n const a2 = oldA + (1 - oldA) * a;\n\n if (a2 <= 0) {\n return [0, 0, 0, 0];\n }\n\n const a3 = oldA / a2;\n\n const newR = oldR * a3 + r * (1 - a3);\n const newG = oldG * a3 + g * (1 - a3);\n const newB = oldB * a3 + b * (1 - a3);\n\n return [newR, newG, newB, a2];\n}\n\n","const STATE_SIZE = 624;\nconst MIDDLE_WORD = 397;\nconst MATRIX_A = 0x9908b0df;\nconst UPPER_MASK = 0x80000000;\nconst LOWER_MASK = 0x7fffffff;\nconst TWO_POW_32 = 0x100000000;\n\n/**\n * Minimal MT19937 implementation mirroring the rerelease's std::mt19937 usage in g_local.h.\n * The generator outputs deterministic unsigned 32-bit integers which drive the\n * higher-level helpers such as frandom/crandom/irandom.\n */\nexport class MersenneTwister19937 {\n private state = new Uint32Array(STATE_SIZE);\n private index = STATE_SIZE;\n\n constructor(seed = 5489) {\n this.seed(seed);\n }\n\n seed(seed: number): void {\n this.state[0] = seed >>> 0;\n for (let i = 1; i < STATE_SIZE; i++) {\n const prev = this.state[i - 1] ^ (this.state[i - 1] >>> 30);\n const next = Math.imul(prev >>> 0, 1812433253) + i;\n this.state[i] = next >>> 0;\n }\n this.index = STATE_SIZE;\n }\n\n nextUint32(): number {\n if (this.index >= STATE_SIZE) {\n this.twist();\n }\n\n let y = this.state[this.index++];\n y ^= y >>> 11;\n y ^= (y << 7) & 0x9d2c5680;\n y ^= (y << 15) & 0xefc60000;\n y ^= y >>> 18;\n return y >>> 0;\n }\n\n private twist(): void {\n for (let i = 0; i < STATE_SIZE; i++) {\n const y = (this.state[i] & UPPER_MASK) | (this.state[(i + 1) % STATE_SIZE] & LOWER_MASK);\n let next = this.state[(i + MIDDLE_WORD) % STATE_SIZE] ^ (y >>> 1);\n if ((y & 1) !== 0) {\n next ^= MATRIX_A;\n }\n this.state[i] = next >>> 0;\n }\n this.index = 0;\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\n/**\n * Deterministic helper mirroring the random helpers defined in rerelease g_local.h.\n */\nexport class RandomGenerator {\n private readonly mt: MersenneTwister19937;\n\n constructor(options: RandomGeneratorOptions = {}) {\n this.mt = new MersenneTwister19937(options.seed);\n }\n\n /** Uniform float in [0, 1). */\n frandom(): number {\n return this.mt.nextUint32() / TWO_POW_32;\n }\n\n /** Uniform float in [min, max). */\n frandomRange(minInclusive: number, maxExclusive: number): number {\n return minInclusive + (maxExclusive - minInclusive) * this.frandom();\n }\n\n /** Uniform float in [0, max). */\n frandomMax(maxExclusive: number): number {\n return this.frandomRange(0, maxExclusive);\n }\n\n /** Uniform float in [-1, 1). */\n crandom(): number {\n return this.frandomRange(-1, 1);\n }\n\n /** Uniform float in (-1, 1). */\n crandomOpen(): number {\n const epsilon = Number.EPSILON;\n return this.frandomRange(-1 + epsilon, 1);\n }\n\n /** Raw uint32 sample. */\n irandomUint32(): number {\n return this.mt.nextUint32();\n }\n\n /** Uniform integer in [min, max). */\n irandomRange(minInclusive: number, maxExclusive: number): number {\n if (maxExclusive - minInclusive <= 1) {\n return minInclusive;\n }\n\n const span = maxExclusive - minInclusive;\n const limit = TWO_POW_32 - (TWO_POW_32 % span);\n let sample: number;\n do {\n sample = this.mt.nextUint32();\n } while (sample >= limit);\n return minInclusive + (sample % span);\n }\n\n /** Uniform integer in [0, max). */\n irandom(maxExclusive: number): number {\n if (maxExclusive <= 0) {\n return 0;\n }\n return this.irandomRange(0, maxExclusive);\n }\n\n /** Uniform time in milliseconds [min, max). */\n randomTimeRange(minMs: number, maxMs: number): number {\n if (maxMs <= minMs) {\n return minMs;\n }\n return this.irandomRange(minMs, maxMs);\n }\n\n /** Uniform time in milliseconds [0, max). */\n randomTime(maxMs: number): number {\n return this.irandom(maxMs);\n }\n\n randomIndex<T extends { length: number }>(container: T): number {\n return this.irandom(container.length);\n }\n}\n\nexport function createRandomGenerator(options?: RandomGeneratorOptions): RandomGenerator {\n return new RandomGenerator(options);\n}\n","/**\n * Bitflag constants mirroring the Quake II rerelease `contents_t` and\n * `surfflags_t` enumerations from `game.h`. The helpers here operate purely on\n * numeric bitmasks so both the authoritative game simulation and the client can\n * share the same semantic checks.\n */\nexport type ContentsFlag = number;\nexport type SurfaceFlag = number;\n\nexport const CONTENTS_NONE: ContentsFlag = 0;\nexport const CONTENTS_SOLID: ContentsFlag = 1 << 0;\nexport const CONTENTS_WINDOW: ContentsFlag = 1 << 1;\nexport const CONTENTS_AUX: ContentsFlag = 1 << 2;\nexport const CONTENTS_LAVA: ContentsFlag = 1 << 3;\nexport const CONTENTS_SLIME: ContentsFlag = 1 << 4;\nexport const CONTENTS_WATER: ContentsFlag = 1 << 5;\nexport const CONTENTS_MIST: ContentsFlag = 1 << 6;\nexport const CONTENTS_NO_WATERJUMP: ContentsFlag = 1 << 13;\nexport const CONTENTS_PROJECTILECLIP: ContentsFlag = 1 << 14;\nexport const CONTENTS_AREAPORTAL: ContentsFlag = 1 << 15;\nexport const CONTENTS_PLAYERCLIP: ContentsFlag = 1 << 16;\nexport const CONTENTS_MONSTERCLIP: ContentsFlag = 1 << 17;\nexport const CONTENTS_CURRENT_0: ContentsFlag = 1 << 18;\nexport const CONTENTS_CURRENT_90: ContentsFlag = 1 << 19;\nexport const CONTENTS_CURRENT_180: ContentsFlag = 1 << 20;\nexport const CONTENTS_CURRENT_270: ContentsFlag = 1 << 21;\nexport const CONTENTS_CURRENT_UP: ContentsFlag = 1 << 22;\nexport const CONTENTS_CURRENT_DOWN: ContentsFlag = 1 << 23;\nexport const CONTENTS_ORIGIN: ContentsFlag = 1 << 24;\nexport const CONTENTS_MONSTER: ContentsFlag = 1 << 25;\nexport const CONTENTS_DEADMONSTER: ContentsFlag = 1 << 26;\nexport const CONTENTS_DETAIL: ContentsFlag = 1 << 27;\nexport const CONTENTS_TRANSLUCENT: ContentsFlag = 1 << 28;\nexport const CONTENTS_LADDER: ContentsFlag = 1 << 29;\nexport const CONTENTS_PLAYER: ContentsFlag = 1 << 30;\nexport const CONTENTS_PROJECTILE: ContentsFlag = 1 << 31;\n\nexport const LAST_VISIBLE_CONTENTS: ContentsFlag = CONTENTS_MIST;\n\nexport const SURF_NONE: SurfaceFlag = 0;\nexport const SURF_LIGHT: SurfaceFlag = 1 << 0;\nexport const SURF_SLICK: SurfaceFlag = 1 << 1;\nexport const SURF_SKY: SurfaceFlag = 1 << 2;\nexport const SURF_WARP: SurfaceFlag = 1 << 3;\nexport const SURF_TRANS33: SurfaceFlag = 1 << 4;\nexport const SURF_TRANS66: SurfaceFlag = 1 << 5;\nexport const SURF_FLOWING: SurfaceFlag = 1 << 6;\nexport const SURF_NODRAW: SurfaceFlag = 1 << 7;\nexport const SURF_ALPHATEST: SurfaceFlag = 1 << 25;\nexport const SURF_N64_UV: SurfaceFlag = 1 << 28;\nexport const SURF_N64_SCROLL_X: SurfaceFlag = 1 << 29;\nexport const SURF_N64_SCROLL_Y: SurfaceFlag = 1 << 30;\nexport const SURF_N64_SCROLL_FLIP: SurfaceFlag = 1 << 31;\n\nexport const MASK_ALL: ContentsFlag = 0xffffffff;\nexport const MASK_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_PLAYERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_DEADSOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_MONSTERSOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_WATER: ContentsFlag = CONTENTS_WATER | CONTENTS_LAVA | CONTENTS_SLIME;\nexport const MASK_OPAQUE: ContentsFlag = CONTENTS_SOLID | CONTENTS_SLIME | CONTENTS_LAVA;\nexport const MASK_SHOT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_PLAYER | CONTENTS_WINDOW | CONTENTS_DEADMONSTER;\nexport const MASK_CURRENT: ContentsFlag =\n CONTENTS_CURRENT_0 |\n CONTENTS_CURRENT_90 |\n CONTENTS_CURRENT_180 |\n CONTENTS_CURRENT_270 |\n CONTENTS_CURRENT_UP |\n CONTENTS_CURRENT_DOWN;\nexport const MASK_BLOCK_SIGHT: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_MONSTER | CONTENTS_PLAYER;\nexport const MASK_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW;\nexport const MASK_LADDER_NAV_SOLID: ContentsFlag = CONTENTS_SOLID | CONTENTS_WINDOW;\nexport const MASK_WALK_NAV_SOLID: ContentsFlag =\n CONTENTS_SOLID | CONTENTS_PLAYERCLIP | CONTENTS_WINDOW | CONTENTS_MONSTERCLIP;\nexport const MASK_PROJECTILE: ContentsFlag = MASK_SHOT | CONTENTS_PROJECTILECLIP;\n\nexport function hasAllContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) === flags;\n}\n\nexport function hasAnyContents(mask: ContentsFlag, flags: ContentsFlag): boolean {\n return (mask & flags) !== 0;\n}\n\nexport function addContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask | flags;\n}\n\nexport function removeContents(mask: ContentsFlag, flags: ContentsFlag): ContentsFlag {\n return mask & ~flags;\n}\n\nexport function hasSurfaceFlags(surface: SurfaceFlag, flags: SurfaceFlag): boolean {\n return (surface & flags) === flags;\n}\n\nexport function combineSurfaceFlags(...flags: SurfaceFlag[]): SurfaceFlag {\n let mask = SURF_NONE;\n for (const flag of flags) {\n mask |= flag;\n }\n return mask;\n}\n","import type { Vec3 } from '../math/vec3.js';\n\nexport interface CollisionPlane {\n normal: Vec3;\n dist: number;\n type: number;\n signbits: number;\n}\n\nexport interface CollisionBrushSide {\n plane: CollisionPlane;\n surfaceFlags: number;\n}\n\nexport interface CollisionBrush {\n contents: number;\n sides: CollisionBrushSide[];\n checkcount?: number;\n}\n\nexport interface CollisionLeaf {\n contents: number;\n cluster: number;\n area: number;\n firstLeafBrush: number;\n numLeafBrushes: number;\n}\n\nexport interface CollisionNode {\n plane: CollisionPlane;\n children: [number, number];\n}\n\nexport interface CollisionBmodel {\n mins: Vec3;\n maxs: Vec3;\n origin: Vec3;\n headnode: number;\n}\n\nexport interface CollisionModel {\n planes: CollisionPlane[];\n nodes: CollisionNode[];\n leaves: CollisionLeaf[];\n brushes: CollisionBrush[];\n leafBrushes: number[];\n bmodels: CollisionBmodel[];\n}\n\nexport interface CollisionLumpData {\n planes: Array<{ normal: Vec3; dist: number; type: number }>;\n nodes: Array<{ planenum: number; children: [number, number] }>;\n leaves: Array<{ contents: number; cluster: number; area: number; firstLeafBrush: number; numLeafBrushes: number }>;\n brushes: Array<{ firstSide: number; numSides: number; contents: number }>;\n brushSides: Array<{ planenum: number; surfaceFlags: number }>;\n leafBrushes: number[];\n bmodels: Array<{ mins: Vec3; maxs: Vec3; origin: Vec3; headnode: number }>;\n}\n\nexport interface TraceResult {\n fraction: number;\n plane: CollisionPlane | null;\n contents: number;\n surfaceFlags: number;\n startsolid: boolean;\n allsolid: boolean;\n}\n\nexport enum PlaneSide {\n FRONT = 1,\n BACK = 2,\n CROSS = 3,\n}\n\nexport const DIST_EPSILON = 0.03125;\n\nexport function buildCollisionModel(lumps: CollisionLumpData): CollisionModel {\n const planes: CollisionPlane[] = lumps.planes.map((plane) => ({\n ...plane,\n signbits: computePlaneSignBits(plane.normal),\n }));\n\n const nodes: CollisionNode[] = lumps.nodes.map((node) => ({\n plane: planes[node.planenum],\n children: node.children,\n }));\n\n const brushes: CollisionBrush[] = lumps.brushes.map((brush) => {\n const sides = lumps.brushSides.slice(brush.firstSide, brush.firstSide + brush.numSides).map((side) => ({\n plane: planes[side.planenum],\n surfaceFlags: side.surfaceFlags,\n }));\n\n return {\n contents: brush.contents,\n sides,\n checkcount: 0,\n };\n });\n\n const leaves: CollisionLeaf[] = lumps.leaves.map((leaf) => ({\n contents: leaf.contents,\n cluster: leaf.cluster,\n area: leaf.area,\n firstLeafBrush: leaf.firstLeafBrush,\n numLeafBrushes: leaf.numLeafBrushes,\n }));\n\n const bmodels: CollisionBmodel[] = lumps.bmodels.map((model) => ({\n mins: model.mins,\n maxs: model.maxs,\n origin: model.origin,\n headnode: model.headnode,\n }));\n\n return {\n planes,\n nodes,\n leaves,\n brushes,\n leafBrushes: lumps.leafBrushes,\n bmodels,\n };\n}\n\nexport function computePlaneSignBits(normal: Vec3): number {\n let bits = 0;\n if (normal.x < 0) bits |= 1;\n if (normal.y < 0) bits |= 2;\n if (normal.z < 0) bits |= 4;\n return bits;\n}\n\nexport function planeDistanceToPoint(plane: CollisionPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z - plane.dist;\n}\n\nexport function pointOnPlaneSide(plane: CollisionPlane, point: Vec3, epsilon = 0): PlaneSide.FRONT | PlaneSide.BACK | PlaneSide.CROSS {\n const dist = planeDistanceToPoint(plane, point);\n if (dist > epsilon) {\n return PlaneSide.FRONT;\n }\n if (dist < -epsilon) {\n return PlaneSide.BACK;\n }\n return PlaneSide.CROSS;\n}\n\nexport function boxOnPlaneSide(mins: Vec3, maxs: Vec3, plane: CollisionPlane, epsilon = 0): PlaneSide {\n let dist1: number;\n let dist2: number;\n\n switch (plane.signbits) {\n case 0:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 1:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n break;\n case 2:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 3:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n break;\n case 4:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 5:\n dist1 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * maxs.z;\n break;\n case 6:\n dist1 = plane.normal.x * maxs.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * mins.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n default:\n dist1 = plane.normal.x * mins.x + plane.normal.y * mins.y + plane.normal.z * mins.z;\n dist2 = plane.normal.x * maxs.x + plane.normal.y * maxs.y + plane.normal.z * maxs.z;\n break;\n }\n\n let sides = 0;\n if (dist1 - plane.dist >= -epsilon) sides = PlaneSide.FRONT;\n if (dist2 - plane.dist <= epsilon) sides |= PlaneSide.BACK;\n return sides as PlaneSide;\n}\n\nexport function pointInsideBrush(point: Vec3, brush: CollisionBrush, epsilon = DIST_EPSILON): boolean {\n for (const side of brush.sides) {\n const dist = planeDistanceToPoint(side.plane, point);\n if (dist > epsilon) {\n return false;\n }\n }\n return true;\n}\n\nexport interface BoxBrushTestResult {\n startsolid: boolean;\n allsolid: boolean;\n contents: number;\n}\n\nexport function testBoxInBrush(origin: Vec3, mins: Vec3, maxs: Vec3, brush: CollisionBrush): BoxBrushTestResult {\n for (const side of brush.sides) {\n const offset = side.plane.normal.x * (side.plane.normal.x < 0 ? maxs.x : mins.x) +\n side.plane.normal.y * (side.plane.normal.y < 0 ? maxs.y : mins.y) +\n side.plane.normal.z * (side.plane.normal.z < 0 ? maxs.z : mins.z);\n\n const dist = side.plane.dist - offset;\n const d1 = origin.x * side.plane.normal.x + origin.y * side.plane.normal.y + origin.z * side.plane.normal.z - dist;\n\n if (d1 > 0) {\n return { startsolid: false, allsolid: false, contents: 0 };\n }\n }\n\n return { startsolid: true, allsolid: true, contents: brush.contents };\n}\n\nexport interface ClipBoxParams {\n start: Vec3;\n end: Vec3;\n mins: Vec3;\n maxs: Vec3;\n brush: CollisionBrush;\n trace: TraceResult;\n}\n\nexport function clipBoxToBrush({ start, end, mins, maxs, brush, trace }: ClipBoxParams): void {\n if (brush.sides.length === 0) return;\n\n const isPoint = mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n\n let enterfrac = -1;\n let leavefrac = 1;\n let clipplane: CollisionPlane | null = null;\n let leadside: CollisionBrushSide | null = null;\n\n let getout = false;\n let startout = false;\n\n for (const side of brush.sides) {\n const { plane } = side;\n let dist = plane.dist;\n if (!isPoint) {\n const ofsX = plane.normal.x < 0 ? maxs.x : mins.x;\n const ofsY = plane.normal.y < 0 ? maxs.y : mins.y;\n const ofsZ = plane.normal.z < 0 ? maxs.z : mins.z;\n dist -= plane.normal.x * ofsX + plane.normal.y * ofsY + plane.normal.z * ofsZ;\n }\n\n const d1 = start.x * plane.normal.x + start.y * plane.normal.y + start.z * plane.normal.z - dist;\n const d2 = end.x * plane.normal.x + end.y * plane.normal.y + end.z * plane.normal.z - dist;\n\n if (d2 > 0) getout = true;\n if (d1 > 0) startout = true;\n\n if (d1 > 0 && d2 >= d1) {\n return;\n }\n\n if (d1 <= 0 && d2 <= 0) {\n continue;\n }\n\n if (d1 > d2) {\n const f = (d1 - DIST_EPSILON) / (d1 - d2);\n if (f > enterfrac) {\n enterfrac = f;\n clipplane = plane;\n leadside = side;\n }\n } else {\n const f = (d1 + DIST_EPSILON) / (d1 - d2);\n if (f < leavefrac) leavefrac = f;\n }\n }\n\n if (!startout) {\n trace.startsolid = true;\n if (!getout) trace.allsolid = true;\n return;\n }\n\n if (enterfrac < leavefrac && enterfrac > -1 && enterfrac < trace.fraction) {\n trace.fraction = enterfrac < 0 ? 0 : enterfrac;\n trace.plane = clipplane;\n trace.contents = brush.contents;\n trace.surfaceFlags = leadside?.surfaceFlags ?? 0;\n }\n}\n\nexport function createDefaultTrace(): TraceResult {\n return {\n fraction: 1,\n plane: null,\n contents: 0,\n surfaceFlags: 0,\n startsolid: false,\n allsolid: false,\n };\n}\n","export const enum CvarFlags {\n None = 0,\n Archive = 1 << 0,\n UserInfo = 1 << 1,\n ServerInfo = 1 << 2,\n Latch = 1 << 3,\n Cheat = 1 << 4,\n}\n\nexport interface CvarDefinition {\n readonly name: string;\n readonly defaultValue: string;\n readonly description?: string;\n readonly flags?: CvarFlags;\n}\n","// Mirrors the Quake II rerelease configstring/index layout from `game.h`.\n// These constants intentionally track the numeric values used in the C++\n// game and client modules so the TypeScript engine/game/client layers can\n// share deterministic indices for precaches and HUD parsing.\n\nexport const MAX_STRING_CHARS = 1024;\nexport const MAX_STRING_TOKENS = 80;\nexport const MAX_TOKEN_CHARS = 512;\n\nexport const MAX_QPATH = 64;\nexport const MAX_OSPATH = 128;\n\nexport const MAX_CLIENTS = 256;\nexport const MAX_EDICTS = 8192;\nexport const MAX_LIGHTSTYLES = 256;\nexport const MAX_MODELS = 8192;\nexport const MAX_SOUNDS = 2048;\nexport const MAX_IMAGES = 512;\nexport const MAX_ITEMS = 256;\nexport const MAX_GENERAL = MAX_CLIENTS * 2;\nexport const MAX_SHADOW_LIGHTS = 256;\nexport const MAX_WHEEL_ITEMS = 32;\n\nexport const CS_MAX_STRING_LENGTH = 96;\nexport const CS_MAX_STRING_LENGTH_OLD = 64;\n\n// Enum-style numeric constants that mirror the C++ `configstrings` enum. Only\n// the explicitly numbered entries are re-stated here; everything else follows\n// sequentially to keep the arithmetic (e.g., CS_SOUNDS = CS_MODELS +\n// MAX_MODELS) intact.\nexport enum ConfigStringIndex {\n Name = 0,\n CdTrack = 1,\n Sky = 2,\n SkyAxis = 3,\n SkyRotate = 4,\n StatusBar = 5,\n\n AirAccel = 59,\n MaxClients = 60,\n MapChecksum = 61,\n\n Models = 62,\n Sounds = Models + MAX_MODELS,\n Images = Sounds + MAX_SOUNDS,\n Lights = Images + MAX_IMAGES,\n ShadowLights = Lights + MAX_LIGHTSTYLES,\n Items = ShadowLights + MAX_SHADOW_LIGHTS,\n PlayerSkins = Items + MAX_ITEMS,\n General = PlayerSkins + MAX_CLIENTS,\n WheelWeapons = General + MAX_GENERAL,\n WheelAmmo = WheelWeapons + MAX_WHEEL_ITEMS,\n WheelPowerups = WheelAmmo + MAX_WHEEL_ITEMS,\n CdLoopCount = WheelPowerups + MAX_WHEEL_ITEMS,\n GameStyle = CdLoopCount + 1,\n MaxConfigStrings = GameStyle + 1,\n}\n\n// Mirror the C++ MAX_CONFIGSTRINGS value for consumers that prefer a standalone constant.\nexport const MAX_CONFIGSTRINGS = ConfigStringIndex.MaxConfigStrings;\n\n/**\n * Returns the maximum string length permitted for the given configstring index,\n * mirroring the `CS_SIZE` helper in the rerelease. Statusbar and general ranges\n * can legally occupy multiple 96-character slots; everything else is capped at\n * `CS_MAX_STRING_LENGTH`.\n */\nexport function configStringSize(index: number): number {\n if (index >= ConfigStringIndex.StatusBar && index < ConfigStringIndex.AirAccel) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.AirAccel - index);\n }\n\n if (index >= ConfigStringIndex.General && index < ConfigStringIndex.WheelWeapons) {\n return CS_MAX_STRING_LENGTH * (ConfigStringIndex.MaxConfigStrings - index);\n }\n\n return CS_MAX_STRING_LENGTH;\n}\n","/**\n * Mirrors the Quake II rerelease `water_level_t` enumeration from `game.h`\n * (lines 443-449). These numeric values are relied upon throughout the\n * movement code when checking how submerged a player is, so we keep the same\n * ordering to make future porting work straightforward.\n */\nexport enum WaterLevel {\n None = 0,\n Feet = 1,\n Waist = 2,\n Under = 3,\n}\n\n/**\n * Utility that matches the common rerelease checks that treat any level at or\n * above the `WATER_WAIST` constant as \"significantly submerged\" for friction\n * and current calculations.\n */\nexport function isAtLeastWaistDeep(level: WaterLevel): boolean {\n return level >= WaterLevel.Waist;\n}\n\n/**\n * Returns true when the player is considered underwater (the `WATER_UNDER`\n * case in the rerelease). This mirrors the places in `p_move.cpp` that gate\n * effects such as breath timers and screen warping.\n */\nexport function isUnderwater(level: WaterLevel): boolean {\n return level === WaterLevel.Under;\n}\n\n/**\n * Matches the Quake II rerelease `pmflags_t` bit layout from `game.h` so the\n * shared helpers can manipulate the same flag words as the authoritative game\n * and the client prediction layer.\n */\nexport const enum PmFlag {\n Ducked = 1 << 0,\n JumpHeld = 1 << 1,\n OnGround = 1 << 2,\n TimeWaterJump = 1 << 3,\n TimeLand = 1 << 4,\n TimeTeleport = 1 << 5,\n NoPositionalPrediction = 1 << 6,\n OnLadder = 1 << 7,\n NoAngularPrediction = 1 << 8,\n IgnorePlayerCollision = 1 << 9,\n TimeTrick = 1 << 10,\n}\n\nexport type PmFlags = number;\n\nexport function hasPmFlag(flags: PmFlags, flag: PmFlag): boolean {\n return (flags & flag) !== 0;\n}\n\nexport function addPmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags | flag;\n}\n\nexport function removePmFlag(flags: PmFlags, flag: PmFlag): PmFlags {\n return flags & ~flag;\n}\n\n/**\n * Player movement types mirrored from the rerelease `pmtype_t` enumeration.\n * The exact numeric values matter when syncing pmove state across the network\n * so we keep the same order as the C++ definition.\n */\nexport enum PmType {\n Normal = 0,\n Grapple = 1,\n NoClip = 2,\n Spectator = 3,\n Dead = 4,\n Gib = 5,\n Freeze = 6,\n}\n\n/**\n * Bitmask constants for the `buttons` field on the Quake II player command\n * structure. These mirror the rerelease `BUTTON_*` definitions so logic such as\n * jump/crouch checks can be shared between the server and client.\n */\nexport const enum PlayerButton {\n None = 0,\n Attack = 1 << 0,\n Use = 1 << 1,\n Holster = 1 << 2,\n Jump = 1 << 3,\n Crouch = 1 << 4,\n Any = 1 << 7,\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, dotVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport type {\n PmoveAccelerateParams,\n PmoveCmd,\n PmoveFrictionParams,\n PmoveWishParams,\n PmoveWishResult,\n} from './types.js';\n\n/**\n * Pure version of PM_Friction from rerelease p_move.cpp.\n * Handles ground and water friction and returns a new velocity.\n */\nexport function applyPmoveFriction(params: PmoveFrictionParams): Vec3 {\n const {\n velocity,\n frametime,\n onGround,\n groundIsSlick,\n onLadder,\n waterlevel,\n pmFriction,\n pmStopSpeed,\n pmWaterFriction,\n } = params;\n\n const speed = lengthVec3(velocity);\n\n // Matches the \"if (speed < 1)\" early-out: clears X/Y but preserves Z.\n if (speed < 1) {\n return { x: 0, y: 0, z: velocity.z };\n }\n\n let drop = 0;\n\n // Ground friction (or ladder)\n if ((onGround && !groundIsSlick) || onLadder) {\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const friction = pmFriction;\n drop += control * friction * frametime;\n }\n\n // Water friction (only when not on ladder)\n if (waterlevel > 0 && !onLadder) {\n drop += speed * pmWaterFriction * waterlevel * frametime;\n }\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n const scale = newspeed / speed;\n return scaleVec3(velocity, scale);\n}\n\n/**\n * Pure version of PM_Accelerate from rerelease p_move.cpp.\n * Returns a new velocity with wishdir/wishspeed acceleration applied.\n */\nexport function applyPmoveAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspeed - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * frametime * wishspeed;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Mirrors PM_AirAccelerate in rerelease `p_move.cpp` (lines ~612-636): wishspeed is clamped\n * to 30 for the addspeed calculation but the acceleration magnitude still uses the full wishspeed.\n */\nexport function applyPmoveAirAccelerate(params: PmoveAccelerateParams): Vec3 {\n const { velocity, wishdir, wishspeed, accel, frametime } = params;\n\n const wishspd = Math.min(wishspeed, 30);\n const currentSpeed = dotVec3(velocity, wishdir);\n const addSpeed = wishspd - currentSpeed;\n\n if (addSpeed <= 0) {\n return velocity;\n }\n\n let accelSpeed = accel * wishspeed * frametime;\n if (accelSpeed > addSpeed) {\n accelSpeed = addSpeed;\n }\n\n return {\n x: velocity.x + wishdir.x * accelSpeed,\n y: velocity.y + wishdir.y * accelSpeed,\n z: velocity.z + wishdir.z * accelSpeed,\n };\n}\n\n/**\n * Pure mirror of PM_CmdScale from rerelease `p_move.cpp`. Computes the scalar applied to\n * the command directional inputs so that the resulting wish velocity caps at `maxSpeed`\n * regardless of the directional mix.\n */\nexport function pmoveCmdScale(cmd: PmoveCmd, maxSpeed: number): number {\n const forward = Math.abs(cmd.forwardmove);\n const side = Math.abs(cmd.sidemove);\n const up = Math.abs(cmd.upmove);\n\n const max = Math.max(forward, side, up);\n if (max === 0) {\n return 0;\n }\n\n const total = Math.sqrt(cmd.forwardmove * cmd.forwardmove + cmd.sidemove * cmd.sidemove + cmd.upmove * cmd.upmove);\n return (maxSpeed * max) / (127 * total);\n}\n\n/**\n * Computes wishdir/wishspeed for ground/air movement as done in PM_AirMove and\n * PM_GroundMove. Z is forced to zero and wishspeed is clamped to maxSpeed, matching\n * the rerelease p_move.cpp helpers before they call PM_Accelerate/PM_AirAccelerate.\n */\nexport function buildAirGroundWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n\n/**\n * Computes the wishdir/wishspeed mix for water movement, matching PM_WaterMove in\n * rerelease p_move.cpp: includes the upward bias when no strong upmove is requested,\n * clamps wishspeed to maxSpeed, and halves the returned wishspeed before acceleration.\n */\nexport function buildWaterWish(params: PmoveWishParams): PmoveWishResult {\n const { forward, right, cmd, maxSpeed } = params;\n\n let wishvel = {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n\n if (cmd.upmove > 10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else if (cmd.upmove < -10) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: cmd.upmove });\n } else {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: 10 });\n }\n\n let wishspeed = lengthVec3(wishvel);\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n }\n\n wishspeed *= 0.5;\n\n return {\n wishdir: wishspeed === 0 ? wishvel : normalizeVec3(wishvel),\n wishspeed,\n };\n}\n","import { addVec3, ZERO_VEC3, clipVelocityVec3, crossVec3, dotVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst DEFAULT_MAX_CLIP_PLANES = 5;\nconst DEFAULT_MAX_BUMPS = 4;\nconst DEFAULT_STEP_SIZE = 18;\nconst MIN_STEP_NORMAL = 0.7;\n\nexport const SLIDEMOVE_BLOCKED_FLOOR = 1;\nexport const SLIDEMOVE_BLOCKED_WALL = 2;\n\nexport interface SlideMoveResult {\n readonly velocity: Vec3;\n readonly planes: readonly Vec3[];\n readonly stopped: boolean;\n}\n\nexport interface SlideMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly overbounce: number;\n readonly trace: PmoveTraceFn;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n /**\n * Mirrors the pm->s.pm_time check in PM_StepSlideMove_Generic: if true, the\n * returned velocity is reset to the primal velocity after collision\n * resolution so time-based effects (like knockbacks) don't dampen.\n */\n readonly hasTime?: boolean;\n}\n\nexport interface SlideMoveOutcome extends SlideMoveResult {\n readonly origin: Vec3;\n readonly blocked: number;\n}\n\nexport interface StepSlideMoveParams extends SlideMoveParams {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly stepSize?: number;\n}\n\nexport interface StepSlideMoveOutcome extends SlideMoveOutcome {\n readonly stepped: boolean;\n readonly stepHeight: number;\n readonly stepNormal?: Vec3;\n}\n\n/**\n * Resolves a sequence of collision planes against a primal velocity using the same\n * plane iteration logic seen in PM_StepSlideMove_Generic (rerelease p_move.cpp).\n * The incoming planes should be ordered as they were encountered during traces;\n * the function will accumulate them, clip the velocity to be parallel to all planes,\n * and return zero velocity when three planes form an unresolvable corner or when\n * the adjusted velocity would oppose the primal direction.\n */\nexport function resolveSlideMove(\n initialVelocity: Vec3,\n planesEncountered: readonly Vec3[],\n overbounce: number,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n primalVelocity: Vec3 = initialVelocity,\n): SlideMoveResult {\n if (planesEncountered.length === 0) {\n return { velocity: initialVelocity, planes: [], stopped: false };\n }\n\n const planes: Vec3[] = [];\n let velocity: Vec3 = initialVelocity;\n\n for (const plane of planesEncountered) {\n if (planes.length >= maxClipPlanes) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n // Skip near-duplicate planes to mirror the epsilon guard in PM_StepSlideMove_Generic.\n const duplicate = planes.find((existing) => dotVec3(existing, plane) > 0.99);\n if (duplicate) {\n continue;\n }\n\n planes.push(plane);\n\n let clipped: Vec3 | undefined;\n let i = 0;\n for (; i < planes.length; i++) {\n const candidate = clipVelocityVec3(velocity, planes[i], overbounce);\n\n let j = 0;\n for (; j < planes.length; j++) {\n if (j === i) continue;\n if (dotVec3(candidate, planes[j]) < 0) break;\n }\n\n if (j === planes.length) {\n clipped = candidate;\n break;\n }\n }\n\n if (clipped) {\n velocity = clipped;\n } else {\n if (planes.length !== 2) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n\n const dir = crossVec3(planes[0], planes[1]);\n const d = dotVec3(dir, velocity);\n velocity = scaleVec3(dir, d);\n }\n\n // If velocity reversed relative to the primal direction, stop to avoid oscillations.\n if (dotVec3(velocity, primalVelocity) <= 0) {\n return { velocity: ZERO_VEC3, planes, stopped: true };\n }\n }\n\n const stopped = velocity.x === 0 && velocity.y === 0 && velocity.z === 0;\n return { velocity, planes, stopped };\n}\n\n/**\n * Pure mirror of PM_SlideMoveGeneric from rerelease `p_move.cpp` (minus gravity/step handling).\n * Uses a caller-provided trace to collect collision planes, accumulates them through\n * `resolveSlideMove`, and returns the resulting origin/velocity/blocking state.\n */\nexport function slideMove(params: SlideMoveParams): SlideMoveOutcome {\n const {\n origin: initialOrigin,\n velocity: initialVelocity,\n frametime,\n overbounce,\n trace,\n maxBumps = DEFAULT_MAX_BUMPS,\n maxClipPlanes = DEFAULT_MAX_CLIP_PLANES,\n mins,\n maxs,\n hasTime = false,\n } = params;\n\n let origin = initialOrigin;\n let velocity = initialVelocity;\n const planes: Vec3[] = [];\n const primalVelocity = initialVelocity;\n let timeLeft = frametime;\n let blocked = 0;\n\n for (let bump = 0; bump < maxBumps; bump++) {\n if (velocity.x === 0 && velocity.y === 0 && velocity.z === 0) {\n break;\n }\n\n const end = addVec3(origin, scaleVec3(velocity, timeLeft));\n const tr = trace(origin, end, mins, maxs);\n\n if (tr.allsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.startsolid) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin: tr.endpos, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.fraction > 0) {\n origin = tr.endpos;\n }\n\n if (tr.fraction === 1) {\n break;\n }\n\n if (!tr.planeNormal) {\n const velocity = hasTime ? primalVelocity : ZERO_VEC3;\n return { origin, velocity, planes, stopped: true, blocked };\n }\n\n if (tr.planeNormal.z > 0.7) {\n blocked |= SLIDEMOVE_BLOCKED_FLOOR;\n }\n if (tr.planeNormal.z === 0) {\n blocked |= SLIDEMOVE_BLOCKED_WALL;\n }\n\n planes.push(tr.planeNormal);\n timeLeft -= timeLeft * tr.fraction;\n\n const resolved = resolveSlideMove(velocity, planes, overbounce, maxClipPlanes, primalVelocity);\n velocity = resolved.velocity;\n planes.splice(0, planes.length, ...resolved.planes);\n\n if (primalVelocity.z > 0 && velocity.z < 0) {\n velocity = { ...velocity, z: 0 };\n }\n\n if (resolved.stopped) {\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: true, blocked };\n }\n }\n\n const velocityOut = hasTime ? primalVelocity : velocity;\n return { origin, velocity: velocityOut, planes, stopped: velocityOut.x === 0 && velocityOut.y === 0 && velocityOut.z === 0, blocked };\n}\n\n/**\n * Mirrors PM_StepSlideMove (rerelease p_move.cpp) in a pure form: attempts a\n * regular slide move, then retries from a stepped-up position when the first\n * attempt was blocked. The function compares planar distance traveled and the\n * steepness of the landing plane to decide whether to keep the step.\n */\nexport function stepSlideMove(params: StepSlideMoveParams): StepSlideMoveOutcome {\n const { mins, maxs, stepSize = DEFAULT_STEP_SIZE, ...rest } = params;\n\n const startOrigin = params.origin;\n const startVelocity = params.velocity;\n\n const downResult = slideMove({ ...rest, mins, maxs });\n\n const upTarget = addVec3(startOrigin, { x: 0, y: 0, z: stepSize });\n const upTrace = rest.trace(startOrigin, upTarget, mins, maxs);\n if (upTrace.allsolid) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const actualStep = upTrace.endpos.z - startOrigin.z;\n const steppedResult = slideMove({ ...rest, origin: upTrace.endpos, velocity: startVelocity, mins, maxs });\n\n const pushDownTarget = addVec3(steppedResult.origin, { x: 0, y: 0, z: -actualStep });\n const downTrace = rest.trace(steppedResult.origin, pushDownTarget, mins, maxs);\n\n let steppedOrigin = steppedResult.origin;\n let stepNormal = downTrace.planeNormal;\n\n if (!downTrace.allsolid) {\n steppedOrigin = downTrace.endpos;\n }\n\n const planarDistanceSquared = (a: Vec3, b: Vec3) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2;\n const downDist = planarDistanceSquared(downResult.origin, startOrigin);\n const upDist = planarDistanceSquared(steppedOrigin, startOrigin);\n\n if (downDist > upDist || (stepNormal && stepNormal.z < MIN_STEP_NORMAL)) {\n return { ...downResult, stepped: false, stepHeight: 0 };\n }\n\n const steppedVelocity = { ...steppedResult.velocity, z: downResult.velocity.z };\n const steppedBlocked = steppedResult.blocked;\n const stopped = steppedVelocity.x === 0 && steppedVelocity.y === 0 && steppedVelocity.z === 0;\n\n return {\n origin: steppedOrigin,\n velocity: steppedVelocity,\n planes: steppedResult.planes,\n blocked: steppedBlocked,\n stopped,\n stepped: true,\n stepHeight: actualStep,\n stepNormal,\n };\n}\n","import {\n addVec3,\n lengthSquaredVec3,\n scaleVec3,\n subtractVec3,\n type Vec3,\n} from '../math/vec3.js';\nimport type { PmoveTraceResult } from './types.js';\n\nconst AXES = ['x', 'y', 'z'] as const;\ntype Axis = (typeof AXES)[number];\n\ntype AxisTuple = readonly [number, number, number];\ntype SideBoundCode = -1 | 0 | 1;\n\ninterface SideCheck {\n readonly normal: AxisTuple;\n readonly mins: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n readonly maxs: readonly [SideBoundCode, SideBoundCode, SideBoundCode];\n}\n\nconst SIDE_CHECKS: readonly SideCheck[] = [\n { normal: [0, 0, 1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [0, 0, -1], mins: [-1, -1, 0], maxs: [1, 1, 0] },\n { normal: [1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [-1, 0, 0], mins: [0, -1, -1], maxs: [0, 1, 1] },\n { normal: [0, 1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n { normal: [0, -1, 0], mins: [-1, 0, -1], maxs: [1, 0, 1] },\n];\n\nexport interface FixStuckParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: FixStuckTraceFn;\n}\n\nexport type FixStuckResult = 'good-position' | 'fixed' | 'no-good-position';\n\nexport interface FixStuckOutcome {\n readonly result: FixStuckResult;\n readonly origin: Vec3;\n}\n\nexport type FixStuckTraceFn = (\n start: Vec3,\n mins: Vec3,\n maxs: Vec3,\n end: Vec3,\n) => PmoveTraceResult;\n\ninterface CandidatePosition {\n readonly distance: number;\n readonly origin: Vec3;\n}\n\nconst ZERO_VEC: Vec3 = { x: 0, y: 0, z: 0 };\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction cloneMutable(vec: Vec3): MutableVec3 {\n return { x: vec.x, y: vec.y, z: vec.z };\n}\n\nfunction tupleToVec3(tuple: AxisTuple): Vec3 {\n return { x: tuple[0], y: tuple[1], z: tuple[2] };\n}\n\nfunction adjustAxis(vec: MutableVec3, axis: Axis, delta: number): void {\n if (delta === 0) return;\n switch (axis) {\n case 'x':\n vec.x += delta;\n break;\n case 'y':\n vec.y += delta;\n break;\n case 'z':\n vec.z += delta;\n break;\n }\n}\n\nfunction setAxis(vec: MutableVec3, axis: Axis, value: number): void {\n switch (axis) {\n case 'x':\n vec.x = value;\n break;\n case 'y':\n vec.y = value;\n break;\n case 'z':\n vec.z = value;\n break;\n }\n}\n\nfunction axisValue(vec: Vec3, axis: Axis): number {\n switch (axis) {\n case 'x':\n return vec.x;\n case 'y':\n return vec.y;\n case 'z':\n default:\n return vec.z;\n }\n}\n\nfunction boundValue(code: SideBoundCode, axis: Axis, mins: Vec3, maxs: Vec3): number {\n if (code === -1) {\n return axisValue(mins, axis);\n }\n if (code === 1) {\n return axisValue(maxs, axis);\n }\n return 0;\n}\n\nfunction applySideOffset(base: Vec3, side: SideCheck, mins: Vec3, maxs: Vec3): MutableVec3 {\n const result = cloneMutable(base);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n const normal = side.normal[i];\n if (normal < 0) {\n adjustAxis(result, axis, axisValue(mins, axis));\n } else if (normal > 0) {\n adjustAxis(result, axis, axisValue(maxs, axis));\n }\n }\n return result;\n}\n\nfunction buildSideBounds(side: SideCheck, mins: Vec3, maxs: Vec3): { mins: MutableVec3; maxs: MutableVec3 } {\n const localMins = cloneMutable(ZERO_VEC);\n const localMaxs = cloneMutable(ZERO_VEC);\n for (let i = 0; i < AXES.length; i++) {\n const axis = AXES[i];\n setAxis(localMins, axis, boundValue(side.mins[i], axis, mins, maxs));\n setAxis(localMaxs, axis, boundValue(side.maxs[i], axis, mins, maxs));\n }\n return { mins: localMins, maxs: localMaxs };\n}\n\nfunction addEpsilon(\n source: MutableVec3,\n axis: Axis | undefined,\n direction: number,\n): MutableVec3 {\n if (!axis || direction === 0) {\n return source;\n }\n const clone = cloneMutable(source);\n adjustAxis(clone, axis, direction);\n return clone;\n}\n\nfunction addEpsilonImmutable(vec: Vec3, axis: Axis | undefined, direction: number): Vec3 {\n if (!axis || direction === 0) {\n return vec;\n }\n switch (axis) {\n case 'x':\n return { ...vec, x: vec.x + direction };\n case 'y':\n return { ...vec, y: vec.y + direction };\n case 'z':\n default:\n return { ...vec, z: vec.z + direction };\n }\n}\n\n/**\n * TypeScript port of G_FixStuckObject_Generic from rerelease p_move.cpp. Attempts to\n * nudge a stuck bounding box out of solid space by probing the faces of the box and\n * moving towards the opposite side, keeping the smallest successful displacement.\n */\nexport function fixStuckObjectGeneric(params: FixStuckParams): FixStuckOutcome {\n const { origin, mins, maxs, trace } = params;\n\n const initial = trace(origin, mins, maxs, origin);\n if (!initial.startsolid) {\n return { result: 'good-position', origin: { ...origin } };\n }\n\n const candidates: CandidatePosition[] = [];\n\n for (let i = 0; i < SIDE_CHECKS.length; i++) {\n const side = SIDE_CHECKS[i];\n const { mins: localMins, maxs: localMaxs } = buildSideBounds(side, mins, maxs);\n\n let start = applySideOffset(origin, side, mins, maxs);\n let tr = trace(start, localMins, localMaxs, start);\n\n let epsilonAxis: Axis | undefined;\n let epsilonDir = 0;\n\n if (tr.startsolid) {\n for (let axisIndex = 0; axisIndex < AXES.length; axisIndex++) {\n if (side.normal[axisIndex] !== 0) {\n continue;\n }\n const axis = AXES[axisIndex];\n let epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, 1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = 1;\n break;\n }\n epsilonStart = cloneMutable(start);\n adjustAxis(epsilonStart, axis, -1);\n tr = trace(epsilonStart, localMins, localMaxs, epsilonStart);\n if (!tr.startsolid) {\n start = epsilonStart;\n epsilonAxis = axis;\n epsilonDir = -1;\n break;\n }\n }\n }\n\n if (tr.startsolid) {\n continue;\n }\n\n const otherSide = SIDE_CHECKS[i ^ 1];\n let oppositeStart = applySideOffset(origin, otherSide, mins, maxs);\n oppositeStart = addEpsilon(oppositeStart, epsilonAxis, epsilonDir);\n\n tr = trace(start, localMins, localMaxs, oppositeStart);\n if (tr.startsolid) {\n continue;\n }\n\n const normal = tupleToVec3(side.normal);\n const end = addVec3(tr.endpos ?? oppositeStart, scaleVec3(normal, 0.125));\n const delta = subtractVec3(end, oppositeStart);\n let newOrigin = addVec3(origin, delta);\n newOrigin = addEpsilonImmutable(newOrigin, epsilonAxis, epsilonDir);\n\n const validation = trace(newOrigin, mins, maxs, newOrigin);\n if (validation.startsolid) {\n continue;\n }\n\n candidates.push({ origin: newOrigin, distance: lengthSquaredVec3(delta) });\n }\n\n if (candidates.length === 0) {\n return { result: 'no-good-position', origin: { ...origin } };\n }\n\n candidates.sort((a, b) => a.distance - b.distance);\n return { result: 'fixed', origin: { ...candidates[0].origin } };\n}\n","import type { ContentsFlag } from '../bsp/contents.js';\nimport {\n CONTENTS_CURRENT_0,\n CONTENTS_CURRENT_180,\n CONTENTS_CURRENT_270,\n CONTENTS_CURRENT_90,\n CONTENTS_CURRENT_DOWN,\n CONTENTS_CURRENT_UP,\n CONTENTS_LADDER,\n MASK_CURRENT,\n} from '../bsp/contents.js';\nimport { addVec3, crossVec3, normalizeVec3, scaleVec3, ZERO_VEC3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, WaterLevel, isAtLeastWaistDeep } from './constants.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nexport interface WaterCurrentParams {\n readonly watertype: ContentsFlag;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly waterSpeed: number;\n}\n\nexport interface GroundCurrentParams {\n readonly groundContents: ContentsFlag;\n readonly scale?: number;\n}\n\nexport interface AddCurrentsParams {\n readonly wishVelocity: Vec3;\n readonly onLadder: boolean;\n readonly onGround: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n readonly groundContents: ContentsFlag;\n readonly cmd: PmoveCmd;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly waterSpeed: number;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace?: PmoveTraceFn;\n}\n\nconst DEFAULT_GROUND_CURRENT_SCALE = 100;\nconst DEFAULT_FORWARD_LADDER_CLAMP = 200;\nconst DEFAULT_SIDE_LADDER_CLAMP = 150;\nconst LADDER_HORIZONTAL_CAP = 25;\nconst LADDER_ASCEND_PITCH_THRESHOLD = 15;\nconst LADDER_TRACE_DISTANCE = 1;\nconst UP_VECTOR: Vec3 = { x: 0, y: 0, z: 1 };\n\nconst DEFAULT_TRACE: PmoveTraceFn = (_, end) => ({\n fraction: 1,\n endpos: end,\n allsolid: false,\n startsolid: false,\n});\n\n/**\n * Mirrors the rerelease pattern in `p_move.cpp` (lines 730-765) that turns the\n * directional CONTENTS_CURRENT_* flags into a unit-ish direction vector.\n */\nexport function currentVectorFromContents(contents: ContentsFlag): Vec3 {\n let x = 0;\n let y = 0;\n let z = 0;\n\n if (contents & CONTENTS_CURRENT_0) {\n x += 1;\n }\n if (contents & CONTENTS_CURRENT_90) {\n y += 1;\n }\n if (contents & CONTENTS_CURRENT_180) {\n x -= 1;\n }\n if (contents & CONTENTS_CURRENT_270) {\n y -= 1;\n }\n if (contents & CONTENTS_CURRENT_UP) {\n z += 1;\n }\n if (contents & CONTENTS_CURRENT_DOWN) {\n z -= 1;\n }\n\n if (x === 0 && y === 0 && z === 0) {\n return ZERO_VEC3;\n }\n\n return { x, y, z };\n}\n\n/**\n * Computes the velocity contribution from water currents using the same rules\n * as `PM_WaterMove`: the CONTENTS_CURRENT_* bits are turned into a direction\n * vector, scaled by `pm_waterspeed`, and halved when the player only has their\n * feet submerged while standing on solid ground.\n */\nexport function waterCurrentVelocity(params: WaterCurrentParams): Vec3 {\n const { watertype, waterlevel, onGround, waterSpeed } = params;\n\n if ((watertype & MASK_CURRENT) === 0) {\n return ZERO_VEC3;\n }\n\n const direction = currentVectorFromContents(watertype);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n let scale = waterSpeed;\n if (waterlevel === WaterLevel.Feet && onGround) {\n scale *= 0.5;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Computes the conveyor-style velocity that should be applied while touching a\n * ground plane that carries CONTENTS_CURRENT_* bits. The rerelease multiplies\n * the direction vector by 100 units per second, so we expose the same default\n * while allowing callers to override the scalar for tests.\n */\nexport function groundCurrentVelocity(params: GroundCurrentParams): Vec3 {\n const { groundContents, scale = DEFAULT_GROUND_CURRENT_SCALE } = params;\n\n const direction = currentVectorFromContents(groundContents);\n if (direction === ZERO_VEC3) {\n return ZERO_VEC3;\n }\n\n return scaleVec3(direction, scale);\n}\n\n/**\n * Pure mirror of PM_AddCurrents from rerelease `p_move.cpp`: handles ladder\n * specific motion tweaks, water currents, and conveyor-style ground currents\n * before pmove acceleration is applied.\n */\nexport function applyPmoveAddCurrents(params: AddCurrentsParams): Vec3 {\n const {\n wishVelocity,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed,\n ladderMod,\n waterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace = DEFAULT_TRACE,\n } = params;\n\n let adjusted = wishVelocity;\n\n if (onLadder) {\n adjusted = applyLadderAdjustments({\n wishVelocity: adjusted,\n cmd,\n waterlevel,\n viewPitch,\n maxSpeed,\n ladderMod,\n onGround,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n }\n\n const waterVelocity = waterCurrentVelocity({ watertype, waterlevel, onGround, waterSpeed });\n if (waterVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, waterVelocity);\n }\n\n if (onGround) {\n const groundVelocity = groundCurrentVelocity({ groundContents });\n if (groundVelocity !== ZERO_VEC3) {\n adjusted = addVec3(adjusted, groundVelocity);\n }\n }\n\n return adjusted;\n}\n\ninterface LadderAdjustParams {\n readonly wishVelocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly maxSpeed: number;\n readonly ladderMod: number;\n readonly onGround: boolean;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nfunction applyLadderAdjustments(params: LadderAdjustParams): Vec3 {\n const { wishVelocity, cmd, waterlevel, viewPitch, maxSpeed, ladderMod, onGround, forward, origin, mins, maxs, trace } = params;\n const buttons = cmd.buttons ?? 0;\n let adjusted = { ...wishVelocity };\n\n if ((buttons & (PlayerButton.Jump | PlayerButton.Crouch)) !== 0) {\n const ladderSpeed = isAtLeastWaistDeep(waterlevel) ? maxSpeed : DEFAULT_FORWARD_LADDER_CLAMP;\n adjusted = {\n ...adjusted,\n z: buttons & PlayerButton.Jump ? ladderSpeed : -ladderSpeed,\n };\n } else if (cmd.forwardmove) {\n const clamped = clamp(cmd.forwardmove, -DEFAULT_FORWARD_LADDER_CLAMP, DEFAULT_FORWARD_LADDER_CLAMP);\n if (cmd.forwardmove > 0) {\n const climb = viewPitch < LADDER_ASCEND_PITCH_THRESHOLD ? clamped : -clamped;\n adjusted = { ...adjusted, z: climb };\n } else {\n if (!onGround) {\n adjusted = { ...adjusted, x: 0, y: 0 };\n }\n adjusted = { ...adjusted, z: clamped };\n }\n } else {\n adjusted = { ...adjusted, z: 0 };\n }\n\n if (!onGround) {\n if (cmd.sidemove) {\n let sideSpeed = clamp(cmd.sidemove, -DEFAULT_SIDE_LADDER_CLAMP, DEFAULT_SIDE_LADDER_CLAMP);\n if (waterlevel < WaterLevel.Waist) {\n sideSpeed *= ladderMod;\n }\n\n const flatForward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n if (flatForward.x !== 0 || flatForward.y !== 0) {\n const spot = addVec3(origin, scaleVec3(flatForward, LADDER_TRACE_DISTANCE));\n const tr = trace(origin, spot, mins, maxs);\n if (\n tr.fraction !== 1 &&\n !tr.allsolid &&\n tr.contents !== undefined &&\n (tr.contents & CONTENTS_LADDER) !== 0 &&\n tr.planeNormal\n ) {\n const right = crossVec3(tr.planeNormal, UP_VECTOR);\n adjusted = { ...adjusted, x: 0, y: 0 };\n adjusted = addVec3(adjusted, scaleVec3(right, -sideSpeed));\n }\n }\n } else {\n adjusted = {\n ...adjusted,\n x: clampHorizontal(adjusted.x),\n y: clampHorizontal(adjusted.y),\n };\n }\n }\n\n return adjusted;\n}\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction clampHorizontal(value: number): number {\n if (value < -LADDER_HORIZONTAL_CAP) {\n return -LADDER_HORIZONTAL_CAP;\n }\n if (value > LADDER_HORIZONTAL_CAP) {\n return LADDER_HORIZONTAL_CAP;\n }\n return value;\n}\n","import { addVec3, lengthVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from './constants.js';\nimport { applyPmoveAccelerate } from './pmove.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\n\nconst FLY_FRICTION_MULTIPLIER = 1.5;\nconst BUTTON_VERTICAL_SCALE = 0.5;\nconst DEFAULT_OVERBOUNCE = 1.01;\n\nexport interface FlyMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly frametime: number;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmMaxSpeed: number;\n readonly pmAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly doclip: boolean;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly trace?: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport type FlyMoveResult = StepSlideMoveOutcome;\n\n/**\n * Pure translation of PM_FlyMove from rerelease `p_move.cpp`: applies the\n * spectator/noclip friction and acceleration rules, then either advances the\n * origin freely or resolves movement through `stepSlideMove` when clipping is\n * requested. This keeps the spectator and noclip physics deterministic between\n * the client and server.\n */\nexport function applyPmoveFlyMove(params: FlyMoveParams): FlyMoveResult {\n const {\n origin,\n cmd,\n frametime,\n pmFriction,\n pmStopSpeed,\n pmMaxSpeed,\n pmAccelerate,\n pmWaterSpeed,\n doclip,\n forward,\n right,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n let velocity = applyFlyFriction({ velocity: params.velocity, pmFriction, pmStopSpeed, frametime });\n\n const wishdirVelocity = buildFlyWishVelocity({\n cmd,\n forward,\n right,\n pmMaxSpeed,\n pmWaterSpeed,\n });\n\n if (wishdirVelocity.wishspeed > 0) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wishdirVelocity.wishdir,\n wishspeed: wishdirVelocity.accelSpeed,\n accel: pmAccelerate,\n frametime,\n });\n }\n\n if (!doclip) {\n const originDelta = scaleVec3(velocity, frametime);\n const nextOrigin = addVec3(origin, originDelta);\n return {\n origin: nextOrigin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: velocity.x === 0 && velocity.y === 0 && velocity.z === 0,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n if (!trace || !mins || !maxs) {\n throw new Error('applyPmoveFlyMove: doclip=true requires trace/mins/maxs');\n }\n\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n overbounce,\n trace,\n mins,\n maxs,\n stepSize,\n maxBumps,\n maxClipPlanes,\n });\n}\n\ninterface FlyFrictionParams {\n readonly velocity: Vec3;\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly frametime: number;\n}\n\nfunction applyFlyFriction(params: FlyFrictionParams): Vec3 {\n const { velocity, pmFriction, pmStopSpeed, frametime } = params;\n const speed = lengthVec3(velocity);\n\n if (speed < 1) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const friction = pmFriction * FLY_FRICTION_MULTIPLIER;\n const control = speed < pmStopSpeed ? pmStopSpeed : speed;\n const drop = control * friction * frametime;\n\n let newspeed = speed - drop;\n if (newspeed < 0) {\n newspeed = 0;\n }\n\n if (newspeed === speed) {\n return velocity;\n }\n\n return scaleVec3(velocity, newspeed / speed);\n}\n\ninterface FlyWishVelocityParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmMaxSpeed: number;\n readonly pmWaterSpeed: number;\n}\n\ninterface FlyWishVelocityResult {\n readonly wishdir: Vec3;\n readonly wishspeed: number;\n readonly accelSpeed: number;\n}\n\nfunction buildFlyWishVelocity(params: FlyWishVelocityParams): FlyWishVelocityResult {\n const { cmd, forward, right, pmMaxSpeed, pmWaterSpeed } = params;\n\n const forwardNorm = normalizeVec3(forward);\n const rightNorm = normalizeVec3(right);\n\n const wishvel = {\n x: forwardNorm.x * cmd.forwardmove + rightNorm.x * cmd.sidemove,\n y: forwardNorm.y * cmd.forwardmove + rightNorm.y * cmd.sidemove,\n z: forwardNorm.z * cmd.forwardmove + rightNorm.z * cmd.sidemove,\n } satisfies Vec3;\n\n let adjusted = wishvel;\n const buttons = cmd.buttons ?? 0;\n\n if (buttons & PlayerButton.Jump) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n if (buttons & PlayerButton.Crouch) {\n adjusted = addVec3(adjusted, { x: 0, y: 0, z: -pmWaterSpeed * BUTTON_VERTICAL_SCALE });\n }\n\n let wishspeed = lengthVec3(adjusted);\n let wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n adjusted = scaleVec3(adjusted, scale);\n wishspeed = pmMaxSpeed;\n wishdir = wishspeed === 0 ? { x: 0, y: 0, z: 0 } : normalizeVec3(adjusted);\n }\n\n const accelSpeed = wishspeed * 2;\n\n return { wishdir, wishspeed, accelSpeed };\n}\n","import { MASK_WATER, CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel } from './constants.js';\nimport type { PmovePointContentsFn } from './types.js';\n\nexport interface WaterLevelParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly viewheight: number;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface WaterLevelResult {\n readonly waterlevel: WaterLevel;\n readonly watertype: ContentsFlag;\n}\n\n/**\n * Mirrors the rerelease `PM_GetWaterLevel` helper: probes the player's feet,\n * waist, and viewheight to determine how submerged they are and returns both\n * the enum level plus the contents bits encountered at the lowest sample.\n */\nexport function getWaterLevel(params: WaterLevelParams): WaterLevelResult {\n const { origin, mins, viewheight, pointContents } = params;\n\n const sample2 = viewheight - mins.z;\n const sample1 = sample2 / 2;\n\n const point: Vec3 = {\n x: origin.x,\n y: origin.y,\n z: origin.z + mins.z + 1,\n };\n\n let contents = pointContents(point);\n if ((contents & MASK_WATER) === 0) {\n return { waterlevel: WaterLevel.None, watertype: CONTENTS_NONE };\n }\n\n const watertype = contents;\n let waterlevel = WaterLevel.Feet;\n\n let point2: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample1 };\n contents = pointContents(point2);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Waist;\n\n let point3: Vec3 = { x: point.x, y: point.y, z: origin.z + mins.z + sample2 };\n contents = pointContents(point3);\n if ((contents & MASK_WATER) !== 0) {\n waterlevel = WaterLevel.Under;\n }\n }\n\n return { waterlevel, watertype };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { WaterLevel, type PmFlags, PmFlag, PmType, PlayerButton, addPmFlag, removePmFlag } from './constants.js';\n\nconst DEFAULT_JUMP_HEIGHT = 270;\n\nexport interface CheckJumpParams {\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpHeight?: number;\n}\n\nexport interface CheckJumpResult {\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly velocity: Vec3;\n readonly jumpSound: boolean;\n readonly jumped: boolean;\n}\n\nfunction hasButton(buttons: number, button: PlayerButton): boolean {\n return (buttons & button) !== 0;\n}\n\n/**\n * Pure translation of the rerelease `PM_CheckJump` helper from `p_move.cpp`.\n * The function takes in the minimal pmove state that the original C++ logic\n * touches and returns the updated flag/origin/velocity tuple so callers can\n * apply the same semantics on both the server and client.\n */\nexport function checkJump(params: CheckJumpParams): CheckJumpResult {\n const { pmFlags, pmType, buttons, waterlevel, onGround, velocity, jumpHeight = DEFAULT_JUMP_HEIGHT } = params;\n\n // PM_CheckJump immediately bails while the landing timer is active.\n if (pmFlags & PmFlag.TimeLand) {\n return { pmFlags, onGround, velocity, jumpSound: false, jumped: false };\n }\n\n const holdingJump = hasButton(buttons, PlayerButton.Jump);\n let nextFlags = pmFlags;\n let nextOnGround = onGround;\n let jumpSound = false;\n let jumped = false;\n let nextVelocity = velocity;\n\n if (!holdingJump) {\n nextFlags = removePmFlag(nextFlags, PmFlag.JumpHeld);\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (hasPmJumpHold(nextFlags)) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (pmType === PmType.Dead) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (waterlevel >= WaterLevel.Waist) {\n nextOnGround = false;\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n if (!nextOnGround) {\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n }\n\n nextFlags = addPmFlag(nextFlags, PmFlag.JumpHeld);\n nextFlags = removePmFlag(nextFlags, PmFlag.OnGround);\n nextOnGround = false;\n jumpSound = true;\n jumped = true;\n\n const z = velocity.z + jumpHeight;\n const finalZ = z < jumpHeight ? jumpHeight : z;\n nextVelocity = { ...velocity, z: finalZ };\n\n return { pmFlags: nextFlags, onGround: nextOnGround, velocity: nextVelocity, jumpSound, jumped };\n}\n\nfunction hasPmJumpHold(flags: PmFlags): boolean {\n return (flags & PmFlag.JumpHeld) !== 0;\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { PmFlag, type PmFlags, PmType } from './constants.js';\n\nexport interface PlayerDimensions {\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n}\n\nfunction createVec3(x: number, y: number, z: number): Vec3 {\n return { x, y, z } satisfies Vec3;\n}\n\n/**\n * Pure mirror of PM_SetDimensions from rerelease `p_move.cpp`.\n * Computes the mins/maxs/viewheight triplet for a player based on\n * their movement type and ducked flag without mutating inputs.\n */\nexport function computePlayerDimensions(pmType: PmType, pmFlags: PmFlags): PlayerDimensions {\n const minsBase = createVec3(-16, -16, 0);\n const maxsBase = createVec3(16, 16, 16);\n\n if (pmType === PmType.Gib) {\n return {\n mins: minsBase,\n maxs: maxsBase,\n viewheight: 8,\n } satisfies PlayerDimensions;\n }\n\n const ducked = pmType === PmType.Dead || (pmFlags & PmFlag.Ducked) !== 0;\n const mins = createVec3(minsBase.x, minsBase.y, -24);\n const maxs = createVec3(maxsBase.x, maxsBase.y, ducked ? 4 : 32);\n\n return {\n mins,\n maxs,\n viewheight: ducked ? -2 : 22,\n } satisfies PlayerDimensions;\n}\n","import { MASK_SOLID, MASK_WATER, type ContentsFlag } from '../bsp/contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport {\n PlayerButton,\n PmFlag,\n type PmFlags,\n PmType,\n WaterLevel,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport type { PmoveTraceResult } from './types.js';\nimport { computePlayerDimensions, type PlayerDimensions } from './dimensions.js';\n\nconst CROUCH_MAX_Z = 4;\nconst STAND_MAX_Z = 32;\nconst ABOVE_WATER_OFFSET = 8;\n\nexport interface DuckTraceParams {\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly mask: ContentsFlag;\n}\n\nexport type DuckTraceFn = (params: DuckTraceParams) => PmoveTraceResult;\n\nexport interface CheckDuckParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly buttons: number;\n readonly waterlevel: WaterLevel;\n readonly hasGroundEntity: boolean;\n readonly onLadder: boolean;\n readonly n64Physics: boolean;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: DuckTraceFn;\n}\n\nexport interface CheckDuckResult extends PlayerDimensions {\n readonly pmFlags: PmFlags;\n readonly ducked: boolean;\n readonly changed: boolean;\n}\n\n/**\n * Pure port of PM_CheckDuck from rerelease `p_move.cpp`. Updates the PMF_DUCKED flag\n * based on crouch input, obstruction traces, and special cases (dead bodies) without\n * mutating the provided mins/maxs. Returns the updated flag word plus the dimensions\n * computed from PM_SetDimensions so callers can update collision bounds atomically.\n */\nexport function checkDuckState(params: CheckDuckParams): CheckDuckResult {\n const { pmType } = params;\n\n if (pmType === PmType.Gib) {\n const dims = computePlayerDimensions(pmType, params.pmFlags);\n return { pmFlags: params.pmFlags, ducked: hasPmFlag(params.pmFlags, PmFlag.Ducked), changed: false, ...dims };\n }\n\n let flags = params.pmFlags;\n let changed = false;\n\n if (pmType === PmType.Dead) {\n if (!hasPmFlag(flags, PmFlag.Ducked)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (shouldDuck(params)) {\n if (!hasPmFlag(flags, PmFlag.Ducked) && !isDuckBlocked(params)) {\n flags = addPmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n } else if (hasPmFlag(flags, PmFlag.Ducked) && !isStandBlocked(params)) {\n flags = removePmFlag(flags, PmFlag.Ducked);\n changed = true;\n }\n\n const dims = computePlayerDimensions(pmType, flags);\n const ducked = pmType === PmType.Dead || hasPmFlag(flags, PmFlag.Ducked);\n\n return { pmFlags: flags, ducked, changed, ...dims };\n}\n\nfunction shouldDuck(params: CheckDuckParams): boolean {\n if ((params.buttons & PlayerButton.Crouch) === 0) {\n return false;\n }\n if (params.onLadder || params.n64Physics) {\n return false;\n }\n if (params.hasGroundEntity) {\n return true;\n }\n if (params.waterlevel <= WaterLevel.Feet && !isAboveWater(params)) {\n return true;\n }\n return false;\n}\n\nfunction isDuckBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, CROUCH_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isStandBlocked(params: CheckDuckParams): boolean {\n const trace = params.trace({\n start: params.origin,\n end: params.origin,\n mins: params.mins,\n maxs: withZ(params.maxs, STAND_MAX_Z),\n mask: MASK_SOLID,\n });\n return trace.allsolid;\n}\n\nfunction isAboveWater(params: CheckDuckParams): boolean {\n const below: Vec3 = { x: params.origin.x, y: params.origin.y, z: params.origin.z - ABOVE_WATER_OFFSET };\n\n const solidTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_SOLID,\n });\n\n if (solidTrace.fraction < 1) {\n return false;\n }\n\n const waterTrace = params.trace({\n start: params.origin,\n end: below,\n mins: params.mins,\n maxs: params.maxs,\n mask: MASK_WATER,\n });\n\n return waterTrace.fraction < 1;\n}\n\nfunction withZ(vec: Vec3, z: number): Vec3 {\n return { x: vec.x, y: vec.y, z };\n}\n","import { CONTENTS_NONE, type ContentsFlag } from '../bsp/contents.js';\nimport { addVec3, clipVelocityVec3, type Vec3 } from '../math/vec3.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n addPmFlag,\n hasPmFlag,\n removePmFlag,\n} from './constants.js';\nimport { getWaterLevel } from './water.js';\nimport type { PmovePointContentsFn, PmoveTraceFn, PmoveTraceResult } from './types.js';\n\nconst GROUND_PROBE_DISTANCE = 0.25;\nconst LADDER_BYPASS_VELOCITY = 180;\nconst TRICK_VELOCITY_THRESHOLD = 100;\nconst SLANTED_NORMAL_THRESHOLD = 0.7;\nconst TRICK_NORMAL_THRESHOLD = 0.9;\nconst TRICK_PM_TIME = 64;\nconst LAND_PM_TIME = 128;\nconst IMPACT_CLIP_OVERBOUNCE = 1.01;\n\nconst WATERJUMP_CLEAR =\n PmFlag.TimeWaterJump | PmFlag.TimeLand | PmFlag.TimeTeleport | PmFlag.TimeTrick;\n\nexport interface CategorizePositionParams {\n readonly pmType: PmType;\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly n64Physics: boolean;\n readonly velocity: Vec3;\n readonly startVelocity: Vec3;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n}\n\nexport interface CategorizePositionResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly onGround: boolean;\n readonly groundTrace?: PmoveTraceResult;\n readonly groundContents: ContentsFlag;\n readonly waterlevel: number;\n readonly watertype: ContentsFlag;\n readonly impactDelta?: number;\n}\n\n/**\n * Pure mirror of PM_CatagorizePosition from `rerelease/p_move.cpp`: traces a quarter-unit\n * below the player bounds to determine whether they stand on solid ground, updates timers\n * and pmflags accordingly, records the latest ground plane data, and recalculates waterlevel\n * by probing feet/waist/viewheight samples.\n */\nexport function categorizePosition(params: CategorizePositionParams): CategorizePositionResult {\n const {\n pmType,\n n64Physics,\n velocity,\n startVelocity,\n origin,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n } = params;\n\n let pmFlags = params.pmFlags;\n let pmTime = params.pmTime;\n let impactDelta: number | undefined;\n let onGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n let groundTrace: PmoveTraceResult | undefined;\n let groundContents: ContentsFlag = CONTENTS_NONE;\n\n const forceAirborne = velocity.z > LADDER_BYPASS_VELOCITY || pmType === PmType.Grapple;\n\n if (forceAirborne) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n const end: Vec3 = { x: origin.x, y: origin.y, z: origin.z - GROUND_PROBE_DISTANCE };\n const traceResult = trace(origin, end, mins, maxs);\n groundTrace = traceResult;\n groundContents = traceResult.contents ?? CONTENTS_NONE;\n\n const planeNormal = traceResult.planeNormal;\n\n let slantedGround =\n traceResult.fraction < 1 && !!planeNormal && planeNormal.z < SLANTED_NORMAL_THRESHOLD;\n\n if (slantedGround && planeNormal) {\n const slantEnd = addVec3(origin, planeNormal);\n const slantTrace = trace(origin, slantEnd, mins, maxs);\n if (slantTrace.fraction < 1 && !slantTrace.startsolid) {\n slantedGround = false;\n }\n }\n\n if (\n traceResult.fraction === 1 ||\n !planeNormal ||\n (slantedGround && !traceResult.startsolid)\n ) {\n pmFlags = removePmFlag(pmFlags, PmFlag.OnGround);\n onGround = false;\n } else {\n onGround = true;\n\n if (hasPmFlag(pmFlags, PmFlag.TimeWaterJump)) {\n pmFlags &= ~WATERJUMP_CLEAR;\n pmTime = 0;\n }\n\n const wasOnGround = hasPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround) {\n if (\n !n64Physics &&\n velocity.z >= TRICK_VELOCITY_THRESHOLD &&\n planeNormal.z >= TRICK_NORMAL_THRESHOLD &&\n !hasPmFlag(pmFlags, PmFlag.Ducked)\n ) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeTrick);\n pmTime = TRICK_PM_TIME;\n }\n\n const clipped = clipVelocityVec3(velocity, planeNormal, IMPACT_CLIP_OVERBOUNCE);\n impactDelta = startVelocity.z - clipped.z;\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.OnGround);\n\n if (!wasOnGround && (n64Physics || hasPmFlag(pmFlags, PmFlag.Ducked))) {\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeLand);\n pmTime = LAND_PM_TIME;\n }\n }\n }\n\n const { waterlevel, watertype } = getWaterLevel({\n origin,\n mins,\n viewheight,\n pointContents,\n });\n\n return {\n pmFlags,\n pmTime,\n onGround: hasPmFlag(pmFlags, PmFlag.OnGround),\n groundTrace,\n groundContents,\n waterlevel,\n watertype,\n impactDelta,\n };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { addVec3, lengthVec3, normalizeVec3, scaleVec3 } from '../math/vec3.js';\nimport { applyPmoveAccelerate, applyPmoveAirAccelerate } from './pmove.js';\nimport { applyPmoveAddCurrents } from './currents.js';\nimport { stepSlideMove, type StepSlideMoveOutcome } from './slide.js';\nimport type { PmoveCmd, PmoveTraceFn } from './types.js';\nimport {\n PmFlag,\n type PmFlags,\n PmType,\n PlayerButton,\n WaterLevel,\n hasPmFlag,\n} from './constants.js';\n\ninterface BaseMoveParams {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly frametime: number;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n readonly hasTime?: boolean;\n}\n\nexport interface AirMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly gravity: number;\n readonly pmType: PmType;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate?: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly onLadder: boolean;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly groundContents: number;\n readonly viewPitch: number;\n readonly ladderMod: number;\n readonly pmWaterSpeed: number;\n}\n\nexport interface WaterMoveParams extends BaseMoveParams {\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly right: Vec3;\n readonly pmFlags: PmFlags;\n readonly onGround: boolean;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterSpeed: number;\n readonly onLadder: boolean;\n readonly watertype: number;\n readonly groundContents: number;\n readonly waterlevel: WaterLevel;\n readonly viewPitch: number;\n readonly ladderMod: number;\n}\n\nconst DEFAULT_AIR_ACCELERATE = 1;\nconst WATER_DRIFT_SPEED = 60;\nconst DEFAULT_STEP_OVERBOUNCE = 1.01;\n\nexport function applyPmoveAirMove(params: AirMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n gravity,\n pmType,\n pmAccelerate,\n pmAirAccelerate = DEFAULT_AIR_ACCELERATE,\n pmMaxSpeed,\n pmDuckSpeed,\n onLadder,\n waterlevel,\n watertype,\n groundContents,\n viewPitch,\n ladderMod,\n pmWaterSpeed,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildPlanarWishVelocity(forward, right, cmd);\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n const maxSpeed = ducked ? pmDuckSpeed : pmMaxSpeed;\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > maxSpeed) {\n const scale = maxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = maxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n if (onLadder) {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (Math.abs(wishvel.z) < Number.EPSILON) {\n velocity = dampVerticalVelocity(velocity, gravity, frametime);\n }\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (onGround) {\n velocity = { ...velocity, z: 0 };\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmAccelerate, frametime });\n if (gravity > 0) {\n velocity = { ...velocity, z: 0 };\n } else {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n if (velocity.x === 0 && velocity.y === 0) {\n return {\n origin,\n velocity,\n planes: [],\n blocked: 0,\n stopped: true,\n stepped: false,\n stepHeight: 0,\n };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n }\n\n if (pmAirAccelerate > 0) {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir,\n wishspeed,\n accel: pmAirAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: DEFAULT_AIR_ACCELERATE, frametime });\n }\n\n if (pmType !== PmType.Grapple) {\n velocity = { ...velocity, z: velocity.z - gravity * frametime };\n }\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nexport function applyPmoveWaterMove(params: WaterMoveParams): StepSlideMoveOutcome {\n const {\n origin,\n frametime,\n mins,\n maxs,\n trace,\n overbounce = DEFAULT_STEP_OVERBOUNCE,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n forward,\n right,\n cmd,\n pmFlags,\n onGround,\n pmMaxSpeed,\n pmDuckSpeed,\n pmWaterAccelerate,\n pmWaterSpeed,\n onLadder,\n watertype,\n groundContents,\n waterlevel,\n viewPitch,\n ladderMod,\n } = params;\n\n let velocity = { ...params.velocity };\n let wishvel = buildFullWishVelocity(forward, right, cmd);\n\n if (isIdleInWater(cmd, onGround)) {\n wishvel = { ...wishvel, z: wishvel.z - WATER_DRIFT_SPEED };\n } else {\n if (hasButton(cmd, PlayerButton.Crouch)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: -pmWaterSpeed * 0.5 });\n } else if (hasButton(cmd, PlayerButton.Jump)) {\n wishvel = addVec3(wishvel, { x: 0, y: 0, z: pmWaterSpeed * 0.5 });\n }\n }\n\n wishvel = applyPmoveAddCurrents({\n wishVelocity: wishvel,\n onLadder,\n onGround,\n waterlevel,\n watertype,\n groundContents,\n cmd,\n viewPitch,\n maxSpeed: hasPmFlag(pmFlags, PmFlag.Ducked) ? pmDuckSpeed : pmMaxSpeed,\n ladderMod,\n waterSpeed: pmWaterSpeed,\n forward,\n origin,\n mins,\n maxs,\n trace,\n });\n\n let wishdir = wishvel;\n let wishspeed = lengthVec3(wishdir);\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishdir);\n }\n\n if (wishspeed > pmMaxSpeed) {\n const scale = pmMaxSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmMaxSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n wishspeed *= 0.5;\n\n const ducked = hasPmFlag(pmFlags, PmFlag.Ducked);\n if (ducked && wishspeed > pmDuckSpeed) {\n const scale = pmDuckSpeed / wishspeed;\n wishvel = scaleVec3(wishvel, scale);\n wishspeed = pmDuckSpeed;\n if (wishspeed !== 0) {\n wishdir = normalizeVec3(wishvel);\n }\n }\n\n velocity = applyPmoveAccelerate({ velocity, wishdir, wishspeed, accel: pmWaterAccelerate, frametime });\n\n return runStepSlideMove({\n origin,\n velocity,\n frametime,\n mins,\n maxs,\n trace,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n\nfunction buildPlanarWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: 0,\n } satisfies Vec3;\n}\n\nfunction buildFullWishVelocity(forward: Vec3, right: Vec3, cmd: PmoveCmd): Vec3 {\n return {\n x: forward.x * cmd.forwardmove + right.x * cmd.sidemove,\n y: forward.y * cmd.forwardmove + right.y * cmd.sidemove,\n z: forward.z * cmd.forwardmove + right.z * cmd.sidemove,\n } satisfies Vec3;\n}\n\nfunction hasButton(cmd: PmoveCmd, button: PlayerButton): boolean {\n return (cmd.buttons ?? 0) & button ? true : false;\n}\n\nfunction isIdleInWater(cmd: PmoveCmd, onGround: boolean): boolean {\n const noMove = cmd.forwardmove === 0 && cmd.sidemove === 0;\n const noButtons = (cmd.buttons ?? 0) & (PlayerButton.Jump | PlayerButton.Crouch) ? false : true;\n return noMove && noButtons && !onGround;\n}\n\nfunction dampVerticalVelocity(velocity: Vec3, gravity: number, frametime: number): Vec3 {\n let z = velocity.z;\n const delta = gravity * frametime;\n if (z > 0) {\n z -= delta;\n if (z < 0) {\n z = 0;\n }\n } else {\n z += delta;\n if (z > 0) {\n z = 0;\n }\n }\n return { ...velocity, z };\n}\n\ninterface StepParams extends BaseMoveParams {\n readonly velocity: Vec3;\n}\n\nfunction runStepSlideMove(params: StepParams): StepSlideMoveOutcome {\n const { origin, velocity, frametime, mins, maxs, trace, overbounce = DEFAULT_STEP_OVERBOUNCE, stepSize, maxBumps, maxClipPlanes, hasTime } = params;\n return stepSlideMove({\n origin,\n velocity,\n frametime,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n}\n","import { CONTENTS_LADDER, CONTENTS_NONE, CONTENTS_NO_WATERJUMP } from '../bsp/contents.js';\nimport { addVec3, lengthSquaredVec3, normalizeVec3, scaleVec3, type Vec3 } from '../math/vec3.js';\nimport { PlayerButton, PmFlag, type PmFlags, addPmFlag, removePmFlag, WaterLevel } from './constants.js';\nimport { stepSlideMove } from './slide.js';\nimport type { PmoveCmd, PmovePointContentsFn, PmoveTraceFn } from './types.js';\nimport { getWaterLevel } from './water.js';\n\nconst LADDER_TRACE_DISTANCE = 1;\nconst WATERJUMP_FORWARD_CHECK = 40;\nconst WATERJUMP_FORWARD_SPEED = 50;\nconst WATERJUMP_UPWARD_SPEED = 350;\nconst WATERJUMP_PM_TIME = 2048;\nconst WATERJUMP_SIM_STEP = 0.1;\nconst WATERJUMP_BASE_GRAVITY = 800;\nconst WATERJUMP_MAX_STEPS = 50;\nconst GROUND_NORMAL_THRESHOLD = 0.7;\nconst WATERJUMP_STEP_TOLERANCE = 18;\nconst DEFAULT_OVERBOUNCE = 1.01;\nconst WATERJUMP_DOWN_PROBE = 2;\n\nexport interface SpecialMovementParams {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly waterlevel: WaterLevel;\n readonly watertype: number;\n readonly gravity: number;\n readonly cmd: PmoveCmd;\n readonly forward: Vec3;\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly viewheight: number;\n readonly trace: PmoveTraceFn;\n readonly pointContents: PmovePointContentsFn;\n readonly onGround: boolean;\n readonly overbounce?: number;\n readonly stepSize?: number;\n readonly maxBumps?: number;\n readonly maxClipPlanes?: number;\n}\n\nexport interface SpecialMovementResult {\n readonly pmFlags: PmFlags;\n readonly pmTime: number;\n readonly velocity: Vec3;\n readonly performedWaterJump: boolean;\n}\n\n/**\n * Mirrors the ladder detection and water-jump probing logic from\n * `PM_CheckSpecialMovement` in `rerelease/p_move.cpp`. The helper clears and\n * re-adds the ladder flag based on nearby CONTENTS_LADDER brushes, then\n * simulates a potential water jump by firing the same 40-unit probe and\n * step-slide loop the C++ uses before committing to the upward velocity.\n */\nexport function checkSpecialMovement(params: SpecialMovementParams): SpecialMovementResult {\n const {\n pmFlags: initialFlags,\n pmTime: initialPmTime,\n waterlevel,\n watertype,\n gravity,\n cmd,\n forward,\n origin,\n velocity: initialVelocity,\n mins,\n maxs,\n viewheight,\n trace,\n pointContents,\n onGround,\n overbounce = DEFAULT_OVERBOUNCE,\n stepSize = WATERJUMP_STEP_TOLERANCE,\n maxBumps,\n maxClipPlanes,\n } = params;\n\n if (initialPmTime > 0) {\n return { pmFlags: initialFlags, pmTime: initialPmTime, velocity: initialVelocity, performedWaterJump: false };\n }\n\n let pmFlags = removePmFlag(initialFlags, PmFlag.OnLadder);\n let pmTime = initialPmTime;\n let velocity = initialVelocity;\n\n const flatforward = normalizeVec3({ x: forward.x, y: forward.y, z: 0 });\n const hasForward = lengthSquaredVec3(flatforward) > 0;\n\n if (waterlevel < WaterLevel.Waist && hasForward) {\n const ladderEnd = addVec3(origin, scaleVec3(flatforward, LADDER_TRACE_DISTANCE));\n const ladderTrace = trace(origin, ladderEnd, mins, maxs);\n const contents = ladderTrace.contents ?? CONTENTS_NONE;\n\n if (ladderTrace.fraction < 1 && (contents & CONTENTS_LADDER) !== 0) {\n pmFlags = addPmFlag(pmFlags, PmFlag.OnLadder);\n }\n }\n\n if (gravity === 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (((cmd.buttons ?? 0) & PlayerButton.Jump) === 0 && cmd.forwardmove <= 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (waterlevel !== WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if ((watertype & CONTENTS_NO_WATERJUMP) !== 0) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (!hasForward) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const forwardCheckEnd = addVec3(origin, scaleVec3(flatforward, WATERJUMP_FORWARD_CHECK));\n const forwardTrace = trace(origin, forwardCheckEnd, mins, maxs);\n\n if (\n forwardTrace.fraction === 1 ||\n !forwardTrace.planeNormal ||\n forwardTrace.planeNormal.z >= GROUND_NORMAL_THRESHOLD\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n let simVelocity: Vec3 = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n };\n\n let simOrigin = origin;\n let hasTime = true;\n const stepCount = computeWaterJumpSteps(gravity);\n\n for (let i = 0; i < stepCount; i++) {\n simVelocity = { x: simVelocity.x, y: simVelocity.y, z: simVelocity.z - gravity * WATERJUMP_SIM_STEP };\n if (simVelocity.z < 0) {\n hasTime = false;\n }\n\n const move = stepSlideMove({\n origin: simOrigin,\n velocity: simVelocity,\n frametime: WATERJUMP_SIM_STEP,\n trace,\n mins,\n maxs,\n overbounce,\n stepSize,\n maxBumps,\n maxClipPlanes,\n hasTime,\n });\n simOrigin = move.origin;\n simVelocity = move.velocity;\n }\n\n const downEnd = addVec3(simOrigin, { x: 0, y: 0, z: -WATERJUMP_DOWN_PROBE });\n const downTrace = trace(simOrigin, downEnd, mins, maxs);\n\n if (\n downTrace.fraction === 1 ||\n !downTrace.planeNormal ||\n downTrace.planeNormal.z < GROUND_NORMAL_THRESHOLD ||\n downTrace.endpos.z < origin.z\n ) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n if (onGround && Math.abs(origin.z - downTrace.endpos.z) <= stepSize) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n const landingWater = getWaterLevel({ origin: downTrace.endpos, mins, viewheight, pointContents });\n if (landingWater.waterlevel >= WaterLevel.Waist) {\n return { pmFlags, pmTime, velocity, performedWaterJump: false };\n }\n\n pmFlags = addPmFlag(pmFlags, PmFlag.TimeWaterJump);\n pmTime = WATERJUMP_PM_TIME;\n velocity = {\n x: flatforward.x * WATERJUMP_FORWARD_SPEED,\n y: flatforward.y * WATERJUMP_FORWARD_SPEED,\n z: WATERJUMP_UPWARD_SPEED,\n } satisfies Vec3;\n\n return { pmFlags, pmTime, velocity, performedWaterJump: true };\n}\n\nfunction computeWaterJumpSteps(gravity: number): number {\n if (gravity === 0) {\n return 0;\n }\n\n const scaled = Math.floor(10 * (WATERJUMP_BASE_GRAVITY / gravity));\n if (scaled <= 0) {\n return 0;\n }\n return Math.min(WATERJUMP_MAX_STEPS, scaled);\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { fixStuckObjectGeneric } from './stuck.js';\nimport type { PmoveTraceFn } from './types.js';\n\nconst SNAP_OFFSETS = [0, -1, 1] as const;\n\nexport interface GoodPositionParams {\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly trace: PmoveTraceFn;\n}\n\nexport function goodPosition(params: GoodPositionParams): boolean {\n const { origin, mins, maxs, trace } = params;\n const result = trace(origin, origin, mins, maxs);\n return result.allsolid ? false : true;\n}\n\nexport type SnapResolution = 'unchanged' | 'fixed' | 'reverted';\n\nexport interface SnapPositionParams extends GoodPositionParams {\n readonly velocity: Vec3;\n readonly previousOrigin: Vec3;\n}\n\nexport interface SnapPositionResult {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly resolution: SnapResolution;\n}\n\n/**\n * Pure translation of PM_SnapPosition from rerelease `p_move.cpp`.\n * Attempts to keep the caller's origin in a valid location by first\n * checking the current origin against collision traces, then falling\n * back to the shared `fixStuckObjectGeneric` helper before finally\n * reverting to the provided previous origin when no fix is possible.\n */\nexport function snapPosition(params: SnapPositionParams): SnapPositionResult {\n const { origin, velocity, mins, maxs, previousOrigin, trace } = params;\n\n if (goodPosition({ origin, mins, maxs, trace })) {\n return { origin: { ...origin }, velocity: { ...velocity }, resolution: 'unchanged' };\n }\n\n const fix = fixStuckObjectGeneric({\n origin,\n mins,\n maxs,\n trace: (start, localMins, localMaxs, end) => trace(start, end, localMins, localMaxs),\n });\n\n if (fix.result === 'fixed' || fix.result === 'good-position') {\n return { origin: fix.origin, velocity: { ...velocity }, resolution: 'fixed' };\n }\n\n return { origin: { ...previousOrigin }, velocity: { ...velocity }, resolution: 'reverted' };\n}\n\nexport interface InitialSnapPositionParams extends GoodPositionParams {}\n\nexport interface InitialSnapPositionResult {\n readonly origin: Vec3;\n readonly snapped: boolean;\n}\n\n/**\n * Pure translation of PM_InitialSnapPosition from rerelease `p_move.cpp`.\n * Tries a 3x3x3 grid of +/-1 unit offsets around the base origin to find\n * a valid collision-free spot, mirroring the search order of the C++ code.\n */\nexport function initialSnapPosition(params: InitialSnapPositionParams): InitialSnapPositionResult {\n const { origin, mins, maxs, trace } = params;\n\n for (const oz of SNAP_OFFSETS) {\n for (const oy of SNAP_OFFSETS) {\n for (const ox of SNAP_OFFSETS) {\n const candidate = { x: origin.x + ox, y: origin.y + oy, z: origin.z + oz } satisfies Vec3;\n if (goodPosition({ origin: candidate, mins, maxs, trace })) {\n const snapped = ox !== 0 || oy !== 0 || oz !== 0;\n return { origin: candidate, snapped };\n }\n }\n }\n }\n\n return { origin: { ...origin }, snapped: false };\n}\n","import type { Vec3 } from '../math/vec3.js';\nimport { angleVectors, type AngleVectorsResult } from '../math/angles.js';\nimport { PmFlag, type PmFlags } from './constants.js';\n\nexport interface ClampViewAnglesParams {\n readonly pmFlags: PmFlags;\n readonly cmdAngles: Vec3;\n readonly deltaAngles: Vec3;\n}\n\nexport interface ClampViewAnglesResult extends AngleVectorsResult {\n readonly viewangles: Vec3;\n}\n\nfunction addAngles(cmdAngles: Vec3, deltaAngles: Vec3): Vec3 {\n return {\n x: cmdAngles.x + deltaAngles.x,\n y: cmdAngles.y + deltaAngles.y,\n z: cmdAngles.z + deltaAngles.z,\n } satisfies Vec3;\n}\n\nfunction clampPitch(pitch: number): number {\n if (pitch > 89 && pitch < 180) {\n return 89;\n }\n if (pitch < 271 && pitch >= 180) {\n return 271;\n }\n return pitch;\n}\n\n/**\n * Pure translation of `PM_ClampAngles` from `rerelease/p_move.cpp`. The helper\n * fuses the latest command angles with the stored delta, applies the teleport\n * pitch/roll reset, enforces the ±90° pitch window, and returns the resulting\n * axis vectors that the C version stored in `pml.forward/right/up`.\n */\nexport function clampViewAngles(params: ClampViewAnglesParams): ClampViewAnglesResult {\n const { pmFlags, cmdAngles, deltaAngles } = params;\n\n let viewangles: Vec3;\n\n if ((pmFlags & PmFlag.TimeTeleport) !== 0) {\n viewangles = {\n x: 0,\n y: cmdAngles.y + deltaAngles.y,\n z: 0,\n } satisfies Vec3;\n } else {\n viewangles = addAngles(cmdAngles, deltaAngles);\n viewangles = { ...viewangles, x: clampPitch(viewangles.x) };\n }\n\n const vectors = angleVectors(viewangles);\n return { viewangles, ...vectors };\n}\n"],"mappings":"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","names":["src_exports","__export","bootstrapViewer","createClient","imports","latestFrame","initial","next","origin","velocity","sample","DEFAULT_FIXED_DELTA_MS","DEFAULT_MAX_SUBSTEPS","defaultNow","defaultScheduler","tick","FixedTimestepLoop","callbacks","options","nowMs","elapsed","fixedDeltaMs","maxSubSteps","elapsedMs","clampedDelta","steps","alpha","EngineHost","game","client","step","renderContext","now","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_LIGHTSTYLES","MAX_SHADOW_LIGHTS","MAX_ITEMS","MAX_CLIENTS","MAX_GENERAL","MAX_WHEEL_ITEMS","MAX_CONFIGSTRINGS","EngineRuntime","engine","host","elapsedMs","createEngineRuntime","game","client","options","EngineHost","createCrcTable","table","i","crc","j","CRC_TABLE","FLOAT_BYTES","STRIDE","BSP_VERTEX_LAYOUT","createEngine","imports","callbacks","options","FixedTimestepLoop","ZERO_VEC3","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_CONFIGSTRINGS","ZERO","ZERO_VEC3","copyVec3","Entity","index","MAX_EDICTS","WORLD_INDEX","EntityPool","maxEntities","i","Entity","world","count","_","current","value","index","entity","ThinkScheduler","timeSeconds","a","b","currentTimeSeconds","next","time","computeBounds","boundsIntersect","EntitySystem","callback","nextThinkSeconds","activeEntities","first","firstBounds","j","second","secondBounds","orderedStageNames","GameFrameLoop","initialStages","stageName","handler","stage","handlers","startTimeMs","step","previousTimeMs","context","writeIndex","readIndex","ZERO_STATE","LevelClock","startSeconds","ZERO_VEC3","createGame","engine","options","gravity","levelClock","frameLoop","entities","deltaSeconds","velocity","origin","snapshot","frame","resetState","ZERO_VEC3","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","CONTENTS_SOLID","CONTENTS_WINDOW","CONTENTS_LAVA","CONTENTS_SLIME","CONTENTS_WATER","CONTENTS_PROJECTILECLIP","CONTENTS_PLAYERCLIP","CONTENTS_MONSTERCLIP","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","CONTENTS_ORIGIN","CONTENTS_MONSTER","CONTENTS_DEADMONSTER","CONTENTS_DETAIL","CONTENTS_TRANSLUCENT","CONTENTS_LADDER","CONTENTS_PLAYER","CONTENTS_PROJECTILE","SURF_ALPHATEST","SURF_N64_UV","SURF_N64_SCROLL_X","SURF_N64_SCROLL_Y","SURF_N64_SCROLL_FLIP","MASK_SOLID","CONTENTS_SOLID","CONTENTS_WINDOW","MASK_PLAYERSOLID","CONTENTS_PLAYERCLIP","CONTENTS_MONSTER","CONTENTS_PLAYER","MASK_DEADSOLID","MASK_MONSTERSOLID","CONTENTS_MONSTERCLIP","MASK_WATER","CONTENTS_WATER","CONTENTS_LAVA","CONTENTS_SLIME","MASK_OPAQUE","MASK_SHOT","CONTENTS_DEADMONSTER","MASK_CURRENT","CONTENTS_CURRENT_0","CONTENTS_CURRENT_90","CONTENTS_CURRENT_180","CONTENTS_CURRENT_270","CONTENTS_CURRENT_UP","CONTENTS_CURRENT_DOWN","MASK_BLOCK_SIGHT","MASK_NAV_SOLID","MASK_LADDER_NAV_SOLID","MASK_WALK_NAV_SOLID","MASK_PROJECTILE","CONTENTS_PROJECTILECLIP","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_CLIENTS","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_LIGHTSTYLES","MAX_SHADOW_LIGHTS","MAX_ITEMS","MAX_CLIENTS","MAX_GENERAL","MAX_WHEEL_ITEMS","MAX_CONFIGSTRINGS","bootstrapViewer","engine","createEngine","start","end","game","createGame","ZERO_VEC3","client","createClient","runtime","createEngineRuntime"]}