quake2ts 0.0.41 → 0.0.43
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.
- package/apps/viewer/dist/browser/index.global.js.map +1 -1
- package/apps/viewer/dist/cjs/index.cjs +8 -8
- package/apps/viewer/dist/cjs/index.cjs.map +1 -1
- package/apps/viewer/dist/esm/index.js +8 -8
- package/apps/viewer/dist/esm/index.js.map +1 -1
- package/apps/viewer/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
- package/packages/game/dist/browser/index.global.js +1 -1
- package/packages/game/dist/browser/index.global.js.map +1 -1
- package/packages/game/dist/cjs/index.cjs +192 -13
- package/packages/game/dist/cjs/index.cjs.map +1 -1
- package/packages/game/dist/esm/index.js +172 -13
- package/packages/game/dist/esm/index.js.map +1 -1
- package/packages/game/dist/tsconfig.tsbuildinfo +1 -1
- package/packages/game/dist/types/inventory/ammo.d.ts +32 -0
- package/packages/game/dist/types/inventory/ammo.d.ts.map +1 -1
- package/packages/game/dist/types/inventory/index.d.ts +1 -0
- package/packages/game/dist/types/inventory/index.d.ts.map +1 -1
- package/packages/game/dist/types/inventory/playerInventory.d.ts +56 -0
- package/packages/game/dist/types/inventory/playerInventory.d.ts.map +1 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../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/protocol/contracts.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/shared/src/protocol/usercmd.ts","../../../../packages/client/src/prediction.ts","../../../../packages/client/src/view-effects.ts","../../../../packages/client/src/input/bindings.ts","../../../../packages/client/src/input/controller.ts","../../../../packages/client/src/input/command-buffer.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/protocol/contracts.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/shared/src/protocol/usercmd.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/pakValidation.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/assets/md3.ts","../../../../packages/engine/src/assets/animation.ts","../../../../packages/engine/src/assets/wal.ts","../../../../packages/engine/src/assets/pcx.ts","../../../../packages/engine/src/assets/texture.ts","../../../../packages/engine/src/assets/wav.ts","../../../../packages/engine/src/assets/ogg.ts","../../../../packages/engine/src/assets/audio.ts","../../../../packages/engine/src/assets/pakIndexStore.ts","../../../../packages/engine/src/assets/manager.ts","../../../../packages/engine/src/audio/constants.ts","../../../../packages/engine/src/audio/context.ts","../../../../packages/engine/src/audio/registry.ts","../../../../packages/engine/src/audio/precache.ts","../../../../packages/engine/src/audio/channels.ts","../../../../packages/engine/src/audio/spatialization.ts","../../../../packages/engine/src/audio/system.ts","../../../../packages/engine/src/audio/music.ts","../../../../packages/engine/src/audio/api.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/render/culling.ts","../../../../packages/engine/src/render/bspTraversal.ts","../../../../packages/engine/src/render/bspPipeline.ts","../../../../packages/engine/src/render/skybox.ts","../../../../packages/engine/src/render/md2Pipeline.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/protocol/contracts.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/shared/src/protocol/usercmd.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/entities/utils.ts","../../../../packages/game/src/entities/triggers.ts","../../../../packages/game/src/entities/spawn.ts","../../../../packages/game/src/loop.ts","../../../../packages/game/src/level.ts","../../../../packages/game/src/ai/constants.ts","../../../../packages/game/src/ai/movement.ts","../../../../packages/game/src/ai/perception.ts","../../../../packages/game/src/checksum.ts","../../../../packages/game/src/save/save.ts","../../../../packages/game/src/save/rerelease.ts","../../../../packages/game/src/save/storage.ts","../../../../packages/game/src/combat/damageFlags.ts","../../../../packages/game/src/combat/armor.ts","../../../../packages/game/src/combat/damage.ts","../../../../packages/game/src/combat/damageMods.ts","../../../../packages/game/src/combat/specialDamage.ts","../../../../packages/game/src/inventory/ammo.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/protocol/contracts.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/shared/src/protocol/usercmd.ts"],"sourcesContent":["import { createClient } from '@quake2ts/client';\nimport { ClientRenderer, 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 as unknown as ClientRenderer);\n runtime.start();\n\n return { engine, game, client, runtime };\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n","import {\n addVec3,\n angleMod,\n scaleVec3,\n type Vec3,\n buildAirGroundWish,\n buildWaterWish,\n clampViewAngles,\n hasPmFlag,\n PmFlag,\n PmType,\n WaterLevel,\n type PmFlags,\n type UserCommand,\n} from '@quake2ts/shared';\nimport {\n applyPmoveAccelerate,\n applyPmoveAirAccelerate,\n applyPmoveFriction,\n} from '@quake2ts/shared';\nimport type { GameFrameResult } from '@quake2ts/engine';\n\nexport interface PredictionState {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly viewangles: Vec3;\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly waterlevel: WaterLevel;\n readonly gravity: number;\n readonly deltaAngles?: Vec3;\n}\n\nexport interface PredictionSettings {\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterFriction: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterSpeed: number;\n readonly groundIsSlick: boolean;\n}\n\nconst DEFAULTS: PredictionSettings = {\n pmFriction: 6,\n pmStopSpeed: 100,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmWaterAccelerate: 4,\n pmWaterFriction: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterSpeed: 400,\n groundIsSlick: false,\n};\n\nconst DEFAULT_GRAVITY = 800;\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\nconst MSEC_MAX = 250;\n\nexport function defaultPredictionState(): PredictionState {\n return {\n origin: ZERO_VEC3,\n velocity: ZERO_VEC3,\n viewangles: ZERO_VEC3,\n pmFlags: PmFlag.OnGround,\n pmType: PmType.Normal,\n waterlevel: WaterLevel.None,\n gravity: DEFAULT_GRAVITY,\n deltaAngles: ZERO_VEC3,\n } satisfies PredictionState;\n}\n\nfunction normalizeState(state: PredictionState | undefined): PredictionState {\n if (!state) return defaultPredictionState();\n\n return {\n ...defaultPredictionState(),\n ...state,\n origin: { ...state.origin },\n velocity: { ...state.velocity },\n viewangles: { ...state.viewangles },\n deltaAngles: state.deltaAngles ? { ...state.deltaAngles } : ZERO_VEC3,\n } satisfies PredictionState;\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpAngle(a: number, b: number, t: number): number {\n let delta = angleMod(b - a);\n if (delta > 180) {\n delta -= 360;\n }\n return angleMod(a + delta * t);\n}\n\nexport function interpolatePredictionState(\n previous: PredictionState,\n latest: PredictionState,\n alpha: number,\n): PredictionState {\n const clamped = Math.max(0, Math.min(alpha, 1));\n return {\n origin: {\n x: lerp(previous.origin.x, latest.origin.x, clamped),\n y: lerp(previous.origin.y, latest.origin.y, clamped),\n z: lerp(previous.origin.z, latest.origin.z, clamped),\n },\n velocity: {\n x: lerp(previous.velocity.x, latest.velocity.x, clamped),\n y: lerp(previous.velocity.y, latest.velocity.y, clamped),\n z: lerp(previous.velocity.z, latest.velocity.z, clamped),\n },\n viewangles: {\n x: lerpAngle(previous.viewangles.x, latest.viewangles.x, clamped),\n y: lerpAngle(previous.viewangles.y, latest.viewangles.y, clamped),\n z: lerpAngle(previous.viewangles.z, latest.viewangles.z, clamped),\n },\n pmFlags: latest.pmFlags,\n pmType: latest.pmType,\n waterlevel: latest.waterlevel,\n gravity: latest.gravity,\n deltaAngles: latest.deltaAngles,\n } satisfies PredictionState;\n}\n\nfunction simulateCommand(\n state: PredictionState,\n cmd: UserCommand,\n settings: PredictionSettings,\n): PredictionState {\n const frametime = Math.min(Math.max(cmd.msec, 0), MSEC_MAX) / 1000;\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n const onLadder = hasPmFlag(state.pmFlags, PmFlag.OnLadder);\n\n let velocity = applyPmoveFriction({\n velocity: state.velocity,\n frametime,\n onGround,\n groundIsSlick: settings.groundIsSlick,\n onLadder,\n waterlevel: state.waterlevel,\n pmFriction: settings.pmFriction,\n pmStopSpeed: settings.pmStopSpeed,\n pmWaterFriction: settings.pmWaterFriction,\n });\n\n const { viewangles, forward, right } = clampViewAngles({\n pmFlags: state.pmFlags,\n cmdAngles: cmd.angles,\n deltaAngles: state.deltaAngles ?? ZERO_VEC3,\n });\n\n const wish =\n state.waterlevel > WaterLevel.None\n ? buildWaterWish({ forward, right, cmd, maxSpeed: settings.pmWaterSpeed })\n : buildAirGroundWish({ forward, right, cmd, maxSpeed: settings.pmMaxSpeed });\n\n if (state.waterlevel > WaterLevel.None) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmWaterAccelerate,\n frametime,\n });\n } else if (onGround || onLadder) {\n const maxSpeed = hasPmFlag(state.pmFlags, PmFlag.Ducked) ? settings.pmDuckSpeed : settings.pmMaxSpeed;\n const clampedWish =\n wish.wishspeed > maxSpeed\n ? {\n wishdir: wish.wishdir,\n wishspeed: maxSpeed,\n }\n : wish;\n\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: clampedWish.wishdir,\n wishspeed: clampedWish.wishspeed,\n accel: settings.pmAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmAirAccelerate,\n frametime,\n });\n velocity = { ...velocity, z: velocity.z - state.gravity * frametime };\n }\n\n const originDelta = scaleVec3(velocity, frametime);\n const origin = addVec3(state.origin, originDelta);\n\n return {\n ...state,\n origin,\n velocity,\n viewangles,\n } satisfies PredictionState;\n}\n\nexport class ClientPrediction {\n private readonly settings: PredictionSettings;\n private baseFrame: GameFrameResult<PredictionState> = {\n frame: 0,\n timeMs: 0,\n state: defaultPredictionState(),\n } satisfies GameFrameResult<PredictionState>;\n private commands: UserCommand[] = [];\n private predicted: PredictionState = defaultPredictionState();\n\n constructor(settings: Partial<PredictionSettings> = {}) {\n this.settings = { ...DEFAULTS, ...settings } satisfies PredictionSettings;\n this.predicted = this.baseFrame.state ?? defaultPredictionState();\n }\n\n setAuthoritative(frame: GameFrameResult<PredictionState>): PredictionState {\n const normalized = normalizeState(frame.state);\n this.baseFrame = { ...frame, state: normalized };\n this.commands = this.commands.filter((cmd) => (cmd.serverFrame ?? Number.MAX_SAFE_INTEGER) > frame.frame);\n return this.recompute();\n }\n\n enqueueCommand(cmd: UserCommand): PredictionState {\n this.commands.push(cmd);\n return this.recompute();\n }\n\n getPredictedState(): PredictionState {\n return this.predicted;\n }\n\n private recompute(): PredictionState {\n let state = normalizeState(this.baseFrame.state);\n\n for (const cmd of this.commands) {\n state = simulateCommand(state, cmd, this.settings);\n }\n\n this.predicted = state;\n return state;\n }\n}\n","import { ZERO_VEC3, angleVectors, clampViewAngles, dotVec3, hasPmFlag, PmFlag, type PmFlags, type Vec3 } from '@quake2ts/shared';\nimport type { PredictionState } from './prediction.js';\n\nexport interface ViewEffectSettings {\n readonly runPitch: number;\n readonly runRoll: number;\n readonly bobUp: number;\n readonly bobPitch: number;\n readonly bobRoll: number;\n readonly maxBobHeight: number;\n readonly maxBobAngle: number;\n}\n\nconst DEFAULT_SETTINGS: ViewEffectSettings = {\n runPitch: 0.002,\n runRoll: 0.005,\n bobUp: 0.005,\n bobPitch: 0.002,\n bobRoll: 0.002,\n maxBobHeight: 6,\n maxBobAngle: 1.2,\n};\n\nexport interface ViewKick {\n readonly pitch: number;\n readonly roll: number;\n readonly durationMs: number;\n}\n\nexport interface ActiveKick extends ViewKick {\n remainingMs: number;\n}\n\nexport interface ViewSample {\n readonly angles: Vec3;\n readonly offset: Vec3;\n readonly bobCycle: number;\n readonly bobCycleRun: number;\n readonly bobFracSin: number;\n readonly xyspeed: number;\n}\n\nfunction clampViewOffset(offset: Vec3): Vec3 {\n return {\n x: Math.max(-14, Math.min(14, offset.x)),\n y: Math.max(-14, Math.min(14, offset.y)),\n z: Math.max(-22, Math.min(30, offset.z)),\n };\n}\n\nfunction computeBobMove(xyspeed: number, onGround: boolean, frameTimeMs: number): number {\n if (!onGround) return 0;\n\n if (xyspeed > 210) return frameTimeMs / 400;\n if (xyspeed > 100) return frameTimeMs / 800;\n return frameTimeMs / 1600;\n}\n\nfunction computeBobValues(\n previousBobTime: number,\n xyspeed: number,\n pmFlags: PmFlags,\n onGround: boolean,\n frameTimeMs: number,\n): { bobTime: number; bobCycle: number; bobCycleRun: number; bobFracSin: number } {\n if (xyspeed < 5) {\n return { bobTime: 0, bobCycle: 0, bobCycleRun: 0, bobFracSin: 0 };\n }\n\n const bobMove = computeBobMove(xyspeed, onGround, frameTimeMs);\n const bobTimeRun = previousBobTime + bobMove;\n const crouched = hasPmFlag(pmFlags, PmFlag.Ducked) && onGround;\n const bobTime = crouched ? bobTimeRun * 4 : bobTimeRun;\n\n return {\n bobTime: bobTimeRun,\n bobCycle: Math.floor(bobTime),\n bobCycleRun: Math.floor(bobTimeRun),\n bobFracSin: Math.abs(Math.sin(bobTime * Math.PI)),\n };\n}\n\nexport class ViewEffects {\n private readonly settings: ViewEffectSettings;\n private bobTime = 0;\n private bobCycle = 0;\n private bobCycleRun = 0;\n private bobFracSin = 0;\n private kick: ActiveKick | undefined;\n private lastSample: ViewSample | undefined;\n\n constructor(settings: Partial<ViewEffectSettings> = {}) {\n this.settings = { ...DEFAULT_SETTINGS, ...settings } satisfies ViewEffectSettings;\n }\n\n addKick(kick: ViewKick): void {\n if (kick.durationMs <= 0) return;\n this.kick = { ...kick, remainingMs: kick.durationMs } satisfies ActiveKick;\n }\n\n get last(): ViewSample | undefined {\n return this.lastSample;\n }\n\n sample(state: PredictionState, frameTimeMs: number): ViewSample {\n const { forward, right } = angleVectors(\n clampViewAngles({ pmFlags: state.pmFlags, cmdAngles: state.viewangles, deltaAngles: state.deltaAngles ?? ZERO_VEC3 }).viewangles,\n );\n\n const xyspeed = Math.sqrt(state.velocity.x * state.velocity.x + state.velocity.y * state.velocity.y);\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n\n const bobValues = computeBobValues(this.bobTime, xyspeed, state.pmFlags, onGround, frameTimeMs);\n this.bobTime = bobValues.bobTime;\n this.bobCycle = bobValues.bobCycle;\n this.bobCycleRun = bobValues.bobCycleRun;\n this.bobFracSin = bobValues.bobFracSin;\n\n // Velocity-based tilt\n let pitchTilt = dotVec3(state.velocity, forward) * this.settings.runPitch;\n let rollTilt = dotVec3(state.velocity, right) * this.settings.runRoll;\n\n // Bob tilt\n let pitchDelta = this.bobFracSin * this.settings.bobPitch * xyspeed;\n let rollDelta = this.bobFracSin * this.settings.bobRoll * xyspeed;\n if (hasPmFlag(state.pmFlags, PmFlag.Ducked) && onGround) {\n pitchDelta *= 6;\n rollDelta *= 6;\n }\n\n pitchTilt += Math.min(pitchDelta, this.settings.maxBobAngle);\n rollDelta = Math.min(rollDelta, this.settings.maxBobAngle);\n if (this.bobCycle & 1) rollDelta = -rollDelta;\n rollTilt += rollDelta;\n\n // Bob height\n const bobHeight = Math.min(this.bobFracSin * xyspeed * this.settings.bobUp, this.settings.maxBobHeight);\n\n let kickPitch = 0;\n let kickRoll = 0;\n\n // Apply active kick\n if (this.kick && this.kick.remainingMs > 0) {\n const ratio = Math.max(0, Math.min(1, this.kick.remainingMs / this.kick.durationMs));\n kickPitch += ratio * this.kick.pitch;\n kickRoll += ratio * this.kick.roll;\n this.kick.remainingMs = Math.max(0, this.kick.remainingMs - frameTimeMs);\n if (this.kick.remainingMs === 0) this.kick = undefined;\n }\n\n const angles: Vec3 = { x: pitchTilt + kickPitch, y: 0, z: rollTilt + kickRoll };\n const offset: Vec3 = { x: 0, y: 0, z: bobHeight };\n\n const sample: ViewSample = {\n angles,\n offset: clampViewOffset(offset),\n bobCycle: this.bobCycle,\n bobCycleRun: this.bobCycleRun,\n bobFracSin: this.bobFracSin,\n xyspeed,\n } satisfies ViewSample;\n this.lastSample = sample;\n return sample;\n }\n}\n","export type InputCode = string;\n\nexport interface BindingEntry {\n readonly code: InputCode;\n readonly command: string;\n}\n\nconst DEFAULT_BINDINGS: readonly BindingEntry[] = [\n { code: 'KeyW', command: '+forward' },\n { code: 'ArrowUp', command: '+forward' },\n { code: 'KeyS', command: '+back' },\n { code: 'ArrowDown', command: '+back' },\n { code: 'KeyA', command: '+moveleft' },\n { code: 'KeyD', command: '+moveright' },\n { code: 'Space', command: '+jump' },\n { code: 'ControlLeft', command: '+crouch' },\n { code: 'ShiftLeft', command: '+speed' },\n { code: 'Mouse1', command: '+attack' },\n { code: 'Mouse2', command: '+use' },\n { code: 'Mouse3', command: '+zoom' },\n { code: 'ArrowLeft', command: '+left' },\n { code: 'ArrowRight', command: '+right' },\n { code: 'PageUp', command: '+lookup' },\n { code: 'PageDown', command: '+lookdown' },\n { code: 'Gamepad0-Button7', command: '+attack' },\n { code: 'Gamepad0-Button6', command: '+zoom' },\n { code: 'Gamepad0-Button0', command: '+jump' },\n { code: 'Gamepad0-Button1', command: '+crouch' },\n { code: 'Gamepad0-Button2', command: '+use' },\n { code: 'Gamepad0-Button4', command: 'prevweapon' },\n { code: 'Gamepad0-Button5', command: 'nextweapon' },\n { code: 'Digit1', command: 'weapon 1' },\n { code: 'Digit2', command: 'weapon 2' },\n { code: 'Digit3', command: 'weapon 3' },\n { code: 'Digit4', command: 'weapon 4' },\n { code: 'Digit5', command: 'weapon 5' },\n { code: 'Digit6', command: 'weapon 6' },\n { code: 'Digit7', command: 'weapon 7' },\n { code: 'Digit8', command: 'weapon 8' },\n { code: 'Digit9', command: 'weapon 9' },\n { code: 'Digit0', command: 'weapon 10' },\n];\n\nexport type BindingMap = ReadonlyMap<InputCode, string>;\n\nexport class InputBindings {\n private readonly bindings = new Map<InputCode, string>();\n\n constructor(entries: Iterable<BindingEntry> = DEFAULT_BINDINGS) {\n for (const entry of entries) {\n this.bind(entry.code, entry.command);\n }\n }\n\n bind(code: InputCode, command: string): void {\n this.bindings.set(code, command);\n }\n\n unbind(code: InputCode): void {\n this.bindings.delete(code);\n }\n\n getBinding(code: InputCode): string | undefined {\n return this.bindings.get(code);\n }\n\n entries(): BindingMap {\n return new Map(this.bindings.entries());\n }\n}\n\nexport function createDefaultBindings(): InputBindings {\n return new InputBindings();\n}\n\nexport function normalizeInputCode(code: string): InputCode {\n return code;\n}\n\nexport function normalizeCommand(command: string): string {\n return command.trim().toLowerCase();\n}\n\n","import {\n DEFAULT_FORWARD_SPEED,\n DEFAULT_MOUSE_SENSITIVITY,\n DEFAULT_PITCH_SPEED,\n DEFAULT_SIDE_SPEED,\n DEFAULT_UP_SPEED,\n DEFAULT_YAW_SPEED,\n PlayerButton,\n addViewAngles,\n mouseDeltaToViewDelta,\n type MouseDelta,\n type UserCommand,\n type Vec3,\n} from '@quake2ts/shared';\nimport { InputBindings, normalizeCommand, normalizeInputCode, type InputCode } from './bindings.js';\n\nconst MSEC_MAX = 250;\n\nexport interface GamepadLikeButton {\n readonly pressed: boolean;\n readonly value: number;\n}\n\nexport interface GamepadLike {\n readonly axes: readonly number[];\n readonly buttons: readonly GamepadLikeButton[];\n readonly index?: number;\n readonly connected?: boolean;\n}\n\ninterface ButtonState {\n readonly active: boolean;\n readonly wasPressed: boolean;\n readonly fraction: number;\n}\n\nexport interface TouchInputState {\n readonly move?: { readonly x: number; readonly y: number };\n readonly look?: { readonly x: number; readonly y: number };\n readonly buttons?: Partial<Record<InputAction, boolean>>;\n}\n\nclass KeyButton {\n private readonly activeCodes = new Set<InputCode>();\n private downTime = 0;\n private msec = 0;\n private pressed = false;\n\n press(code: InputCode, now: number): boolean {\n if (this.activeCodes.has(code)) return false;\n\n this.activeCodes.add(code);\n this.pressed = true;\n if (this.activeCodes.size === 1) {\n this.downTime = now;\n return true;\n }\n\n return false;\n }\n\n release(code: InputCode, now: number): boolean {\n if (!this.activeCodes.delete(code)) return false;\n\n if (this.activeCodes.size === 0) {\n this.msec += now - this.downTime;\n this.downTime = 0;\n return true;\n }\n\n return false;\n }\n\n sample(frameMsec: number, now: number): ButtonState {\n if (frameMsec <= 0) {\n return { active: this.activeCodes.size > 0, wasPressed: this.pressed, fraction: 0 };\n }\n\n let total = this.msec;\n\n if (this.activeCodes.size > 0) {\n total += now - this.downTime;\n this.downTime = now;\n }\n\n this.msec = 0;\n\n const fraction = Math.min(total / frameMsec, 1);\n const wasPressed = this.pressed;\n this.pressed = false;\n\n return { active: this.activeCodes.size > 0, wasPressed, fraction };\n }\n}\n\nexport interface InputControllerOptions {\n readonly forwardSpeed?: number;\n readonly sideSpeed?: number;\n readonly upSpeed?: number;\n readonly yawSpeed?: number;\n readonly pitchSpeed?: number;\n readonly sensitivity?: number;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n readonly invertMouseY?: boolean;\n readonly runByDefault?: boolean;\n readonly requirePointerLock?: boolean;\n readonly jumpAddsUpMove?: boolean;\n readonly crouchAddsDownMove?: boolean;\n readonly mouseFilter?: boolean;\n readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n readonly gamepadDeadZone?: number;\n readonly gamepadLookScale?: number;\n readonly invertGamepadY?: boolean;\n}\n\nexport enum InputAction {\n Forward = '+forward',\n Back = '+back',\n MoveLeft = '+moveleft',\n MoveRight = '+moveright',\n MoveUp = '+moveup',\n MoveDown = '+movedown',\n Jump = '+jump',\n Crouch = '+crouch',\n Attack = '+attack',\n Use = '+use',\n Holster = '+holster',\n TurnLeft = '+left',\n TurnRight = '+right',\n LookUp = '+lookup',\n LookDown = '+lookdown',\n SpeedModifier = '+speed',\n Zoom = '+zoom',\n}\n\nconst BUTTON_ACTIONS: Partial<Record<InputAction, PlayerButton>> = {\n [InputAction.Attack]: PlayerButton.Attack,\n [InputAction.Use]: PlayerButton.Use,\n [InputAction.Holster]: PlayerButton.Holster,\n [InputAction.Jump]: PlayerButton.Jump,\n [InputAction.Crouch]: PlayerButton.Crouch,\n};\n\nconst ACTION_LOOKUP = new Map<string, InputAction>(\n Object.values(InputAction).map((action) => [normalizeCommand(action), action]),\n);\n\nfunction commandToAction(command: string): InputAction | undefined {\n return ACTION_LOOKUP.get(normalizeCommand(command));\n}\n\nfunction nowMs(): number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now();\n }\n\n return Date.now();\n}\n\nexport class InputController {\n private readonly bindings: InputBindings;\n private readonly buttons = new Map<InputAction, KeyButton>();\n private viewAngles: Vec3 = { x: 0, y: 0, z: 0 };\n private pointerLocked = false;\n private mouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private previousMouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private anyPressed = false;\n private commandQueue: string[] = [];\n private pendingGamepads: readonly (GamepadLike | null | undefined)[] | undefined;\n private readonly gamepadButtons = new Map<string, boolean>();\n private gamepadMove = { x: 0, y: 0 };\n private gamepadLook = { x: 0, y: 0 };\n private pendingTouchState: TouchInputState | undefined;\n private readonly touchButtons = new Map<InputAction, boolean>();\n private touchMove = { x: 0, y: 0 };\n private touchLook = { x: 0, y: 0 };\n\n private readonly forwardSpeed: number;\n private readonly sideSpeed: number;\n private readonly upSpeed: number;\n private readonly yawSpeed: number;\n private readonly pitchSpeed: number;\n private readonly sensitivity: number;\n private readonly sensitivityX?: number;\n private readonly sensitivityY?: number;\n private readonly invertMouseY: boolean;\n private readonly runByDefault: boolean;\n private readonly requirePointerLock: boolean;\n private readonly jumpAddsUpMove: boolean;\n private readonly crouchAddsDownMove: boolean;\n private readonly mouseFilter: boolean;\n private readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n private readonly gamepadDeadZone: number;\n private readonly gamepadLookScale: number;\n private readonly invertGamepadY: boolean;\n\n constructor(options: InputControllerOptions = {}, bindings = new InputBindings()) {\n this.bindings = bindings;\n this.forwardSpeed = options.forwardSpeed ?? DEFAULT_FORWARD_SPEED;\n this.sideSpeed = options.sideSpeed ?? DEFAULT_SIDE_SPEED;\n this.upSpeed = options.upSpeed ?? DEFAULT_UP_SPEED;\n this.yawSpeed = options.yawSpeed ?? DEFAULT_YAW_SPEED;\n this.pitchSpeed = options.pitchSpeed ?? DEFAULT_PITCH_SPEED;\n this.sensitivity = options.sensitivity ?? DEFAULT_MOUSE_SENSITIVITY;\n this.sensitivityX = options.sensitivityX;\n this.sensitivityY = options.sensitivityY;\n this.invertMouseY = options.invertMouseY ?? false;\n this.runByDefault = options.runByDefault ?? true;\n this.requirePointerLock = options.requirePointerLock ?? true;\n this.jumpAddsUpMove = options.jumpAddsUpMove ?? true;\n this.crouchAddsDownMove = options.crouchAddsDownMove ?? true;\n this.mouseFilter = options.mouseFilter ?? false;\n this.getGamepads = options.getGamepads;\n this.gamepadDeadZone = options.gamepadDeadZone ?? 0.15;\n this.gamepadLookScale = options.gamepadLookScale ?? 1;\n this.invertGamepadY = options.invertGamepadY ?? this.invertMouseY;\n }\n\n handleKeyDown(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, true, normalized, eventTimeMs);\n }\n\n handleKeyUp(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, false, normalized, eventTimeMs);\n }\n\n handleMouseButtonDown(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), true, code, eventTimeMs);\n }\n\n handleMouseButtonUp(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), false, code, eventTimeMs);\n }\n\n handleMouseMove(deltaX: number, deltaY: number): void {\n if (this.requirePointerLock && !this.pointerLocked) return;\n\n this.mouseDelta = {\n deltaX: this.mouseDelta.deltaX + deltaX,\n deltaY: this.mouseDelta.deltaY + deltaY,\n };\n }\n\n setPointerLocked(locked: boolean): void {\n this.pointerLocked = locked;\n }\n\n setGamepadState(gamepads: readonly (GamepadLike | null | undefined)[]): void {\n this.pendingGamepads = gamepads;\n }\n\n setTouchState(state: TouchInputState): void {\n this.pendingTouchState = state;\n }\n\n buildCommand(frameMsec: number, now: number = nowMs(), serverFrame?: number): UserCommand {\n this.pollGamepads(now);\n this.applyTouchState(now);\n\n const yawStep = (this.yawSpeed * frameMsec) / 1000;\n const pitchStep = (this.pitchSpeed * frameMsec) / 1000;\n\n const turnLeft = this.sample(InputAction.TurnLeft, frameMsec, now);\n const turnRight = this.sample(InputAction.TurnRight, frameMsec, now);\n const lookUp = this.sample(InputAction.LookUp, frameMsec, now);\n const lookDown = this.sample(InputAction.LookDown, frameMsec, now);\n\n let viewDelta: Vec3 = {\n x: (lookDown.fraction - lookUp.fraction) * pitchStep,\n y: (turnRight.fraction - turnLeft.fraction) * yawStep,\n z: 0,\n };\n\n if (this.gamepadLook.x !== 0 || this.gamepadLook.y !== 0) {\n const pitch = this.gamepadLook.y * (this.invertGamepadY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep * this.gamepadLookScale,\n y: viewDelta.y + this.gamepadLook.x * yawStep * this.gamepadLookScale,\n z: 0,\n };\n }\n\n if (this.touchLook.x !== 0 || this.touchLook.y !== 0) {\n const pitch = this.touchLook.y * (this.invertMouseY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep,\n y: viewDelta.y + this.touchLook.x * yawStep,\n z: 0,\n };\n }\n\n if (this.pointerLocked || !this.requirePointerLock) {\n const sampledDelta = this.sampleMouseDelta();\n const mouseDelta = mouseDeltaToViewDelta(sampledDelta, {\n sensitivity: this.sensitivity,\n sensitivityX: this.sensitivityX,\n sensitivityY: this.sensitivityY,\n invertY: this.invertMouseY,\n });\n viewDelta = {\n x: viewDelta.x + mouseDelta.x,\n y: viewDelta.y + mouseDelta.y,\n z: 0,\n };\n }\n\n const angles = addViewAngles(this.viewAngles, viewDelta);\n this.viewAngles = angles;\n\n const forward = this.sample(InputAction.Forward, frameMsec, now);\n const back = this.sample(InputAction.Back, frameMsec, now);\n const moveLeft = this.sample(InputAction.MoveLeft, frameMsec, now);\n const moveRight = this.sample(InputAction.MoveRight, frameMsec, now);\n const moveUp = this.sample(InputAction.MoveUp, frameMsec, now);\n const moveDown = this.sample(InputAction.MoveDown, frameMsec, now);\n const speed = this.sample(InputAction.SpeedModifier, frameMsec, now);\n const jump = this.sample(InputAction.Jump, frameMsec, now);\n const crouch = this.sample(InputAction.Crouch, frameMsec, now);\n\n const speedScale = this.runByDefault\n ? speed.active\n ? 0.5\n : 1\n : speed.active\n ? 1\n : 0.5;\n\n let forwardmove = this.forwardSpeed * (forward.fraction - back.fraction) * speedScale;\n let sidemove = this.sideSpeed * (moveRight.fraction - moveLeft.fraction) * speedScale;\n let upmove = this.upSpeed * (moveUp.fraction - moveDown.fraction);\n\n if (this.gamepadMove.x !== 0 || this.gamepadMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.gamepadMove.y * speedScale;\n sidemove += this.sideSpeed * this.gamepadMove.x * speedScale;\n }\n\n if (this.touchMove.x !== 0 || this.touchMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.touchMove.y * speedScale;\n sidemove += this.sideSpeed * this.touchMove.x * speedScale;\n }\n\n if (this.jumpAddsUpMove && jump.fraction > 0) {\n upmove += this.upSpeed * jump.fraction;\n }\n\n if (this.crouchAddsDownMove && crouch.fraction > 0) {\n upmove -= this.upSpeed * crouch.fraction;\n }\n\n forwardmove = this.clampMove(forwardmove, this.forwardSpeed);\n sidemove = this.clampMove(sidemove, this.sideSpeed);\n upmove = this.clampMove(upmove, this.upSpeed);\n\n let buttons = this.collectButtonBits(frameMsec, now);\n\n const msec = Math.min(Math.max(Math.round(frameMsec), 1), MSEC_MAX);\n\n if (this.anyPressed || buttons !== PlayerButton.None) {\n buttons |= PlayerButton.Any;\n }\n\n this.anyPressed = false;\n\n return {\n msec,\n buttons,\n angles: { ...this.viewAngles },\n forwardmove,\n sidemove,\n upmove,\n serverFrame,\n } satisfies UserCommand;\n }\n\n consumeConsoleCommands(): readonly string[] {\n const commands = this.commandQueue;\n this.commandQueue = [];\n return commands;\n }\n\n private pollGamepads(now: number): void {\n const gamepads = this.getGamepads?.() ?? this.pendingGamepads ?? [];\n this.pendingGamepads = undefined;\n\n this.gamepadMove = { x: 0, y: 0 };\n this.gamepadLook = { x: 0, y: 0 };\n\n const pressedThisFrame = new Set<InputCode>();\n\n for (const pad of gamepads) {\n if (!pad || pad.connected === false) continue;\n\n const index = pad.index ?? 0;\n const axes = pad.axes ?? [];\n\n this.gamepadMove = {\n x: this.mergeAnalog(this.gamepadMove.x, this.applyDeadZone(axes[0] ?? 0)),\n y: this.mergeAnalog(this.gamepadMove.y, -this.applyDeadZone(axes[1] ?? 0)),\n };\n\n this.gamepadLook = {\n x: this.mergeAnalog(this.gamepadLook.x, this.applyDeadZone(axes[2] ?? 0)),\n y: this.mergeAnalog(this.gamepadLook.y, this.applyDeadZone(axes[3] ?? 0)),\n };\n\n const buttons = pad.buttons ?? [];\n for (let i = 0; i < buttons.length; i++) {\n const button = buttons[i];\n if (!button) continue;\n\n const pressed = button.pressed || button.value > this.gamepadDeadZone;\n const code = this.gamepadButtonCode(index, i);\n if (pressed) pressedThisFrame.add(code);\n\n const wasPressed = this.gamepadButtons.get(code) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(this.bindings.getBinding(code), pressed, code, now);\n this.gamepadButtons.set(code, pressed);\n }\n }\n }\n\n for (const [code, wasPressed] of this.gamepadButtons.entries()) {\n if (wasPressed && !pressedThisFrame.has(code)) {\n this.applyCommand(this.bindings.getBinding(code), false, code, now);\n this.gamepadButtons.set(code, false);\n }\n }\n }\n\n private applyTouchState(now: number): void {\n const state = this.pendingTouchState;\n if (!state) return;\n\n this.pendingTouchState = undefined;\n\n if (state.move) {\n this.touchMove = {\n x: this.clampAnalog(state.move.x),\n y: this.clampAnalog(state.move.y),\n };\n }\n\n if (state.look) {\n this.touchLook = {\n x: this.clampAnalog(state.look.x),\n y: this.clampAnalog(state.look.y),\n };\n }\n\n if (state.buttons) {\n for (const [action, pressed] of Object.entries(state.buttons) as Array<\n [InputAction, boolean | undefined]\n >) {\n if (pressed === undefined) continue;\n\n const wasPressed = this.touchButtons.get(action) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(action, pressed, this.touchButtonCode(action), now);\n this.touchButtons.set(action, pressed);\n }\n }\n }\n }\n\n private applyCommand(\n command: string | undefined,\n isDown: boolean,\n code: InputCode,\n eventTimeMs: number,\n ): void {\n if (!command) return;\n\n const action = commandToAction(command);\n if (action) {\n const button = this.lookupButton(action);\n if (isDown) {\n if (button.press(code, eventTimeMs)) {\n this.commandQueue.push(action);\n }\n this.anyPressed = true;\n } else if (button.release(code, eventTimeMs)) {\n this.commandQueue.push(action.replace('+', '-'));\n }\n } else if (isDown) {\n this.commandQueue.push(command);\n }\n }\n\n private sampleMouseDelta(): MouseDelta {\n const delta = this.mouseDelta;\n this.mouseDelta = { deltaX: 0, deltaY: 0 };\n\n if (!this.mouseFilter) {\n this.previousMouseDelta = delta;\n return delta;\n }\n\n const filtered = {\n deltaX: (delta.deltaX + this.previousMouseDelta.deltaX) * 0.5,\n deltaY: (delta.deltaY + this.previousMouseDelta.deltaY) * 0.5,\n } satisfies MouseDelta;\n\n this.previousMouseDelta = delta;\n return filtered;\n }\n\n private collectButtonBits(frameMsec: number, now: number): PlayerButton {\n let buttons = PlayerButton.None;\n\n for (const [action, bit] of Object.entries(BUTTON_ACTIONS) as Array<\n [InputAction, PlayerButton]\n >) {\n const sample = this.sample(action, frameMsec, now);\n if (sample.fraction > 0 || sample.active || sample.wasPressed) {\n buttons |= bit;\n }\n }\n\n return buttons;\n }\n\n private lookupButton(action: InputAction): KeyButton {\n let button = this.buttons.get(action);\n if (!button) {\n button = new KeyButton();\n this.buttons.set(action, button);\n }\n return button;\n }\n\n private mouseButtonToCode(button: number): InputCode {\n if (button === 0) return 'Mouse1';\n if (button === 1) return 'Mouse3';\n if (button === 2) return 'Mouse2';\n return `Mouse${button + 1}`;\n }\n\n private mouseButtonToCommand(code: InputCode): string | undefined {\n return this.bindings.getBinding(code);\n }\n\n private sample(action: InputAction, frameMsec: number, now: number): ButtonState {\n const button = this.lookupButton(action);\n return button.sample(frameMsec, now);\n }\n\n private gamepadButtonCode(index: number, button: number): InputCode {\n return `Gamepad${index}-Button${button}`;\n }\n\n private touchButtonCode(action: InputAction): InputCode {\n return `Touch-${action}`;\n }\n\n private clampAnalog(value: number): number {\n return Math.max(-1, Math.min(1, value));\n }\n\n private applyDeadZone(value: number): number {\n return Math.abs(value) < this.gamepadDeadZone ? 0 : value;\n }\n\n private mergeAnalog(current: number, incoming: number): number {\n return Math.abs(incoming) > Math.abs(current) ? incoming : current;\n }\n\n private clampMove(value: number, max: number): number {\n return Math.max(-max, Math.min(max, value));\n }\n}\n\n","import type { UserCommand } from '@quake2ts/shared';\nimport { InputController, type InputControllerOptions } from './controller.js';\n\nexport interface QueuedFrameCommands {\n readonly command: UserCommand;\n readonly console: readonly string[];\n}\n\nexport class InputCommandBuffer {\n private readonly controller: InputController;\n private readonly queued: QueuedFrameCommands[] = [];\n\n constructor(options?: InputControllerOptions, controller = new InputController(options)) {\n this.controller = controller;\n }\n\n captureFrame(frameMsec: number, now?: number, serverFrame?: number): QueuedFrameCommands {\n const command = this.controller.buildCommand(frameMsec, now, serverFrame);\n const console = this.controller.consumeConsoleCommands();\n const entry: QueuedFrameCommands = { command, console };\n this.queued.push(entry);\n return entry;\n }\n\n consumeQueued(): readonly QueuedFrameCommands[] {\n const queued = [...this.queued];\n this.queued.length = 0;\n return queued;\n }\n\n getController(): InputController {\n return this.controller;\n }\n}\n","import type {\n ClientRenderer,\n EngineImports,\n GameFrameResult,\n GameRenderSample,\n} from '@quake2ts/engine';\nimport type { UserCommand } from '@quake2ts/shared';\nimport { ClientPrediction, interpolatePredictionState } from './prediction.js';\nimport type { PredictionState } from './prediction.js';\nimport { ViewEffects, type ViewSample } from './view-effects.js';\nexport { createDefaultBindings, InputBindings, normalizeCommand, normalizeInputCode } from './input/bindings.js';\nexport {\n GamepadLike,\n GamepadLikeButton,\n InputAction,\n InputController,\n TouchInputState,\n type InputControllerOptions,\n} from './input/controller.js';\nexport {\n InputCommandBuffer,\n type QueuedFrameCommands,\n} from './input/command-buffer.js';\nexport {\n ClientPrediction,\n defaultPredictionState,\n interpolatePredictionState,\n type PredictionSettings,\n type PredictionState,\n} from './prediction.js';\nexport { ViewEffects, type ViewEffectSettings, type ViewKick, type ViewSample } from './view-effects.js';\n\nexport interface ClientImports {\n readonly engine: EngineImports;\n}\n\nexport interface ClientExports extends ClientRenderer<PredictionState> {\n predict(command: UserCommand): PredictionState;\n readonly prediction: ClientPrediction;\n readonly lastRendered?: PredictionState;\n readonly view: ViewEffects;\n readonly lastView?: ViewSample;\n}\n\nexport function createClient(imports: ClientImports): ClientExports {\n const prediction = new ClientPrediction();\n const view = new ViewEffects();\n let latestFrame: GameFrameResult<PredictionState> | undefined;\n let lastRendered: PredictionState | undefined;\n let lastView: ViewSample | undefined;\n\n return {\n init(initial) {\n latestFrame = initial;\n if (initial?.state) {\n prediction.setAuthoritative(initial);\n }\n void imports.engine.trace({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });\n },\n predict(command: UserCommand): PredictionState {\n return prediction.enqueueCommand(command);\n },\n render(sample: GameRenderSample<PredictionState>): void {\n if (sample.latest?.state) {\n prediction.setAuthoritative(sample.latest);\n latestFrame = sample.latest;\n }\n\n if (sample.previous?.state && sample.latest?.state) {\n lastRendered = interpolatePredictionState(sample.previous.state, sample.latest.state, sample.alpha);\n } else {\n lastRendered = sample.latest?.state ?? sample.previous?.state ?? prediction.getPredictedState();\n }\n\n const frameTimeMs = sample.latest && sample.previous ? Math.max(0, sample.latest.timeMs - sample.previous.timeMs) : 0;\n lastView = view.sample(lastRendered, frameTimeMs);\n\n void imports;\n void sample;\n },\n shutdown() {\n latestFrame = undefined;\n lastRendered = undefined;\n },\n get prediction(): ClientPrediction {\n return prediction;\n },\n get lastRendered(): PredictionState | undefined {\n return lastRendered;\n },\n get view(): ViewEffects {\n return view;\n },\n get lastView(): ViewSample | undefined {\n return lastView;\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\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 findSoundIndex(path: string): number | undefined {\n for (let i = ConfigStringIndex.Sounds; i < ConfigStringIndex.Sounds + MAX_SOUNDS; i += 1) {\n if (this.values.get(i) === path) {\n return i;\n }\n }\n return undefined;\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, normalizePath, type PakValidationResult } from './pak.js';\n\nexport interface KnownPakChecksum {\n readonly name: string;\n readonly checksum: number;\n readonly size?: number;\n readonly description?: string;\n}\n\nexport interface PakValidationOutcome {\n readonly name: string;\n readonly checksum: number;\n readonly expectedChecksum?: number;\n readonly size?: number;\n readonly status: 'valid' | 'mismatch' | 'unknown';\n readonly description?: string;\n}\n\nexport const RERELEASE_KNOWN_PAKS: readonly KnownPakChecksum[] = Object.freeze([\n // Base campaign\n { name: 'pak0.pak', checksum: 0x8dbe2e6d, description: 'Base game assets' },\n { name: 'pak0.pak@baseq2', checksum: 0x8dbe2e6d, description: 'Base game assets (baseq2)' },\n // Mission packs bundled with the rerelease\n { name: 'pak0.pak@rogue', checksum: 0xc90f1e6d, description: 'Ground Zero (rogue) mission pack' },\n { name: 'pak0.pak@xatrix', checksum: 0x50f58d80, description: 'The Reckoning (xatrix) mission pack' },\n]);\n\nexport class PakValidationError extends Error {\n constructor(readonly result: PakValidationOutcome) {\n super(\n result.status === 'unknown'\n ? `Unknown PAK not allowed: ${result.name}`\n : `PAK checksum mismatch for ${result.name}`,\n );\n this.name = 'PakValidationError';\n }\n}\n\nexport class PakValidator {\n private readonly known = new Map<string, KnownPakChecksum>();\n\n constructor(knownPaks: readonly KnownPakChecksum[] = RERELEASE_KNOWN_PAKS) {\n knownPaks.forEach((pak) => this.known.set(this.normalizePakName(pak.name), pak));\n }\n\n validateArchive(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const pakName = this.normalizePakName(nameOverride ?? ('name' in archive ? archive.name : 'unknown'));\n const checksum = archive.checksum;\n const size = 'size' in archive ? archive.size : undefined;\n\n const known = this.known.get(pakName);\n if (!known) {\n return { name: pakName, checksum, status: 'unknown', size };\n }\n\n if (known.checksum !== checksum) {\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'mismatch',\n size,\n description: known.description,\n };\n }\n\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'valid',\n size,\n description: known.description,\n };\n }\n\n assertValid(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const outcome = this.validateArchive(archive, nameOverride);\n if (outcome.status === 'mismatch') {\n throw new PakValidationError(outcome);\n }\n return outcome;\n }\n\n private normalizePakName(name: string): string {\n const normalized = normalizePath(name);\n const parts = normalized.split('/');\n const filename = parts.pop() ?? normalized;\n const directory = parts.pop();\n return directory ? `${filename}@${directory}` : filename;\n }\n}\n","import { PakArchive } from './pak.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { PakIndexStore } from './pakIndexStore.js';\nimport { PakValidationError, PakValidator, type PakValidationOutcome } from './pakValidation.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 readonly validation?: PakValidationOutcome;\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 * Optional persistence target for PAK directory indexes. When provided, each successfully\n * parsed archive will be stored in IndexedDB so the browser can rebuild listings without\n * reparsing the binary payload.\n */\n readonly pakIndexStore?: PakIndexStore;\n /**\n * Whether to persist parsed PAK indexes. Defaults to true when a pakIndexStore is provided.\n */\n readonly persistIndexes?: boolean;\n /**\n * Optional checksum validator. When provided, PAKs whose checksums do not match the known list will\n * raise a PakValidationError unless `enforceValidation` is explicitly set to false.\n */\n readonly validator?: PakValidator;\n /**\n * Whether checksum mismatches should prevent mounting the archive. Defaults to true when a validator\n * is supplied.\n */\n readonly enforceValidation?: boolean;\n /**\n * Whether unknown PAKs (not present in the validator list) are allowed. Defaults to true.\n */\n readonly allowUnknownPaks?: boolean;\n /**\n * Callback invoked with the validation outcome when a validator is provided.\n */\n readonly onValidationResult?: (outcome: PakValidationOutcome) => void;\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 shouldPersist = options.persistIndexes ?? Boolean(options.pakIndexStore);\n const enforceValidation = options.enforceValidation ?? Boolean(options.validator);\n const allowUnknownPaks = options.allowUnknownPaks ?? true;\n const stopOnError = options.stopOnError ?? false;\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 const validation = options.validator?.validateArchive(archive);\n if (validation) {\n options.onValidationResult?.(validation);\n const isMismatch = validation.status === 'mismatch';\n const isUnknown = validation.status === 'unknown';\n if ((isMismatch && enforceValidation) || (isUnknown && !allowUnknownPaks)) {\n const validationError = new PakValidationError(validation);\n options.onError?.(source.name, validationError);\n if (stopOnError) {\n throw new PakIngestionError(source.name, validationError);\n }\n results.push({ archive, mounted: false, validation });\n continue;\n }\n }\n vfs.mountPak(archive);\n if (shouldPersist && options.pakIndexStore) {\n try {\n await options.pakIndexStore.persist(archive);\n } catch (error) {\n options.onError?.(source.name, error);\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n options.onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'parsed' });\n results.push({ archive, mounted: true, validation });\n } catch (error) {\n options.onProgress?.({ file: source.name, loadedBytes: 0, totalBytes: 0, state: 'error' });\n options.onError?.(source.name, error);\n\n if (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","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD3_IDENT = 860898377; // 'IDP3'\nconst MD3_VERSION = 15;\n\nexport interface Md3Header {\n readonly ident: number;\n readonly version: number;\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly numTags: number;\n readonly numSurfaces: number;\n readonly numSkins: number;\n readonly ofsFrames: number;\n readonly ofsTags: number;\n readonly ofsSurfaces: number;\n readonly ofsEnd: number;\n}\n\nexport interface Md3Frame {\n readonly minBounds: Vec3;\n readonly maxBounds: Vec3;\n readonly localOrigin: Vec3;\n readonly radius: number;\n readonly name: string;\n}\n\nexport interface Md3Tag {\n readonly name: string;\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n}\n\nexport interface Md3Triangle {\n readonly indices: readonly [number, number, number];\n}\n\nexport interface Md3Shader {\n readonly name: string;\n readonly shaderIndex: number;\n}\n\nexport interface Md3TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md3Vertex {\n readonly position: Vec3;\n readonly normal: Vec3;\n readonly latLng: number;\n}\n\nexport interface Md3Surface {\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly shaders: readonly Md3Shader[];\n readonly triangles: readonly Md3Triangle[];\n readonly texCoords: readonly Md3TexCoord[];\n readonly vertices: readonly (readonly Md3Vertex[])[];\n}\n\nexport interface Md3Model {\n readonly header: Md3Header;\n readonly frames: readonly Md3Frame[];\n readonly tags: readonly Md3Tag[][];\n readonly surfaces: readonly Md3Surface[];\n}\n\nexport class Md3ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Md3ParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);\n const decoded = new TextDecoder('utf-8').decode(bytes);\n return decoded.replace(/\\0.*$/, '').trim();\n}\n\nfunction decodeLatLngNormal(latLng: number): Vec3 {\n const lat = ((latLng >> 8) & 0xff) * (2 * Math.PI / 255);\n const lng = (latLng & 0xff) * (2 * Math.PI / 255);\n const sinLng = Math.sin(lng);\n return {\n x: Math.cos(lat) * sinLng,\n y: Math.sin(lat) * sinLng,\n z: Math.cos(lng),\n };\n}\n\nfunction validateOffset(name: string, offset: number, size: number, bufferLength: number): void {\n if (offset < 0 || offset + size > bufferLength) {\n throw new Md3ParseError(`${name} exceeds buffer bounds`);\n }\n}\n\nfunction parseHeader(view: DataView): Md3Header {\n const ident = view.getInt32(0, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid MD3 ident: ${ident}`);\n }\n const version = view.getInt32(4, true);\n if (version !== MD3_VERSION) {\n throw new Md3ParseError(`Unsupported MD3 version: ${version}`);\n }\n\n const name = readString(view, 8, 64);\n const flags = view.getInt32(72, true);\n const numFrames = view.getInt32(76, true);\n const numTags = view.getInt32(80, true);\n const numSurfaces = view.getInt32(84, true);\n const numSkins = view.getInt32(88, true);\n const ofsFrames = view.getInt32(92, true);\n const ofsTags = view.getInt32(96, true);\n const ofsSurfaces = view.getInt32(100, true);\n const ofsEnd = view.getInt32(104, true);\n\n if (numFrames <= 0 || numSurfaces < 0 || numTags < 0) {\n throw new Md3ParseError('Invalid MD3 counts');\n }\n\n return {\n ident,\n version,\n name,\n flags,\n numFrames,\n numTags,\n numSurfaces,\n numSkins,\n ofsFrames,\n ofsTags,\n ofsSurfaces,\n ofsEnd,\n };\n}\n\nfunction parseFrames(view: DataView, header: Md3Header): Md3Frame[] {\n const frames: Md3Frame[] = [];\n const frameSize = 56;\n validateOffset('Frames', header.ofsFrames, header.numFrames * frameSize, view.byteLength);\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.ofsFrames + i * frameSize;\n frames.push({\n minBounds: {\n x: view.getFloat32(base, true),\n y: view.getFloat32(base + 4, true),\n z: view.getFloat32(base + 8, true),\n },\n maxBounds: {\n x: view.getFloat32(base + 12, true),\n y: view.getFloat32(base + 16, true),\n z: view.getFloat32(base + 20, true),\n },\n localOrigin: {\n x: view.getFloat32(base + 24, true),\n y: view.getFloat32(base + 28, true),\n z: view.getFloat32(base + 32, true),\n },\n radius: view.getFloat32(base + 36, true),\n name: readString(view, base + 40, 16),\n });\n }\n\n return frames;\n}\n\nfunction parseTags(view: DataView, header: Md3Header): Md3Tag[][] {\n const tags: Md3Tag[][] = [];\n const tagSize = 112;\n const totalSize = header.numFrames * header.numTags * tagSize;\n validateOffset('Tags', header.ofsTags, totalSize, view.byteLength);\n\n for (let frame = 0; frame < header.numFrames; frame += 1) {\n const frameTags: Md3Tag[] = [];\n for (let tagIndex = 0; tagIndex < header.numTags; tagIndex += 1) {\n const base = header.ofsTags + (frame * header.numTags + tagIndex) * tagSize;\n const originOffset = base + 64;\n const axisOffset = originOffset + 12;\n frameTags.push({\n name: readString(view, base, 64),\n origin: {\n x: view.getFloat32(originOffset, true),\n y: view.getFloat32(originOffset + 4, true),\n z: view.getFloat32(originOffset + 8, true),\n },\n axis: [\n {\n x: view.getFloat32(axisOffset, true),\n y: view.getFloat32(axisOffset + 4, true),\n z: view.getFloat32(axisOffset + 8, true),\n },\n {\n x: view.getFloat32(axisOffset + 12, true),\n y: view.getFloat32(axisOffset + 16, true),\n z: view.getFloat32(axisOffset + 20, true),\n },\n {\n x: view.getFloat32(axisOffset + 24, true),\n y: view.getFloat32(axisOffset + 28, true),\n z: view.getFloat32(axisOffset + 32, true),\n },\n ],\n });\n }\n tags.push(frameTags);\n }\n\n return tags;\n}\n\nfunction parseSurface(view: DataView, offset: number): { surface: Md3Surface; nextOffset: number } {\n const ident = view.getInt32(offset, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid surface ident at ${offset}: ${ident}`);\n }\n\n const name = readString(view, offset + 4, 64);\n const flags = view.getInt32(offset + 68, true);\n const numFrames = view.getInt32(offset + 72, true);\n const numShaders = view.getInt32(offset + 76, true);\n const numVerts = view.getInt32(offset + 80, true);\n const numTriangles = view.getInt32(offset + 84, true);\n const ofsTriangles = view.getInt32(offset + 88, true);\n const ofsShaders = view.getInt32(offset + 92, true);\n const ofsSt = view.getInt32(offset + 96, true);\n const ofsXyzNormals = view.getInt32(offset + 100, true);\n const ofsEnd = view.getInt32(offset + 104, true);\n\n if (numFrames <= 0 || numVerts <= 0 || numTriangles <= 0) {\n throw new Md3ParseError(`Invalid surface counts for ${name}`);\n }\n\n const surfaceSize = ofsEnd;\n validateOffset(`Surface ${name}`, offset, surfaceSize, view.byteLength);\n\n const triangles: Md3Triangle[] = [];\n const triangleStart = offset + ofsTriangles;\n for (let i = 0; i < numTriangles; i += 1) {\n const base = triangleStart + i * 12;\n triangles.push({\n indices: [view.getInt32(base, true), view.getInt32(base + 4, true), view.getInt32(base + 8, true)],\n });\n }\n\n const shaders: Md3Shader[] = [];\n const shaderStart = offset + ofsShaders;\n for (let i = 0; i < numShaders; i += 1) {\n const base = shaderStart + i * 68;\n shaders.push({ name: readString(view, base, 64), shaderIndex: view.getInt32(base + 64, true) });\n }\n\n const texCoords: Md3TexCoord[] = [];\n const stStart = offset + ofsSt;\n for (let i = 0; i < numVerts; i += 1) {\n const base = stStart + i * 8;\n texCoords.push({ s: view.getFloat32(base, true), t: view.getFloat32(base + 4, true) });\n }\n\n const vertices: Md3Vertex[][] = [];\n const xyzStart = offset + ofsXyzNormals;\n for (let frame = 0; frame < numFrames; frame += 1) {\n const frameVertices: Md3Vertex[] = [];\n for (let i = 0; i < numVerts; i += 1) {\n const base = xyzStart + (frame * numVerts + i) * 8;\n const x = view.getInt16(base, true) / 64;\n const y = view.getInt16(base + 2, true) / 64;\n const z = view.getInt16(base + 4, true) / 64;\n const latLng = view.getUint16(base + 6, true);\n frameVertices.push({ position: { x, y, z }, latLng, normal: decodeLatLngNormal(latLng) });\n }\n vertices.push(frameVertices);\n }\n\n return {\n surface: { name, flags, numFrames, shaders, triangles, texCoords, vertices },\n nextOffset: offset + ofsEnd,\n };\n}\n\nexport function parseMd3(buffer: ArrayBufferLike): Md3Model {\n if (buffer.byteLength < 108) {\n throw new Md3ParseError('MD3 buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const header = parseHeader(view);\n validateOffset('MD3 end', header.ofsEnd, 0, buffer.byteLength);\n\n const frames = parseFrames(view, header);\n const tags = parseTags(view, header);\n\n const surfaces: Md3Surface[] = [];\n let surfaceOffset = header.ofsSurfaces;\n for (let i = 0; i < header.numSurfaces; i += 1) {\n const { surface, nextOffset } = parseSurface(view, surfaceOffset);\n surfaces.push(surface);\n surfaceOffset = nextOffset;\n }\n\n if (surfaceOffset !== header.ofsEnd) {\n throw new Md3ParseError('Surface parsing did not reach ofsEnd');\n }\n\n return { header, frames, tags, surfaces };\n}\n\nexport class Md3Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md3Model> {\n const data = await this.vfs.readFile(path);\n return parseMd3(data.slice().buffer);\n }\n}\n","export interface FrameBlend {\n readonly frame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface AnimationSequence {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n readonly fps: number;\n readonly loop?: boolean;\n}\n\nexport interface AnimationState {\n readonly sequence: AnimationSequence;\n readonly time: number;\n}\n\nexport function advanceAnimation(state: AnimationState, deltaSeconds: number): AnimationState {\n const duration = (state.sequence.end - state.sequence.start + 1) / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n let time = state.time + deltaSeconds;\n\n if (loop) {\n time = ((time % duration) + duration) % duration;\n } else if (time > duration) {\n time = duration;\n }\n\n return { ...state, time: Math.max(0, Math.min(time, duration)) };\n}\n\nexport function computeFrameBlend(state: AnimationState): FrameBlend {\n const totalFrames = state.sequence.end - state.sequence.start + 1;\n const frameDuration = 1 / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n const framePosition = state.time / frameDuration;\n\n if (!loop && framePosition >= totalFrames) {\n return { frame: state.sequence.end, nextFrame: state.sequence.end, lerp: 0 };\n }\n\n const normalizedPosition = loop ? framePosition % totalFrames : Math.min(framePosition, totalFrames - 1);\n const baseFrame = Math.floor(normalizedPosition);\n const frame = state.sequence.start + baseFrame;\n const nextFrame = baseFrame + 1 >= totalFrames ? (loop ? state.sequence.start : state.sequence.end) : frame + 1;\n const lerp = !loop && baseFrame >= totalFrames - 1 ? 0 : normalizedPosition - baseFrame;\n return { frame, nextFrame, lerp };\n}\n\nexport function createAnimationState(sequence: AnimationSequence): AnimationState {\n return { sequence, time: 0 };\n}\n\nexport function interpolateVec3(\n a: { x: number; y: number; z: number },\n b: { x: number; y: number; z: number },\n t: number,\n): { x: number; y: number; z: number } {\n return {\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n z: a.z + (b.z - a.z) * t,\n };\n}\n","export interface WalTexture {\n readonly name: string;\n readonly width: number;\n readonly height: number;\n readonly mipmaps: readonly WalMipmap[];\n readonly animName: string;\n readonly flags: number;\n readonly contents: number;\n readonly value: number;\n}\n\nexport interface WalMipmap {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\nexport class WalParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WalParseError';\n }\n}\n\nexport function parseWal(buffer: ArrayBuffer): WalTexture {\n if (buffer.byteLength < 100) {\n throw new WalParseError('WAL buffer too small');\n }\n\n const view = new DataView(buffer);\n const nameBytes = new Uint8Array(buffer, 0, 32);\n const name = new TextDecoder('utf-8').decode(nameBytes).replace(/\\0.*$/, '').trim();\n const width = view.getInt32(32, true);\n const height = view.getInt32(36, true);\n const offsets = [view.getInt32(40, true), view.getInt32(44, true), view.getInt32(48, true), view.getInt32(52, true)];\n const animNameBytes = new Uint8Array(buffer, 56, 32);\n const animName = new TextDecoder('utf-8').decode(animNameBytes).replace(/\\0.*$/, '').trim();\n const flags = view.getInt32(88, true);\n const contents = view.getInt32(92, true);\n const value = view.getInt32(96, true);\n\n if (width <= 0 || height <= 0) {\n throw new WalParseError('Invalid WAL dimensions');\n }\n\n const mipmaps: WalMipmap[] = [];\n let currentWidth = width;\n let currentHeight = height;\n\n for (let level = 0; level < offsets.length; level += 1) {\n const offset = offsets[level];\n const expectedSize = Math.max(1, (currentWidth * currentHeight) | 0);\n if (offset <= 0 || offset + expectedSize > buffer.byteLength) {\n throw new WalParseError(`Invalid WAL mip offset for level ${level}`);\n }\n const data = new Uint8Array(buffer, offset, expectedSize);\n mipmaps.push({ level, width: currentWidth, height: currentHeight, data });\n currentWidth = Math.max(1, currentWidth >> 1);\n currentHeight = Math.max(1, currentHeight >> 1);\n }\n\n return { name, width, height, mipmaps, animName, flags, contents, value };\n}\n","export interface PcxImage {\n readonly width: number;\n readonly height: number;\n readonly bitsPerPixel: number;\n readonly pixels: Uint8Array;\n readonly palette: Uint8Array;\n}\n\nexport class PcxParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'PcxParseError';\n }\n}\n\nexport function parsePcx(buffer: ArrayBuffer): PcxImage {\n if (buffer.byteLength < 128) {\n throw new PcxParseError('PCX buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const manufacturer = view.getUint8(0);\n const encoding = view.getUint8(2);\n const bitsPerPixel = view.getUint8(3);\n const xMin = view.getUint16(4, true);\n const yMin = view.getUint16(6, true);\n const xMax = view.getUint16(8, true);\n const yMax = view.getUint16(10, true);\n\n if (manufacturer !== 0x0a || encoding !== 1) {\n throw new PcxParseError('Unsupported PCX encoding');\n }\n if (bitsPerPixel !== 8) {\n throw new PcxParseError('Only 8bpp PCX files are supported');\n }\n\n const width = xMax - xMin + 1;\n const height = yMax - yMin + 1;\n const bytesPerLine = view.getUint16(66, true);\n\n const paletteMarkerOffset = buffer.byteLength - 769;\n if (paletteMarkerOffset < 128 || new DataView(buffer, paletteMarkerOffset, 1).getUint8(0) !== 0x0c) {\n throw new PcxParseError('Missing PCX palette');\n }\n\n const palette = new Uint8Array(buffer, paletteMarkerOffset + 1, 768);\n const encoded = new Uint8Array(buffer, 128, paletteMarkerOffset - 128);\n const pixels = new Uint8Array(width * height);\n\n let srcIndex = 0;\n let dstIndex = 0;\n\n for (let y = 0; y < height; y += 1) {\n let written = 0;\n while (written < bytesPerLine && srcIndex < encoded.length) {\n let count = 1;\n let value = encoded[srcIndex++]!;\n\n if ((value & 0xc0) === 0xc0) {\n count = value & 0x3f;\n if (srcIndex >= encoded.length) {\n throw new PcxParseError('Unexpected end of PCX RLE data');\n }\n value = encoded[srcIndex++]!;\n }\n\n for (let i = 0; i < count && written < bytesPerLine; i += 1) {\n if (written < width) {\n pixels[dstIndex++] = value;\n }\n written += 1;\n }\n }\n }\n\n return { width, height, bitsPerPixel, pixels, palette };\n}\n\nexport function pcxToRgba(image: PcxImage): Uint8Array {\n const rgba = new Uint8Array(image.width * image.height * 4);\n for (let i = 0; i < image.pixels.length; i += 1) {\n const colorIndex = image.pixels[i]!;\n const paletteIndex = colorIndex * 3;\n const rgbaIndex = i * 4;\n rgba[rgbaIndex] = image.palette[paletteIndex]!;\n rgba[rgbaIndex + 1] = image.palette[paletteIndex + 1]!;\n rgba[rgbaIndex + 2] = image.palette[paletteIndex + 2]!;\n rgba[rgbaIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n return rgba;\n}\n","import { LruCache } from './cache.js';\nimport { pcxToRgba, type PcxImage } from './pcx.js';\nimport { parseWal, type WalTexture } from './wal.js';\n\nexport interface PreparedTexture {\n readonly width: number;\n readonly height: number;\n readonly levels: readonly TextureLevel[];\n readonly source: 'pcx' | 'wal';\n}\n\nexport interface TextureLevel {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly rgba: Uint8Array;\n}\n\nexport interface TextureCacheOptions {\n readonly capacity?: number;\n}\n\nexport class TextureCache {\n private readonly cache: LruCache<PreparedTexture>;\n\n constructor(options: TextureCacheOptions = {}) {\n this.cache = new LruCache<PreparedTexture>(options.capacity ?? 128);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get(key: string): PreparedTexture | undefined {\n return this.cache.get(key.toLowerCase());\n }\n\n set(key: string, texture: PreparedTexture): void {\n this.cache.set(key.toLowerCase(), texture);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\nexport function walToRgba(wal: WalTexture, palette: Uint8Array): PreparedTexture {\n const levels: TextureLevel[] = [];\n for (const mip of wal.mipmaps) {\n const rgba = new Uint8Array(mip.width * mip.height * 4);\n for (let i = 0; i < mip.data.length; i += 1) {\n const colorIndex = mip.data[i]!;\n const paletteIndex = colorIndex * 3;\n const outIndex = i * 4;\n rgba[outIndex] = palette[paletteIndex]!;\n rgba[outIndex + 1] = palette[paletteIndex + 1]!;\n rgba[outIndex + 2] = palette[paletteIndex + 2]!;\n rgba[outIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n levels.push({ level: mip.level, width: mip.width, height: mip.height, rgba });\n }\n\n return { width: wal.width, height: wal.height, levels, source: 'wal' };\n}\n\nexport function preparePcxTexture(pcx: PcxImage): PreparedTexture {\n const rgba = pcxToRgba(pcx);\n const level: TextureLevel = { level: 0, width: pcx.width, height: pcx.height, rgba };\n return { width: pcx.width, height: pcx.height, levels: [level], source: 'pcx' };\n}\n\nexport function parseWalTexture(buffer: ArrayBuffer, palette: Uint8Array): PreparedTexture {\n return walToRgba(parseWal(buffer), palette);\n}\n","export interface WavData {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitsPerSample: number;\n readonly samples: Float32Array;\n}\n\nexport class WavParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WavParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n return new TextDecoder('ascii').decode(new Uint8Array(view.buffer, view.byteOffset + offset, length));\n}\n\nexport function parseWav(buffer: ArrayBuffer): WavData {\n if (buffer.byteLength < 44) {\n throw new WavParseError('WAV buffer too small');\n }\n\n const view = new DataView(buffer);\n if (readString(view, 0, 4) !== 'RIFF' || readString(view, 8, 4) !== 'WAVE') {\n throw new WavParseError('Invalid WAV header');\n }\n\n let offset = 12;\n let fmtOffset = -1;\n let dataOffset = -1;\n let fmtSize = 0;\n let dataSize = 0;\n\n while (offset + 8 <= buffer.byteLength) {\n const chunkId = readString(view, offset, 4);\n const chunkSize = view.getUint32(offset + 4, true);\n const chunkDataOffset = offset + 8;\n\n if (chunkId === 'fmt ') {\n fmtOffset = chunkDataOffset;\n fmtSize = chunkSize;\n } else if (chunkId === 'data') {\n dataOffset = chunkDataOffset;\n dataSize = chunkSize;\n }\n\n offset = chunkDataOffset + chunkSize;\n }\n\n if (fmtOffset === -1 || dataOffset === -1) {\n throw new WavParseError('Missing fmt or data chunk');\n }\n\n const audioFormat = view.getUint16(fmtOffset, true);\n const channels = view.getUint16(fmtOffset + 2, true);\n const sampleRate = view.getUint32(fmtOffset + 4, true);\n const bitsPerSample = view.getUint16(fmtOffset + 14, true);\n\n if (audioFormat !== 1) {\n throw new WavParseError('Only PCM WAV is supported');\n }\n\n const bytesPerSample = bitsPerSample / 8;\n const frameCount = dataSize / (bytesPerSample * channels);\n const samples = new Float32Array(frameCount * channels);\n\n for (let frame = 0; frame < frameCount; frame += 1) {\n for (let ch = 0; ch < channels; ch += 1) {\n const sampleIndex = frame * channels + ch;\n const byteOffset = dataOffset + sampleIndex * bytesPerSample;\n let value = 0;\n if (bitsPerSample === 8) {\n value = view.getUint8(byteOffset);\n samples[sampleIndex] = (value - 128) / 128;\n } else if (bitsPerSample === 16) {\n value = view.getInt16(byteOffset, true);\n samples[sampleIndex] = value / 32768;\n } else if (bitsPerSample === 24) {\n const b0 = view.getUint8(byteOffset);\n const b1 = view.getUint8(byteOffset + 1);\n const b2 = view.getInt8(byteOffset + 2);\n value = b0 | (b1 << 8) | (b2 << 16);\n samples[sampleIndex] = value / 8388608;\n } else {\n throw new WavParseError(`Unsupported bitsPerSample: ${bitsPerSample}`);\n }\n }\n }\n\n return { sampleRate, channels, bitsPerSample, samples };\n}\n","import { OggVorbisDecoder } from '@wasm-audio-decoders/ogg-vorbis';\n\nexport interface OggAudio {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitDepth: number;\n readonly channelData: readonly Float32Array[];\n}\n\nexport class OggDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OggDecodeError';\n }\n}\n\nexport async function decodeOgg(buffer: ArrayBuffer, decoder: OggVorbisDecoder = new OggVorbisDecoder()): Promise<OggAudio> {\n await decoder.ready;\n const result = await decoder.decode(new Uint8Array(buffer));\n\n const errors = (result as { errors?: { message: string }[] }).errors;\n if (errors && errors.length > 0) {\n throw new OggDecodeError(errors.map((err) => err.message).join('; '));\n }\n\n return {\n sampleRate: result.sampleRate,\n channels: result.channelData.length,\n bitDepth: result.bitDepth,\n channelData: result.channelData,\n };\n}\n","import { decodeOgg, type OggAudio } from './ogg.js';\nimport { parseWav } from './wav.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { LruCache } from './cache.js';\n\nexport type DecodedAudio = OggAudio;\n\nexport class AudioRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AudioRegistryError';\n }\n}\n\nexport interface AudioRegistryOptions {\n readonly cacheSize?: number;\n}\n\nexport class AudioRegistry {\n private readonly cache: LruCache<DecodedAudio>;\n private readonly refCounts = new Map<string, number>();\n\n constructor(private readonly vfs: VirtualFileSystem, options: AudioRegistryOptions = {}) {\n this.cache = new LruCache<DecodedAudio>(options.cacheSize ?? 64);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n async load(path: string): Promise<DecodedAudio> {\n const normalized = path.toLowerCase();\n const cached = this.cache.get(normalized);\n if (cached) {\n this.refCounts.set(normalized, (this.refCounts.get(normalized) ?? 0) + 1);\n return cached;\n }\n\n const data = await this.vfs.readFile(path);\n const arrayBuffer = data.slice().buffer;\n const audio = await this.decodeByExtension(path, arrayBuffer);\n this.cache.set(normalized, audio);\n this.refCounts.set(normalized, 1);\n return audio;\n }\n\n release(path: string): void {\n const normalized = path.toLowerCase();\n const count = this.refCounts.get(normalized) ?? 0;\n if (count <= 1) {\n this.cache.delete(normalized);\n this.refCounts.delete(normalized);\n } else {\n this.refCounts.set(normalized, count - 1);\n }\n }\n\n clearAll(): void {\n this.cache.clear();\n this.refCounts.clear();\n }\n\n private async decodeByExtension(path: string, buffer: ArrayBuffer): Promise<DecodedAudio> {\n const lower = path.toLowerCase();\n if (lower.endsWith('.wav')) {\n const wav = parseWav(buffer);\n const channels = wav.channels;\n const channelData: Float32Array[] = Array.from({ length: channels }, () => new Float32Array(wav.samples.length / channels));\n for (let i = 0; i < wav.samples.length; i += 1) {\n channelData[i % channels]![Math.floor(i / channels)] = wav.samples[i]!;\n }\n return { sampleRate: wav.sampleRate, channels, bitDepth: wav.bitsPerSample, channelData } satisfies OggAudio;\n }\n if (lower.endsWith('.ogg') || lower.endsWith('.oga')) {\n return decodeOgg(buffer);\n }\n throw new AudioRegistryError(`Unsupported audio format: ${path}`);\n }\n}\n","import { PakArchive, type PakDirectoryEntry, type PakValidationResult, normalizePath } from './pak.js';\n\nconst DEFAULT_DB_NAME = 'quake2ts-pak-indexes';\nconst DEFAULT_STORE_NAME = 'pak-indexes';\n\nexport interface StoredPakIndex extends PakValidationResult {\n readonly key: string;\n readonly name: string;\n readonly size: number;\n readonly persistedAt: number;\n}\n\nfunction getIndexedDb(): IDBFactory | undefined {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof window !== 'undefined' && 'indexedDB' in window) {\n return window.indexedDB;\n }\n if (typeof globalThis !== 'undefined' && 'indexedDB' in globalThis) {\n return (globalThis as unknown as { indexedDB?: IDBFactory }).indexedDB;\n }\n return undefined;\n}\n\nfunction openDatabase(dbName: string, storeName: string): Promise<IDBDatabase> {\n const idb = getIndexedDb();\n if (!idb) {\n return Promise.reject(new Error('IndexedDB is not available in this environment'));\n }\n\n return new Promise<IDBDatabase>((resolve, reject) => {\n const request = idb.open(dbName, 1);\n\n request.onupgradeneeded = () => {\n const { result } = request;\n if (!result.objectStoreNames.contains(storeName)) {\n result.createObjectStore(storeName, { keyPath: 'key' });\n }\n };\n\n request.onerror = () => reject(request.error ?? new Error('Unknown IndexedDB error'));\n request.onsuccess = () => resolve(request.result);\n });\n}\n\nfunction runTransaction<T>(\n db: IDBDatabase,\n storeName: string,\n mode: IDBTransactionMode,\n runner: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const transaction = db.transaction(storeName, mode);\n const store = transaction.objectStore(storeName);\n const request = runner(store);\n\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB transaction error'));\n });\n}\n\nfunction buildKey(name: string, checksum: number): string {\n return `${normalizePath(name)}:${checksum.toString(16)}`;\n}\n\nfunction cloneEntries(entries: readonly PakDirectoryEntry[]): PakDirectoryEntry[] {\n return entries.map((entry) => ({ ...entry }));\n}\n\nexport class PakIndexStore {\n constructor(\n private readonly dbName = DEFAULT_DB_NAME,\n private readonly storeName = DEFAULT_STORE_NAME,\n ) {}\n\n get isSupported(): boolean {\n return Boolean(getIndexedDb());\n }\n\n async persist(archive: PakArchive): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n\n const validation = archive.validate();\n const record: StoredPakIndex = {\n ...validation,\n key: buildKey(archive.name, validation.checksum),\n name: archive.name,\n size: archive.size,\n persistedAt: Date.now(),\n entries: cloneEntries(validation.entries),\n };\n\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.put(record));\n db.close();\n return record;\n }\n\n async find(name: string, checksum?: number): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n\n const record = await runTransaction(db, this.storeName, 'readonly', (store) => {\n if (key) {\n return store.get(key);\n }\n return store.getAll();\n });\n\n db.close();\n\n if (!record) {\n return undefined;\n }\n\n if (Array.isArray(record)) {\n const normalized = normalizePath(name);\n const matches = record.filter((candidate: StoredPakIndex) => normalizePath(candidate.name) === normalized);\n if (matches.length === 0) {\n return undefined;\n }\n return matches.sort((a, b) => b.persistedAt - a.persistedAt)[0];\n }\n\n return record as StoredPakIndex;\n }\n\n async remove(name: string, checksum?: number): Promise<boolean> {\n if (!this.isSupported) {\n return false;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n const result = await runTransaction(db, this.storeName, 'readwrite', (store) => {\n if (key) {\n return store.delete(key);\n }\n const prefix = `${normalizePath(name)}:`;\n return store.delete(IDBKeyRange.bound(prefix, `${prefix}`, false, true));\n });\n db.close();\n return typeof result === 'number' ? result > 0 : true;\n }\n\n async clear(): Promise<void> {\n if (!this.isSupported) {\n return;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.clear());\n db.close();\n }\n\n async list(): Promise<StoredPakIndex[]> {\n if (!this.isSupported) {\n return [];\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const result = await runTransaction(db, this.storeName, 'readonly', (store) => store.getAll());\n db.close();\n return (result as StoredPakIndex[]).sort((a, b) => b.persistedAt - a.persistedAt);\n }\n}\n","import { normalizePath } from './pak.js';\nimport { TextureCache, type PreparedTexture } from './texture.js';\nimport { AudioRegistry, type DecodedAudio } from './audio.js';\nimport { Md2Loader, type Md2Model } from './md2.js';\nimport { Md3Loader, type Md3Model } from './md3.js';\nimport { VirtualFileSystem } from './vfs.js';\n\ntype AssetType = 'texture' | 'model' | 'sound';\n\ninterface DependencyNode {\n readonly dependencies: Set<string>;\n loaded: boolean;\n}\n\nexport class AssetDependencyError extends Error {\n constructor(readonly missing: readonly string[], message?: string) {\n super(message ?? `Missing dependencies: ${missing.join(', ')}`);\n this.name = 'AssetDependencyError';\n }\n}\n\nexport class AssetDependencyTracker {\n private readonly nodes = new Map<string, DependencyNode>();\n\n register(assetKey: string, dependencies: readonly string[] = []): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n dependencies.forEach((dependency) => node.dependencies.add(dependency));\n this.nodes.set(assetKey, node);\n dependencies.forEach((dependency) => {\n if (!this.nodes.has(dependency)) {\n this.nodes.set(dependency, { dependencies: new Set<string>(), loaded: false });\n }\n });\n }\n\n markLoaded(assetKey: string): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n const missing = this.getMissingDependencies(assetKey, node);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${assetKey} is missing dependencies: ${missing.join(', ')}`);\n }\n node.loaded = true;\n this.nodes.set(assetKey, node);\n }\n\n markUnloaded(assetKey: string): void {\n const node = this.nodes.get(assetKey);\n if (node) {\n node.loaded = false;\n }\n }\n\n isLoaded(assetKey: string): boolean {\n return this.nodes.get(assetKey)?.loaded ?? false;\n }\n\n missingDependencies(assetKey: string): string[] {\n const node = this.nodes.get(assetKey);\n if (!node) {\n return [];\n }\n return this.getMissingDependencies(assetKey, node);\n }\n\n reset(): void {\n this.nodes.clear();\n }\n\n private getMissingDependencies(assetKey: string, node: DependencyNode): string[] {\n const missing: string[] = [];\n for (const dependency of node.dependencies) {\n if (!this.nodes.get(dependency)?.loaded) {\n missing.push(dependency);\n }\n }\n return missing;\n }\n}\n\nexport interface AssetManagerOptions {\n readonly textureCacheCapacity?: number;\n readonly audioCacheSize?: number;\n readonly dependencyTracker?: AssetDependencyTracker;\n}\n\nexport class AssetManager {\n readonly textures: TextureCache;\n readonly audio: AudioRegistry;\n readonly dependencyTracker: AssetDependencyTracker;\n private readonly md2: Md2Loader;\n private readonly md3: Md3Loader;\n\n constructor(private readonly vfs: VirtualFileSystem, options: AssetManagerOptions = {}) {\n this.textures = new TextureCache({ capacity: options.textureCacheCapacity ?? 128 });\n this.audio = new AudioRegistry(vfs, { cacheSize: options.audioCacheSize ?? 64 });\n this.dependencyTracker = options.dependencyTracker ?? new AssetDependencyTracker();\n this.md2 = new Md2Loader(vfs);\n this.md3 = new Md3Loader(vfs);\n }\n\n isAssetLoaded(type: AssetType, path: string): boolean {\n return this.dependencyTracker.isLoaded(this.makeKey(type, path));\n }\n\n registerTexture(path: string, texture: PreparedTexture): void {\n this.textures.set(path, texture);\n const key = this.makeKey('texture', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n }\n\n async loadSound(path: string): Promise<DecodedAudio> {\n const audio = await this.audio.load(path);\n const key = this.makeKey('sound', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n return audio;\n }\n\n async loadMd2Model(path: string, textureDependencies: readonly string[] = []): Promise<Md2Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md2.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadMd3Model(path: string, textureDependencies: readonly string[] = []): Promise<Md3Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md3.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n resetForLevelChange(): void {\n this.textures.clear();\n this.audio.clearAll();\n this.dependencyTracker.reset();\n }\n\n private makeKey(type: AssetType, path: string): string {\n return `${type}:${normalizePath(path)}`;\n }\n}\n","export const MAX_SOUND_CHANNELS = 32;\n\n// Sound channel identifiers and flags from the rerelease game headers.\nexport enum SoundChannel {\n Auto = 0,\n Weapon = 1,\n Voice = 2,\n Item = 3,\n Body = 4,\n Aux = 5,\n Footstep = 6,\n Aux3 = 7,\n\n NoPhsAdd = 1 << 3,\n Reliable = 1 << 4,\n ForcePos = 1 << 5,\n}\n\nexport const ATTN_LOOP_NONE = -1;\nexport const ATTN_NONE = 0;\nexport const ATTN_NORM = 1;\nexport const ATTN_IDLE = 2;\nexport const ATTN_STATIC = 3;\n\nexport const SOUND_FULLVOLUME = 80;\nexport const SOUND_LOOP_ATTENUATE = 0.003;\n\nexport function attenuationToDistanceMultiplier(attenuation: number): number {\n return attenuation === ATTN_STATIC ? attenuation * 0.001 : attenuation * 0.0005;\n}\n\nexport function calculateMaxAudibleDistance(attenuation: number): number {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n return distMult <= 0 ? Number.POSITIVE_INFINITY : SOUND_FULLVOLUME + 1 / distMult;\n}\n","export interface AudioParamLike {\n value: number;\n}\n\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): void;\n}\n\nexport interface BiquadFilterNodeLike extends AudioNodeLike {\n frequency: AudioParamLike;\n Q: AudioParamLike;\n type: string;\n}\n\nexport interface GainNodeLike extends AudioNodeLike {\n gain: AudioParamLike;\n}\n\nexport interface DynamicsCompressorNodeLike extends AudioNodeLike {}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n}\n\nexport interface AudioBufferSourceNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n onended: (() => void) | null;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n}\n\nexport interface PannerNodeLike extends AudioNodeLike {\n positionX: AudioParamLike;\n positionY: AudioParamLike;\n positionZ: AudioParamLike;\n refDistance?: number;\n maxDistance?: number;\n rolloffFactor?: number;\n distanceModel?: string;\n}\n\nexport interface AudioDestinationNodeLike extends AudioNodeLike {}\n\nexport interface AudioContextLike {\n readonly destination: AudioDestinationNodeLike;\n readonly currentTime: number;\n state: 'suspended' | 'running' | 'closed';\n resume(): Promise<void>;\n suspend(): Promise<void>;\n createGain(): GainNodeLike;\n createDynamicsCompressor(): DynamicsCompressorNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n createPanner?(): PannerNodeLike;\n createBiquadFilter?(): BiquadFilterNodeLike;\n decodeAudioData?(data: ArrayBuffer): Promise<AudioBufferLike>;\n}\n\nexport type AudioContextFactory = () => AudioContextLike;\n\nexport interface AudioGraph {\n context: AudioContextLike;\n master: GainNodeLike;\n compressor: DynamicsCompressorNodeLike;\n filter?: BiquadFilterNodeLike;\n}\n\nexport class AudioContextController {\n private context?: AudioContextLike;\n\n constructor(private readonly factory: AudioContextFactory) {}\n\n getContext(): AudioContextLike {\n if (!this.context) {\n this.context = this.factory();\n }\n return this.context;\n }\n\n async resume(): Promise<void> {\n const ctx = this.getContext();\n if (ctx.state === 'suspended') {\n await ctx.resume();\n }\n }\n\n getState(): AudioContextLike['state'] {\n return this.context?.state ?? 'suspended';\n }\n}\n\nexport function createAudioGraph(controller: AudioContextController): AudioGraph {\n const context = controller.getContext();\n const master = context.createGain();\n master.gain.value = 1;\n const compressor = context.createDynamicsCompressor();\n const filter = context.createBiquadFilter?.();\n if (filter) {\n filter.type = 'lowpass';\n filter.frequency.value = 20000;\n filter.Q.value = 0.707;\n master.connect(filter);\n filter.connect(compressor);\n } else {\n master.connect(compressor);\n }\n compressor.connect(context.destination);\n return { context, master, compressor, filter };\n}\n","import { ConfigStringRegistry } from '../configstrings.js';\nimport type { AudioBufferLike } from './context.js';\n\nexport class SoundRegistry {\n private readonly buffers = new Map<number, AudioBufferLike>();\n\n constructor(private readonly configStrings = new ConfigStringRegistry()) {}\n\n registerName(name: string): number {\n return this.configStrings.soundIndex(name);\n }\n\n register(name: string, buffer: AudioBufferLike): number {\n const index = this.registerName(name);\n this.buffers.set(index, buffer);\n return index;\n }\n\n find(name: string): number | undefined {\n return this.configStrings.findSoundIndex(name);\n }\n\n get(index: number): AudioBufferLike | undefined {\n return this.buffers.get(index);\n }\n\n has(index: number): boolean {\n return this.buffers.has(index);\n }\n}\n","import { normalizePath } from '../assets/pak.js';\nimport type { VirtualFileSystem } from '../assets/vfs.js';\nimport type { AudioBufferLike, AudioContextLike } from './context.js';\nimport { AudioContextController } from './context.js';\nimport { SoundRegistry } from './registry.js';\n\nexport interface SoundPrecacheOptions {\n vfs: Pick<VirtualFileSystem, 'readFile' | 'stat'>;\n registry: SoundRegistry;\n context: AudioContextController;\n decodeAudio?: (context: AudioContextLike, data: ArrayBuffer) => Promise<AudioBufferLike>;\n soundRoot?: string;\n}\n\nexport interface SoundPrecacheReport {\n loaded: string[];\n skipped: string[];\n missing: string[];\n errors: Record<string, Error>;\n}\n\nexport class SoundPrecache {\n private readonly vfs: SoundPrecacheOptions['vfs'];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly decodeAudio: NonNullable<SoundPrecacheOptions['decodeAudio']>;\n private readonly soundRoot: string;\n\n constructor(options: SoundPrecacheOptions) {\n this.vfs = options.vfs;\n this.registry = options.registry;\n this.contextController = options.context;\n this.soundRoot = options.soundRoot ?? 'sound/';\n this.decodeAudio =\n options.decodeAudio ??\n ((context: AudioContextLike, data: ArrayBuffer) => {\n if (!context.decodeAudioData) {\n throw new Error('decodeAudioData is not available on the provided audio context');\n }\n return context.decodeAudioData(data);\n });\n }\n\n async precache(paths: string[]): Promise<SoundPrecacheReport> {\n const unique = [...new Set(paths.map((p) => this.normalize(p)))];\n const report: SoundPrecacheReport = { loaded: [], skipped: [], missing: [], errors: {} };\n const context = this.contextController.getContext();\n\n for (const path of unique) {\n try {\n const existingIndex = this.registry.find(path);\n if (existingIndex !== undefined && this.registry.has(existingIndex)) {\n report.skipped.push(path);\n continue;\n }\n\n const stat = this.vfs.stat(path);\n if (!stat) {\n report.missing.push(path);\n continue;\n }\n\n const bytes = await this.vfs.readFile(path);\n const copy = bytes.slice().buffer;\n const buffer = await this.decodeAudio(context, copy);\n this.registry.register(path, buffer);\n report.loaded.push(path);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n report.errors[path] = err;\n }\n }\n\n return report;\n }\n\n private normalize(path: string): string {\n const normalized = normalizePath(path.replace(/^\\//, ''));\n if (normalized.startsWith(this.soundRoot)) {\n return normalized;\n }\n return normalizePath(`${this.soundRoot}${normalized}`);\n }\n}\n","import { MAX_SOUND_CHANNELS, SoundChannel } from './constants.js';\n\nconst CHANNEL_MASK = 0x07;\n\nexport const baseChannel = (entchannel: number): number => entchannel & CHANNEL_MASK;\n\nexport interface ChannelState {\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n isPlayer: boolean;\n active: boolean;\n}\n\nexport interface ChannelPickContext {\n readonly nowMs: number;\n readonly playerEntity?: number;\n}\n\nexport function createInitialChannels(playerEntity?: number): ChannelState[] {\n return Array.from({ length: MAX_SOUND_CHANNELS }, () => ({\n entnum: 0,\n entchannel: SoundChannel.Auto,\n endTimeMs: 0,\n isPlayer: false,\n active: false,\n } satisfies ChannelState)).map((channel) => ({ ...channel, isPlayer: channel.entnum === playerEntity }));\n}\n\nexport function pickChannel(\n channels: ChannelState[],\n entnum: number,\n entchannel: number,\n context: ChannelPickContext,\n): number | undefined {\n if (entchannel < 0) {\n throw new Error('pickChannel: entchannel must be non-negative');\n }\n\n const normalizedEntchannel = baseChannel(entchannel);\n let firstToDie = -1;\n let lifeLeft = Number.POSITIVE_INFINITY;\n\n for (let i = 0; i < channels.length; i += 1) {\n const channel = channels[i];\n const channelBase = baseChannel(channel.entchannel);\n\n if (\n normalizedEntchannel !== SoundChannel.Auto &&\n channel.entnum === entnum &&\n channelBase === normalizedEntchannel\n ) {\n firstToDie = i;\n break;\n }\n\n if (channel.active && channel.entnum === context.playerEntity && entnum !== context.playerEntity) {\n continue;\n }\n\n const remainingLife = channel.endTimeMs - context.nowMs;\n if (firstToDie === -1 || remainingLife < lifeLeft) {\n lifeLeft = remainingLife;\n firstToDie = i;\n }\n }\n\n return firstToDie === -1 ? undefined : firstToDie;\n}\n","import { Vec3, dotVec3, lengthVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { SOUND_FULLVOLUME, attenuationToDistanceMultiplier } from './constants.js';\n\nexport interface ListenerState {\n origin: Vec3;\n right: Vec3;\n mono?: boolean;\n playerEntity?: number;\n}\n\nexport interface SpatializationResult {\n left: number;\n right: number;\n distanceComponent: number;\n}\n\nexport function spatializeOrigin(\n origin: Vec3,\n listener: ListenerState,\n masterVolume: number,\n attenuation: number,\n isListenerSound: boolean,\n): SpatializationResult {\n if (isListenerSound) {\n return { left: masterVolume, right: masterVolume, distanceComponent: 0 };\n }\n\n const sourceVec = subtractVec3(origin, listener.origin);\n const distance = lengthVec3(sourceVec);\n const normalized = normalizeVec3(sourceVec);\n let dist = distance - SOUND_FULLVOLUME;\n if (dist < 0) dist = 0;\n dist *= attenuationToDistanceMultiplier(attenuation);\n\n const dot = dotVec3(listener.right, normalized);\n const mono = listener.mono ?? false;\n const rscale = mono || attenuation === 0 ? 1 : 0.5 * (1 + dot);\n const lscale = mono || attenuation === 0 ? 1 : 0.5 * (1 - dot);\n\n const right = Math.max(0, Math.floor(masterVolume * (1 - dist) * rscale));\n const left = Math.max(0, Math.floor(masterVolume * (1 - dist) * lscale));\n\n return { left, right, distanceComponent: dist };\n}\n","import { ZERO_VEC3, type Vec3 } from '@quake2ts/shared';\nimport {\n ATTN_NONE,\n SOUND_FULLVOLUME,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n SoundChannel,\n} from './constants.js';\nimport {\n AudioContextController,\n createAudioGraph,\n type AudioContextLike,\n type AudioBufferSourceNodeLike,\n type AudioGraph,\n type BiquadFilterNodeLike,\n type GainNodeLike,\n type PannerNodeLike,\n} from './context.js';\nimport { SoundRegistry } from './registry.js';\nimport { baseChannel, createInitialChannels, pickChannel, type ChannelState } from './channels.js';\nimport { spatializeOrigin, type ListenerState } from './spatialization.js';\n\nexport interface SoundRequest {\n entity: number;\n channel: number;\n soundIndex: number;\n volume: number;\n attenuation: number;\n origin?: Vec3;\n timeOffsetMs?: number;\n looping?: boolean;\n}\n\nexport interface AudioSystemOptions {\n context: AudioContextController;\n registry: SoundRegistry;\n playerEntity?: number;\n listener?: ListenerState;\n sfxVolume?: number;\n masterVolume?: number;\n resolveOcclusion?: OcclusionResolver;\n}\n\ninterface ActiveSound {\n channelIndex: number;\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n source: AudioBufferSourceNodeLike;\n panner: PannerNodeLike;\n gain: GainNodeLike;\n baseGain: number;\n origin: Vec3;\n attenuation: number;\n occlusion?: OcclusionState;\n}\n\ninterface OcclusionState {\n scale: number;\n lowpassHz?: number;\n filter?: BiquadFilterNodeLike;\n}\n\nexport interface OcclusionResult {\n gainScale?: number;\n lowpassHz?: number;\n}\n\nexport type OcclusionResolver = (\n listener: ListenerState,\n source: Vec3,\n attenuation: number,\n) => OcclusionResult | undefined;\n\nexport interface AudioDiagnostics {\n activeChannels: number;\n masterVolume: number;\n sfxVolume: number;\n channels: ChannelState[];\n activeSounds: Array<{\n entnum: number;\n entchannel: number;\n channelIndex: number;\n origin: Vec3;\n gain: number;\n baseGain: number;\n attenuation: number;\n maxDistance?: number;\n distanceModel?: string;\n occlusion?: { scale: number; lowpassHz?: number };\n }>;\n}\n\nexport class AudioSystem {\n private readonly channels: ChannelState[];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly graph: AudioGraph;\n private readonly playerEntity?: number;\n private readonly activeSources = new Map<number, ActiveSound>();\n private readonly resolveOcclusion?: OcclusionResolver;\n private listener: ListenerState;\n private sfxVolume: number;\n private masterVolume: number;\n\n constructor(options: AudioSystemOptions) {\n this.contextController = options.context;\n this.registry = options.registry;\n this.playerEntity = options.playerEntity;\n this.channels = createInitialChannels(options.playerEntity);\n this.listener = options.listener ?? { origin: ZERO_VEC3, right: { x: 1, y: 0, z: 0 } };\n this.sfxVolume = options.sfxVolume ?? 1;\n this.masterVolume = options.masterVolume ?? 1;\n this.resolveOcclusion = options.resolveOcclusion;\n this.graph = createAudioGraph(this.contextController);\n this.graph.master.gain.value = this.masterVolume;\n }\n\n setListener(listener: ListenerState): void {\n this.listener = listener;\n }\n\n setMasterVolume(volume: number): void {\n this.masterVolume = volume;\n this.graph.master.gain.value = volume;\n }\n\n setSfxVolume(volume: number): void {\n this.sfxVolume = volume;\n }\n\n async ensureRunning(): Promise<void> {\n await this.contextController.resume();\n }\n\n play(request: SoundRequest): ActiveSound | undefined {\n const buffer = this.registry.get(request.soundIndex);\n if (!buffer) return undefined;\n\n const ctx = this.graph.context;\n const nowMs = ctx.currentTime * 1000;\n const channelIndex = pickChannel(this.channels, request.entity, request.channel, {\n nowMs,\n playerEntity: this.playerEntity,\n });\n\n if (channelIndex === undefined) return undefined;\n\n const existing = this.activeSources.get(channelIndex);\n if (existing) {\n existing.source.onended = null;\n existing.source.stop();\n this.activeSources.delete(channelIndex);\n }\n\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = request.looping ?? false;\n\n const origin = request.origin ?? this.listener.origin;\n const gain = ctx.createGain();\n const panner = this.createPanner(ctx, request.attenuation);\n const occlusion = this.resolveOcclusion?.(this.listener, origin, request.attenuation);\n const occlusionScale = clamp01(occlusion?.gainScale ?? 1);\n const occlusionFilter = this.resolveOcclusion\n ? this.createOcclusionFilter(ctx, occlusion?.lowpassHz ?? 20000)\n : undefined;\n this.applyOriginToPanner(panner, origin);\n const isListenerSound = request.entity === this.playerEntity;\n const spatial = spatializeOrigin(origin, this.listener, request.volume, request.attenuation, isListenerSound);\n\n const attenuationScale = request.volume === 0 ? 0 : Math.max(spatial.left, spatial.right) / Math.max(1, request.volume);\n const gainValue = attenuationScale * (request.volume / 255) * this.masterVolume * this.sfxVolume;\n gain.gain.value = gainValue * occlusionScale;\n\n const startTimeSec = ctx.currentTime + (request.timeOffsetMs ?? 0) / 1000;\n const endTimeMs = (request.looping ? Number.POSITIVE_INFINITY : buffer.duration * 1000) + startTimeSec * 1000;\n\n source.connect(panner);\n if (occlusionFilter) {\n panner.connect(occlusionFilter);\n occlusionFilter.connect(gain);\n } else {\n panner.connect(gain);\n }\n gain.connect(this.graph.master);\n\n source.start(startTimeSec);\n source.onended = () => {\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n };\n\n const active: ActiveSound = {\n channelIndex,\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n source,\n panner,\n gain,\n baseGain: gainValue,\n origin,\n attenuation: request.attenuation,\n occlusion: occlusionFilter\n ? { scale: occlusionScale, lowpassHz: occlusion?.lowpassHz, filter: occlusionFilter }\n : occlusion\n ? { scale: occlusionScale, lowpassHz: occlusion.lowpassHz }\n : undefined,\n };\n\n this.channels[channelIndex] = {\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n isPlayer: request.entity === this.playerEntity,\n active: true,\n };\n\n this.activeSources.set(channelIndex, active);\n return active;\n }\n\n stop(channelIndex: number): void {\n const active = this.activeSources.get(channelIndex);\n if (!active) return;\n active.source.stop();\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n }\n\n stopEntitySounds(entnum: number): void {\n for (const [index, active] of [...this.activeSources.entries()]) {\n if (active.entnum !== entnum) continue;\n active.source.stop();\n this.channels[index].active = false;\n this.activeSources.delete(index);\n }\n }\n\n updateEntityPosition(entnum: number, origin: Vec3): void {\n for (const active of this.activeSources.values()) {\n if (active.entnum !== entnum) continue;\n this.applyOriginToPanner(active.panner, origin);\n active.origin = origin;\n if (this.resolveOcclusion) {\n const occlusion = this.resolveOcclusion(this.listener, origin, active.attenuation);\n this.applyOcclusion(active, occlusion);\n }\n }\n }\n\n positionedSound(origin: Vec3, soundIndex: number, volume: number, attenuation: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation,\n origin,\n });\n }\n\n ambientSound(origin: Vec3, soundIndex: number, volume: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation: ATTN_NONE,\n origin,\n looping: true,\n });\n }\n\n getChannelState(index: number): ChannelState | undefined {\n return this.channels[index];\n }\n\n getDiagnostics(): AudioDiagnostics {\n return {\n activeChannels: this.activeSources.size,\n masterVolume: this.masterVolume,\n sfxVolume: this.sfxVolume,\n channels: [...this.channels],\n activeSounds: [...this.activeSources.values()].map((sound) => ({\n entnum: sound.entnum,\n entchannel: sound.entchannel,\n channelIndex: sound.channelIndex,\n origin: sound.origin,\n gain: sound.gain.gain.value,\n baseGain: sound.baseGain,\n attenuation: sound.attenuation,\n maxDistance: sound.panner.maxDistance,\n distanceModel: sound.panner.distanceModel,\n occlusion: sound.occlusion ? { scale: sound.occlusion.scale, lowpassHz: sound.occlusion.lowpassHz } : undefined,\n })),\n };\n }\n\n setUnderwater(enabled: boolean, cutoffHz = 400): void {\n const filter = this.graph.filter;\n if (!filter) return;\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = enabled ? cutoffHz : 20000;\n }\n\n private createPanner(context: AudioContextLike, attenuation: number): PannerNodeLike {\n const panner = context.createPanner\n ? context.createPanner()\n : Object.assign(context.createGain(), {\n positionX: { value: this.listener.origin.x },\n positionY: { value: this.listener.origin.y },\n positionZ: { value: this.listener.origin.z },\n } satisfies Partial<PannerNodeLike>);\n\n return this.configurePanner(panner, attenuation);\n }\n\n private configurePanner(panner: PannerNodeLike, attenuation: number): PannerNodeLike {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n panner.refDistance = SOUND_FULLVOLUME;\n panner.maxDistance = calculateMaxAudibleDistance(attenuation);\n panner.rolloffFactor = distMult;\n panner.distanceModel = attenuation === 0 ? 'linear' : 'inverse';\n panner.positionX.value = this.listener.origin.x;\n panner.positionY.value = this.listener.origin.y;\n panner.positionZ.value = this.listener.origin.z;\n return panner;\n }\n\n private applyOriginToPanner(panner: PannerNodeLike, origin: Vec3): void {\n panner.positionX.value = origin.x;\n panner.positionY.value = origin.y;\n panner.positionZ.value = origin.z;\n }\n\n private createOcclusionFilter(context: AudioContextLike, cutoffHz: number): BiquadFilterNodeLike | undefined {\n if (!context.createBiquadFilter) return undefined;\n const filter = context.createBiquadFilter();\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = clamp(cutoffHz, 10, 20000);\n return filter;\n }\n\n private applyOcclusion(active: ActiveSound, occlusion?: OcclusionResult): void {\n const scale = clamp01(occlusion?.gainScale ?? 1);\n active.gain.gain.value = active.baseGain * scale;\n if (active.occlusion?.filter) {\n const cutoff = occlusion?.lowpassHz ?? 20000;\n active.occlusion.filter.frequency.value = clamp(cutoff, 10, 20000);\n }\n if (active.occlusion) {\n active.occlusion.scale = scale;\n active.occlusion.lowpassHz = occlusion?.lowpassHz;\n } else if (occlusion) {\n active.occlusion = { scale, lowpassHz: occlusion.lowpassHz };\n }\n }\n}\n\nconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));\nconst clamp01 = (value: number): number => clamp(value, 0, 1);\n\n","export interface AudioElementLike {\n src: string;\n loop: boolean;\n volume: number;\n currentTime: number;\n paused: boolean;\n ended: boolean;\n play(): Promise<void>;\n pause(): void;\n load(): void;\n}\n\nexport type AudioElementFactory = () => AudioElementLike;\nexport type MusicSourceResolver = (path: string) => Promise<string>;\n\nexport interface MusicSystemOptions {\n createElement: AudioElementFactory;\n resolveSource?: MusicSourceResolver;\n volume?: number;\n}\n\nexport interface MusicState {\n readonly track?: string;\n readonly paused: boolean;\n readonly playing: boolean;\n readonly volume: number;\n}\n\nexport class MusicSystem {\n private readonly createElement: AudioElementFactory;\n private readonly resolveSource: MusicSourceResolver;\n private element?: AudioElementLike;\n private track?: string;\n private volume: number;\n\n constructor(options: MusicSystemOptions) {\n this.createElement = options.createElement;\n this.resolveSource = options.resolveSource ?? (async (path) => path);\n this.volume = options.volume ?? 1;\n }\n\n async play(track: string, { loop = true, restart = false }: { loop?: boolean; restart?: boolean } = {}): Promise<void> {\n if (this.track === track && this.element) {\n this.element.loop = loop;\n this.element.volume = this.volume;\n if (restart) {\n this.element.currentTime = 0;\n }\n if (this.element.paused || restart) {\n await this.element.play();\n }\n return;\n }\n\n const src = await this.resolveSource(track);\n const element = this.createElement();\n element.src = src;\n element.loop = loop;\n element.volume = this.volume;\n element.currentTime = 0;\n element.load();\n await element.play();\n\n this.element = element;\n this.track = track;\n }\n\n pause(): void {\n if (!this.element || this.element.paused) return;\n this.element.pause();\n }\n\n async resume(): Promise<void> {\n if (!this.element || !this.element.paused) return;\n await this.element.play();\n }\n\n stop(): void {\n if (!this.element) return;\n this.element.pause();\n this.element.currentTime = 0;\n this.element = undefined;\n this.track = undefined;\n }\n\n setVolume(volume: number): void {\n this.volume = volume;\n if (this.element) {\n this.element.volume = volume;\n }\n }\n\n getState(): MusicState {\n const playing = Boolean(this.element && !this.element.paused && !this.element.ended);\n const paused = Boolean(this.element?.paused);\n return { track: this.track, paused, playing, volume: this.volume };\n }\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport { MusicSystem } from './music.js';\nimport { SoundRegistry } from './registry.js';\nimport { AudioSystem, type SoundRequest } from './system.js';\n\nexport interface AudioApiOptions {\n registry: SoundRegistry;\n system: AudioSystem;\n music?: MusicSystem;\n}\n\nexport class AudioApi {\n private readonly registry: SoundRegistry;\n private readonly system: AudioSystem;\n private readonly music?: MusicSystem;\n\n constructor(options: AudioApiOptions) {\n this.registry = options.registry;\n this.system = options.system;\n this.music = options.music;\n }\n\n soundindex(name: string): number {\n return this.registry.registerName(name);\n }\n\n sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number, timeofs: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n timeOffsetMs: timeofs,\n });\n }\n\n positioned_sound(origin: Vec3, soundindex: number, volume: number, attenuation: number): void {\n this.system.positionedSound(origin, soundindex, volume, attenuation);\n }\n\n loop_sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n looping: true,\n });\n }\n\n stop_entity_sounds(entnum: number): void {\n this.system.stopEntitySounds(entnum);\n }\n\n set_listener(listener: Parameters<AudioSystem['setListener']>[0]): void {\n this.system.setListener(listener);\n }\n\n play_music(track: string, loop = true): Promise<void> {\n if (!this.music) {\n return Promise.resolve();\n }\n return this.music.play(track, { loop });\n }\n\n pause_music(): void {\n this.music?.pause();\n }\n\n resume_music(): Promise<void> {\n return this.music?.resume() ?? Promise.resolve();\n }\n\n stop_music(): void {\n this.music?.stop();\n }\n\n set_music_volume(volume: number): void {\n this.music?.setVolume(volume);\n }\n\n play_ambient(origin: Vec3, soundindex: number, volume: number): void {\n this.system.ambientSound(origin, soundindex, volume);\n }\n\n play_channel(request: Omit<SoundRequest, 'looping'>): void {\n this.system.play({ ...request });\n }\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 TextureCubeMap {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.target = gl.TEXTURE_CUBE_MAP;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate cubemap 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 uploadFace(\n faceTarget: GLenum,\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(faceTarget, 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 { type Vec3 } from '@quake2ts/shared';\n\nexport interface FrustumPlane {\n readonly normal: Vec3;\n readonly distance: number;\n}\n\nfunction normalizePlane(plane: FrustumPlane): FrustumPlane {\n const { normal, distance } = plane;\n const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z);\n if (length === 0) {\n return plane;\n }\n const inv = 1 / length;\n return {\n normal: { x: normal.x * inv, y: normal.y * inv, z: normal.z * inv },\n distance: distance * inv,\n };\n}\n\nexport function extractFrustumPlanes(matrix: readonly number[]): readonly FrustumPlane[] {\n if (matrix.length !== 16) {\n throw new Error('View-projection matrix must contain 16 elements');\n }\n\n const m00 = matrix[0];\n const m01 = matrix[4];\n const m02 = matrix[8];\n const m03 = matrix[12];\n const m10 = matrix[1];\n const m11 = matrix[5];\n const m12 = matrix[9];\n const m13 = matrix[13];\n const m20 = matrix[2];\n const m21 = matrix[6];\n const m22 = matrix[10];\n const m23 = matrix[14];\n const m30 = matrix[3];\n const m31 = matrix[7];\n const m32 = matrix[11];\n const m33 = matrix[15];\n\n const planes: FrustumPlane[] = [\n // Left\n normalizePlane({ normal: { x: m30 + m00, y: m31 + m01, z: m32 + m02 }, distance: m33 + m03 }),\n // Right\n normalizePlane({ normal: { x: m30 - m00, y: m31 - m01, z: m32 - m02 }, distance: m33 - m03 }),\n // Bottom\n normalizePlane({ normal: { x: m30 + m10, y: m31 + m11, z: m32 + m12 }, distance: m33 + m13 }),\n // Top\n normalizePlane({ normal: { x: m30 - m10, y: m31 - m11, z: m32 - m12 }, distance: m33 - m13 }),\n // Near\n normalizePlane({ normal: { x: m30 + m20, y: m31 + m21, z: m32 + m22 }, distance: m33 + m23 }),\n // Far\n normalizePlane({ normal: { x: m30 - m20, y: m31 - m21, z: m32 - m22 }, distance: m33 - m23 }),\n ];\n\n return planes;\n}\n\nfunction planeDistance(plane: FrustumPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.distance;\n}\n\nexport function boxIntersectsFrustum(mins: Vec3, maxs: Vec3, planes: readonly FrustumPlane[]): boolean {\n for (const plane of planes) {\n // Choose the corner most likely to be outside based on the plane normal.\n const x = plane.normal.x >= 0 ? maxs.x : mins.x;\n const y = plane.normal.y >= 0 ? maxs.y : mins.y;\n const z = plane.normal.z >= 0 ? maxs.z : mins.z;\n if (planeDistance(plane, { x, y, z }) < 0) {\n return false;\n }\n }\n return true;\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport type {\n BspLeaf,\n BspMap,\n BspNode,\n BspPlane,\n BspVisibility,\n} from '../assets/bsp.js';\nimport { boxIntersectsFrustum, type FrustumPlane } from './culling.js';\n\nexport interface VisibleFace {\n readonly faceIndex: number;\n readonly leafIndex: number;\n readonly sortKey: number;\n}\n\nfunction childIsLeaf(index: number): boolean {\n return index < 0;\n}\n\nfunction childLeafIndex(index: number): number {\n return -index - 1;\n}\n\nfunction distanceToPlane(plane: BspPlane, point: Vec3): number {\n return plane.normal[0] * point.x + plane.normal[1] * point.y + plane.normal[2] * point.z - plane.dist;\n}\n\nfunction isClusterVisible(visibility: BspVisibility | undefined, fromCluster: number, testCluster: number): boolean {\n if (!visibility) {\n return true;\n }\n if (fromCluster < 0 || testCluster < 0) {\n return true;\n }\n const rowBytes = Math.ceil(visibility.numClusters / 8);\n const row = visibility.clusters[fromCluster].pvs;\n const byteIndex = Math.floor(testCluster / 8);\n const bit = 1 << (testCluster % 8);\n if (byteIndex < 0 || byteIndex >= rowBytes) {\n return false;\n }\n return (row[byteIndex] & bit) !== 0;\n}\n\nfunction leafIntersectsFrustum(leaf: BspLeaf, planes: readonly FrustumPlane[]): boolean {\n const mins = { x: leaf.mins[0], y: leaf.mins[1], z: leaf.mins[2] };\n const maxs = { x: leaf.maxs[0], y: leaf.maxs[1], z: leaf.maxs[2] };\n return boxIntersectsFrustum(mins, maxs, planes);\n}\n\nexport function findLeafForPoint(map: BspMap, point: Vec3): number {\n let nodeIndex = 0;\n while (nodeIndex >= 0) {\n const node: BspNode = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, point);\n const side = dist >= 0 ? 0 : 1;\n const child = node.children[side];\n if (childIsLeaf(child)) {\n return childLeafIndex(child);\n }\n nodeIndex = child;\n }\n return -1;\n}\n\nfunction collectFacesFromLeaf(map: BspMap, leafIndex: number): number[] {\n const leaf = map.leafs[leafIndex];\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(map.leafLists.leafFaces[leafIndex][i]);\n }\n return faces;\n}\n\nfunction traverse(\n map: BspMap,\n nodeIndex: number,\n camera: Vec3,\n frustum: readonly FrustumPlane[],\n viewCluster: number,\n visibleFaces: VisibleFace[],\n visitedFaces: Set<number>\n): void {\n if (childIsLeaf(nodeIndex)) {\n const leafIndex = childLeafIndex(nodeIndex);\n const leaf = map.leafs[leafIndex];\n if (!isClusterVisible(map.visibility, viewCluster, leaf.cluster)) {\n return;\n }\n if (!leafIntersectsFrustum(leaf, frustum)) {\n return;\n }\n const center = {\n x: (leaf.mins[0] + leaf.maxs[0]) * 0.5,\n y: (leaf.mins[1] + leaf.maxs[1]) * 0.5,\n z: (leaf.mins[2] + leaf.maxs[2]) * 0.5,\n };\n const dx = center.x - camera.x;\n const dy = center.y - camera.y;\n const dz = center.z - camera.z;\n const leafSortKey = -(dx * dx + dy * dy + dz * dz);\n for (const faceIndex of collectFacesFromLeaf(map, leafIndex)) {\n if (visitedFaces.has(faceIndex)) {\n continue;\n }\n visitedFaces.add(faceIndex);\n visibleFaces.push({ faceIndex, leafIndex, sortKey: leafSortKey });\n }\n return;\n }\n\n const node = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, camera);\n const nearChild = dist >= 0 ? node.children[0] : node.children[1];\n const farChild = dist >= 0 ? node.children[1] : node.children[0];\n\n if (boxIntersectsFrustum(\n { x: node.mins[0], y: node.mins[1], z: node.mins[2] },\n { x: node.maxs[0], y: node.maxs[1], z: node.maxs[2] },\n frustum,\n )) {\n traverse(map, nearChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n traverse(map, farChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n }\n}\n\nexport function gatherVisibleFaces(\n map: BspMap,\n cameraPosition: Vec3,\n frustum: readonly FrustumPlane[],\n): VisibleFace[] {\n const viewLeaf = findLeafForPoint(map, cameraPosition);\n const viewCluster = viewLeaf >= 0 ? map.leafs[viewLeaf].cluster : -1;\n const visibleFaces: VisibleFace[] = [];\n const visitedFaces = new Set<number>();\n traverse(map, 0, cameraPosition, frustum, viewCluster, visibleFaces, visitedFaces);\n return visibleFaces;\n}\n","import {\n SURF_FLOWING,\n SURF_NONE,\n SURF_SKY,\n SURF_TRANS33,\n SURF_TRANS66,\n SURF_WARP,\n type SurfaceFlag,\n} from '@quake2ts/shared';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface SurfaceRenderState {\n readonly alpha: number;\n readonly blend: boolean;\n readonly depthWrite: boolean;\n readonly warp: boolean;\n readonly flowOffset: readonly [number, number];\n readonly sky: boolean;\n}\n\nexport interface BspSurfaceBindOptions {\n readonly modelViewProjection: Float32List;\n readonly styleIndices?: readonly number[];\n readonly styleValues?: ReadonlyArray<number>;\n readonly diffuseSampler?: number;\n readonly lightmapSampler?: number;\n readonly surfaceFlags?: SurfaceFlag;\n readonly timeSeconds?: number;\n}\n\nexport const BSP_SURFACE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec2 a_lightmapCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec2 u_texScroll;\nuniform vec2 u_lightmapScroll;\n\nout vec2 v_texCoord;\nout vec2 v_lightmapCoord;\n\nvec2 applyScroll(vec2 uv, vec2 scroll) {\n return uv + scroll;\n}\n\nvoid main() {\n v_texCoord = applyScroll(a_texCoord, u_texScroll);\n v_lightmapCoord = applyScroll(a_lightmapCoord, u_lightmapScroll);\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const BSP_SURFACE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec2 v_lightmapCoord;\n\nuniform sampler2D u_diffuseMap;\nuniform sampler2D u_lightmapAtlas;\nuniform vec4 u_lightStyleFactors;\nuniform float u_alpha;\nuniform bool u_applyLightmap;\nuniform bool u_warp;\nuniform float u_time;\n\nout vec4 o_color;\n\nvec2 warpCoords(vec2 uv) {\n // Quake II warp applies a subtle sinusoidal offset; we mirror the rerelease scale.\n if (!u_warp) {\n return uv;\n }\n float s = uv.x + sin(uv.y * 0.125 + u_time) * 0.125;\n float t = uv.y + sin(uv.x * 0.125 + u_time) * 0.125;\n return vec2(s, t);\n}\n\nvoid main() {\n vec2 warpedTex = warpCoords(v_texCoord);\n vec4 base = texture(u_diffuseMap, warpedTex);\n\n if (u_applyLightmap) {\n vec3 light = texture(u_lightmapAtlas, warpCoords(v_lightmapCoord)).rgb;\n float styleScale = dot(u_lightStyleFactors, vec4(1.0));\n base.rgb *= light * styleScale;\n }\n\n o_color = vec4(base.rgb, base.a * u_alpha);\n}`;\n\nconst DEFAULT_STYLE_INDICES: readonly number[] = [0, 255, 255, 255];\n\nexport function resolveLightStyles(\n styleIndices: readonly number[] = DEFAULT_STYLE_INDICES,\n styleValues: ReadonlyArray<number> = []\n): Float32Array {\n const factors = new Float32Array(4);\n for (let i = 0; i < 4; i += 1) {\n const styleIndex = styleIndices[i] ?? 255;\n if (styleIndex === 255) {\n factors[i] = 0;\n continue;\n }\n const value = styleValues[styleIndex];\n factors[i] = value !== undefined ? value : 1;\n }\n return factors;\n}\n\nfunction computeFlowOffset(timeSeconds: number): readonly [number, number] {\n const cycle = (timeSeconds * 0.25) % 1;\n // Match Quake II's negative scroll direction for flowing water/conveyors.\n return [-cycle, 0];\n}\n\nexport function deriveSurfaceRenderState(\n surfaceFlags: SurfaceFlag = SURF_NONE,\n timeSeconds = 0\n): SurfaceRenderState {\n const flowing = (surfaceFlags & SURF_FLOWING) !== 0;\n const warp = (surfaceFlags & SURF_WARP) !== 0;\n const sky = (surfaceFlags & SURF_SKY) !== 0;\n const trans33 = (surfaceFlags & SURF_TRANS33) !== 0;\n const trans66 = (surfaceFlags & SURF_TRANS66) !== 0;\n\n const alpha = trans33 ? 0.33 : trans66 ? 0.66 : 1;\n const blend = trans33 || trans66;\n const depthWrite = !blend && !sky;\n const flowOffset: readonly [number, number] = flowing ? computeFlowOffset(timeSeconds) : [0, 0];\n\n return {\n alpha,\n blend,\n depthWrite,\n warp,\n flowOffset,\n sky,\n };\n}\n\nexport class BspSurfacePipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTexScroll: WebGLUniformLocation | null;\n private readonly uniformLmScroll: WebGLUniformLocation | null;\n private readonly uniformLightStyles: WebGLUniformLocation | null;\n private readonly uniformAlpha: WebGLUniformLocation | null;\n private readonly uniformApplyLightmap: WebGLUniformLocation | null;\n private readonly uniformWarp: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n private readonly uniformLightmap: WebGLUniformLocation | null;\n private readonly uniformTime: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: BSP_SURFACE_VERTEX_SOURCE, fragment: BSP_SURFACE_FRAGMENT_SOURCE },\n { a_position: 0, a_texCoord: 1, a_lightmapCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTexScroll = this.program.getUniformLocation('u_texScroll');\n this.uniformLmScroll = this.program.getUniformLocation('u_lightmapScroll');\n this.uniformLightStyles = this.program.getUniformLocation('u_lightStyleFactors');\n this.uniformAlpha = this.program.getUniformLocation('u_alpha');\n this.uniformApplyLightmap = this.program.getUniformLocation('u_applyLightmap');\n this.uniformWarp = this.program.getUniformLocation('u_warp');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n this.uniformLightmap = this.program.getUniformLocation('u_lightmapAtlas');\n this.uniformTime = this.program.getUniformLocation('u_time');\n }\n\n bind(options: BspSurfaceBindOptions): SurfaceRenderState {\n const {\n modelViewProjection,\n styleIndices = DEFAULT_STYLE_INDICES,\n styleValues = [],\n diffuseSampler = 0,\n lightmapSampler = 1,\n surfaceFlags = SURF_NONE,\n timeSeconds = 0,\n } = options;\n\n const state = deriveSurfaceRenderState(surfaceFlags, timeSeconds);\n const styles = resolveLightStyles(styleIndices, styleValues);\n\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform2f(this.uniformTexScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform2f(this.uniformLmScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform4fv(this.uniformLightStyles, styles);\n this.gl.uniform1f(this.uniformAlpha, state.alpha);\n this.gl.uniform1i(this.uniformApplyLightmap, state.sky ? 0 : 1);\n this.gl.uniform1i(this.uniformWarp, state.warp ? 1 : 0);\n this.gl.uniform1f(this.uniformTime, timeSeconds);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n this.gl.uniform1i(this.uniformLightmap, lightmapSampler);\n\n return state;\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n\nexport function applySurfaceState(gl: WebGL2RenderingContext, state: SurfaceRenderState): void {\n gl.depthMask(state.depthWrite);\n if (state.blend) {\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n } else {\n gl.disable(gl.BLEND);\n }\n}\n","import { ShaderProgram } from './shaderProgram.js';\nimport { TextureCubeMap, VertexArray, VertexBuffer, type VertexAttributeLayout } from './resources.js';\n\nconst SKYBOX_POSITIONS = new Float32Array([\n // Front\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n -1, -1, 1,\n 1, 1, 1,\n -1, 1, 1,\n // Back\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n -1, -1, -1,\n 1, 1, -1,\n 1, -1, -1,\n // Left\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, 1,\n -1, -1, -1,\n -1, 1, 1,\n -1, 1, -1,\n // Right\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n 1, 1, 1,\n 1, -1, 1,\n // Top\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, 1,\n -1, 1, -1,\n 1, 1, 1,\n 1, 1, -1,\n // Bottom\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n 1, -1, 1,\n -1, -1, 1,\n]);\n\nexport const SKYBOX_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\n\nuniform mat4 u_viewProjectionNoTranslation;\nuniform vec2 u_scroll;\n\nout vec3 v_direction;\n\nvoid main() {\n vec3 dir = normalize(a_position);\n dir.xy += u_scroll;\n v_direction = dir;\n gl_Position = u_viewProjectionNoTranslation * vec4(a_position, 1.0);\n}`;\n\nexport const SKYBOX_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec3 v_direction;\nuniform samplerCube u_skybox;\n\nout vec4 o_color;\n\nvoid main() {\n o_color = texture(u_skybox, v_direction);\n}`;\n\nexport interface SkyboxBindOptions {\n readonly viewProjection: Float32List;\n readonly scroll: readonly [number, number];\n readonly textureUnit?: number;\n}\n\nexport class SkyboxPipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly vao: VertexArray;\n readonly vbo: VertexBuffer;\n readonly cubemap: TextureCubeMap;\n\n private readonly uniformViewProj: WebGLUniformLocation | null;\n private readonly uniformScroll: WebGLUniformLocation | null;\n private readonly uniformSampler: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: SKYBOX_VERTEX_SHADER, fragment: SKYBOX_FRAGMENT_SHADER },\n { a_position: 0 }\n );\n\n this.vao = new VertexArray(gl);\n this.vbo = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.vbo.upload(SKYBOX_POSITIONS, gl.STATIC_DRAW);\n\n const layout: VertexAttributeLayout[] = [{ index: 0, size: 3, type: gl.FLOAT, stride: 12, offset: 0 }];\n this.vao.configureAttributes(layout, this.vbo);\n\n this.uniformViewProj = this.program.getUniformLocation('u_viewProjectionNoTranslation');\n this.uniformScroll = this.program.getUniformLocation('u_scroll');\n this.uniformSampler = this.program.getUniformLocation('u_skybox');\n\n this.cubemap = new TextureCubeMap(gl);\n this.cubemap.setParameters({\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n });\n }\n\n bind(options: SkyboxBindOptions): void {\n const { viewProjection, scroll, textureUnit = 0 } = options;\n this.program.use();\n this.gl.depthMask(false);\n this.gl.uniformMatrix4fv(this.uniformViewProj, false, viewProjection);\n this.gl.uniform2f(this.uniformScroll, scroll[0], scroll[1]);\n this.gl.uniform1i(this.uniformSampler, textureUnit);\n this.cubemap.bind(textureUnit);\n this.vao.bind();\n }\n\n draw(): void {\n this.gl.drawArrays(this.gl.TRIANGLES, 0, SKYBOX_POSITIONS.length / 3);\n }\n\n dispose(): void {\n this.vbo.dispose();\n this.vao.dispose();\n this.cubemap.dispose();\n this.program.dispose();\n }\n}\n\nexport function removeViewTranslation(viewMatrix: Float32Array): Float32Array {\n const noTranslation = viewMatrix.slice();\n noTranslation[12] = 0;\n noTranslation[13] = 0;\n noTranslation[14] = 0;\n return noTranslation;\n}\n\nexport function computeSkyScroll(timeSeconds: number, scrollSpeeds: readonly [number, number] = [0.01, 0.02]): [number, number] {\n const [sx, sy] = scrollSpeeds;\n return [sx * timeSeconds, sy * timeSeconds];\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { Md2Model } from '../assets/md2.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md2DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md2Geometry {\n readonly vertices: readonly Md2DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md2FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md2BindOptions {\n readonly modelViewProjection: Float32List;\n readonly lightDirection?: readonly [number, number, number];\n readonly tint?: readonly [number, number, number, number];\n readonly diffuseSampler?: number;\n}\n\nexport const MD2_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec3 u_lightDir;\n\nout vec2 v_texCoord;\nout float v_light;\n\nvoid main() {\n vec3 normal = normalize(a_normal);\n v_light = max(dot(normal, normalize(u_lightDir)), 0.0);\n v_texCoord = a_texCoord;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD2_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin float v_light;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_light, albedo.a);\n}`;\n\nfunction normalizeVec3(v: Vec3): Vec3 {\n const lengthSq = v.x * v.x + v.y * v.y + v.z * v.z;\n if (lengthSq <= 0) {\n return { x: 0, y: 0, z: 1 };\n }\n const inv = 1 / Math.sqrt(lengthSq);\n return { x: v.x * inv, y: v.y * inv, z: v.z * inv };\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return {\n x: lerp(a.x, b.x, t),\n y: lerp(a.y, b.y, t),\n z: lerp(a.z, b.z, t),\n };\n}\n\nfunction normalizeUv(s: number, t: number, header: Md2Model['header']): readonly [number, number] {\n return [s / header.skinWidth, 1 - t / header.skinHeight];\n}\n\nexport function buildMd2Geometry(model: Md2Model): Md2Geometry {\n if (model.glCommands.length === 0) {\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n model.triangles.forEach((triangle) => {\n const baseIndex = vertices.length;\n for (let i = 0; i < 3; i += 1) {\n const vertexIndex = triangle.vertexIndices[i];\n const texCoordIndex = triangle.texCoordIndices[i];\n const texCoord = model.texCoords[texCoordIndex];\n vertices.push({\n vertexIndex,\n texCoord: normalizeUv(texCoord.s, texCoord.t, model.header),\n });\n }\n indices.push(baseIndex, baseIndex + 1, baseIndex + 2);\n });\n\n return { vertices, indices: new Uint16Array(indices) };\n }\n\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const command of model.glCommands) {\n const start = vertices.length;\n vertices.push(\n ...command.vertices.map((vertex) => ({\n vertexIndex: vertex.vertexIndex,\n texCoord: [vertex.s, 1 - vertex.t] as const,\n }))\n );\n\n if (command.mode === 'strip') {\n for (let i = 0; i < command.vertices.length - 2; i += 1) {\n const even = i % 2 === 0;\n const a = start + i + (even ? 0 : 1);\n const b = start + i + (even ? 1 : 0);\n const c = start + i + 2;\n indices.push(a, b, c);\n }\n } else {\n for (let i = 1; i < command.vertices.length - 1; i += 1) {\n indices.push(start, start + i, start + i + 1);\n }\n }\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nexport function buildMd2VertexData(\n model: Md2Model,\n geometry: Md2Geometry,\n blend: Md2FrameBlend\n): Float32Array {\n const { currentFrame, nextFrame, lerp } = blend;\n const frameA = model.frames[currentFrame];\n const frameB = model.frames[nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD2 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 8);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA.vertices[vertex.vertexIndex];\n const vB = frameB.vertices[vertex.vertexIndex];\n if (!vA || !vB) {\n throw new Error('MD2 vertex index out of range for frame');\n }\n\n const position = lerpVec3(vA.position, vB.position, lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, lerp));\n\n const base = index * 8;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n });\n\n return data;\n}\n\nexport class Md2MeshBuffers {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md2Geometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, model: Md2Model, blend: Md2FrameBlend) {\n this.gl = gl;\n this.geometry = buildMd2Geometry(model);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 32, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 32, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 32, offset: 24 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(model, blend);\n }\n\n update(model: Md2Model, blend: Md2FrameBlend): void {\n const data = buildMd2VertexData(model, this.geometry, blend);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md2Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformLightDir: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD2_VERTEX_SHADER, fragment: MD2_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformLightDir = this.program.getUniformLocation('u_lightDir');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(options: Md2BindOptions): void {\n const { modelViewProjection, lightDirection = [0, 0, 1], tint = [1, 1, 1, 1], diffuseSampler = 0 } = options;\n const lightVec = new Float32Array(lightDirection);\n const tintVec = new Float32Array(tint);\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform3fv(this.uniformLightDir, lightVec);\n this.gl.uniform4fv(this.uniformTint, tintVec);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n }\n\n draw(mesh: Md2MeshBuffers): void {\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\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 Md3Loader,\n Md3ParseError,\n parseMd3,\n type Md3Frame,\n type Md3Model,\n type Md3Surface,\n} from './assets/md3.js';\nexport {\n advanceAnimation,\n computeFrameBlend,\n createAnimationState,\n interpolateVec3,\n type AnimationSequence,\n type AnimationState,\n type FrameBlend,\n} from './assets/animation.js';\nexport { parseWal, type WalTexture } from './assets/wal.js';\nexport { parsePcx, pcxToRgba, type PcxImage } from './assets/pcx.js';\nexport {\n parseWalTexture,\n preparePcxTexture,\n TextureCache,\n walToRgba,\n type PreparedTexture,\n type TextureLevel,\n} from './assets/texture.js';\nexport { parseWav, type WavData } from './assets/wav.js';\nexport { decodeOgg, type OggAudio } from './assets/ogg.js';\nexport { AudioRegistry, AudioRegistryError, type DecodedAudio } from './assets/audio.js';\nexport { PakIndexStore, type StoredPakIndex } from './assets/pakIndexStore.js';\nexport {\n PakValidationError,\n PakValidator,\n RERELEASE_KNOWN_PAKS,\n type KnownPakChecksum,\n type PakValidationOutcome,\n} from './assets/pakValidation.js';\nexport {\n AssetDependencyError,\n AssetDependencyTracker,\n AssetManager,\n type AssetManagerOptions,\n} from './assets/manager.js';\nexport {\n ATTN_IDLE,\n ATTN_LOOP_NONE,\n ATTN_NONE,\n ATTN_NORM,\n ATTN_STATIC,\n MAX_SOUND_CHANNELS,\n SOUND_FULLVOLUME,\n SOUND_LOOP_ATTENUATE,\n SoundChannel,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n} from './audio/constants.js';\nexport {\n AudioContextController,\n createAudioGraph,\n type AudioBufferLike,\n type AudioContextLike,\n type AudioGraph,\n type AudioNodeLike,\n type GainNodeLike,\n type BiquadFilterNodeLike,\n type PannerNodeLike,\n} from './audio/context.js';\nexport { SoundRegistry } from './audio/registry.js';\nexport { SoundPrecache, type SoundPrecacheOptions, type SoundPrecacheReport } from './audio/precache.js';\nexport { AudioSystem, type AudioSystemOptions, type SoundRequest } from './audio/system.js';\nexport { spatializeOrigin, type ListenerState, type SpatializationResult } from './audio/spatialization.js';\nexport { createInitialChannels, pickChannel, type ChannelState } from './audio/channels.js';\nexport { MusicSystem, type MusicSystemOptions, type MusicState, type AudioElementLike } from './audio/music.js';\nexport { AudioApi, type AudioApiOptions } from './audio/api.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 TextureCubeMap,\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';\nexport { extractFrustumPlanes, boxIntersectsFrustum, type FrustumPlane } from './render/culling.js';\nexport { findLeafForPoint, gatherVisibleFaces, type VisibleFace } from './render/bspTraversal.js';\nexport {\n applySurfaceState,\n BspSurfacePipeline,\n BSP_SURFACE_FRAGMENT_SOURCE,\n BSP_SURFACE_VERTEX_SOURCE,\n deriveSurfaceRenderState,\n resolveLightStyles,\n type BspSurfaceBindOptions,\n type SurfaceRenderState,\n} from './render/bspPipeline.js';\nexport {\n SKYBOX_FRAGMENT_SHADER,\n SKYBOX_VERTEX_SHADER,\n SkyboxPipeline,\n computeSkyScroll,\n removeViewTranslation,\n} from './render/skybox.js';\nexport {\n MD2_FRAGMENT_SHADER,\n MD2_VERTEX_SHADER,\n Md2MeshBuffers,\n Md2Pipeline,\n buildMd2Geometry,\n buildMd2VertexData,\n type Md2BindOptions,\n type Md2FrameBlend,\n type Md2Geometry,\n type Md2DrawVertex,\n} from './render/md2Pipeline.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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\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 ServerFlags {\n None = 0,\n NoClient = 1 << 0,\n DeadMonster = 1 << 1,\n Monster = 1 << 2,\n Player = 1 << 3,\n Bot = 1 << 4,\n NoBots = 1 << 5,\n Respawning = 1 << 6,\n Projectile = 1 << 7,\n Instanced = 1 << 8,\n Door = 1 << 9,\n NoCull = 1 << 10,\n Hull = 1 << 11,\n}\n\nexport enum EntityFlags {\n Fly = 1 << 0,\n Swim = 1 << 1,\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, activator?: 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 | 'inventory'\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 interface MonsterInfo {\n aiflags: number;\n}\n\nconst DEFAULT_MONSTER_INFO: MonsterInfo = Object.freeze({ aiflags: 0 });\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 killtarget?: string;\n team?: string;\n message?: string;\n pathtarget?: string;\n model?: string;\n item?: string;\n\n inventory: Record<string, number> = {};\n\n origin: Vec3 = copyVec3();\n old_origin: Vec3 = copyVec3();\n velocity: Vec3 = copyVec3();\n avelocity: Vec3 = copyVec3();\n angles: Vec3 = copyVec3();\n\n viewheight = 0;\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 movedir: Vec3 = copyVec3();\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 speed = 0;\n deadflag: DeadFlag = DeadFlag.Alive;\n count = 0;\n wait = 0;\n delay = 0;\n timestamp = 0;\n sounds = 0;\n noise_index = 0;\n fly_sound_debounce_time = 0;\n\n enemy: Entity | null = null;\n movetarget: Entity | null = null;\n target_ent: Entity | null = null;\n goalentity: Entity | null = null;\n ideal_yaw = 0;\n yaw_speed = 0;\n search_time = 0;\n attack_finished_time = 0;\n pain_finished_time = 0;\n trail_time = 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 activator: Entity | null = null;\n\n solid: Solid = Solid.Not;\n flags = 0;\n svflags = 0;\n\n monsterinfo: MonsterInfo = { ...DEFAULT_MONSTER_INFO };\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.killtarget = undefined;\n this.team = undefined;\n this.message = undefined;\n this.pathtarget = undefined;\n this.model = undefined;\n this.item = undefined;\n\n this.inventory = {};\n\n this.origin = copyVec3();\n this.old_origin = copyVec3();\n this.velocity = copyVec3();\n this.avelocity = copyVec3();\n this.angles = copyVec3();\n this.viewheight = 0;\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 this.movedir = copyVec3();\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.speed = 0;\n this.deadflag = DeadFlag.Alive;\n this.count = 0;\n this.wait = 0;\n this.delay = 0;\n this.timestamp = 0;\n this.sounds = 0;\n this.noise_index = 0;\n this.fly_sound_debounce_time = 0;\n\n this.enemy = null;\n this.movetarget = null;\n this.target_ent = null;\n this.goalentity = null;\n this.ideal_yaw = 0;\n this.yaw_speed = 0;\n this.search_time = 0;\n this.attack_finished_time = 0;\n this.pain_finished_time = 0;\n this.trail_time = 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 this.activator = null;\n\n this.solid = Solid.Not;\n this.flags = 0;\n this.svflags = 0;\n\n this.monsterinfo = { ...DEFAULT_MONSTER_INFO };\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: 'killtarget', type: 'string', save: true },\n { name: 'team', type: 'string', save: true },\n { name: 'message', type: 'string', save: true },\n { name: 'pathtarget', type: 'string', save: true },\n { name: 'model', type: 'string', save: true },\n { name: 'item', type: 'string', save: true },\n { name: 'inventory', type: 'inventory', 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: 'viewheight', type: 'int', 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: 'movedir', type: 'vec3', 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: 'speed', type: 'float', save: true },\n { name: 'deadflag', type: 'int', save: true },\n { name: 'count', type: 'int', save: true },\n { name: 'wait', type: 'float', save: true },\n { name: 'delay', type: 'float', save: true },\n { name: 'timestamp', type: 'float', save: true },\n { name: 'sounds', type: 'int', save: true },\n { name: 'noise_index', type: 'int', save: true },\n { name: 'fly_sound_debounce_time', type: 'float', save: true },\n { name: 'enemy', type: 'entity', save: true },\n { name: 'movetarget', type: 'entity', save: true },\n { name: 'target_ent', 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: 'search_time', type: 'float', save: true },\n { name: 'attack_finished_time', type: 'float', save: true },\n { name: 'pain_finished_time', type: 'float', save: true },\n { name: 'trail_time', 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 interface EntityPoolSnapshot {\n readonly capacity: number;\n readonly activeOrder: readonly number[];\n readonly freeList: readonly number[];\n readonly pendingFree: readonly number[];\n}\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 freeImmediate(entity: Entity): void {\n if (entity.index === WORLD_INDEX) {\n throw new Error('Cannot free world entity');\n }\n\n if (!entity.inUse) {\n return;\n }\n\n this.unlink(entity);\n entity.reset();\n this.freeList.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 createSnapshot(): EntityPoolSnapshot {\n const activeOrder = Array.from(this, (entity) => entity.index);\n return {\n capacity: this.entities.length,\n activeOrder,\n freeList: [...this.freeList],\n pendingFree: [...this.pendingFree],\n };\n }\n\n restore(snapshot: EntityPoolSnapshot): void {\n if (snapshot.capacity !== this.entities.length) {\n throw new Error(`Snapshot capacity ${snapshot.capacity} does not match pool capacity ${this.entities.length}`);\n }\n\n const seen = new Set<number>();\n const noteIndex = (index: number, label: string) => {\n if (index < 0 || index >= this.entities.length) {\n throw new Error(`Invalid entity index ${index} in ${label}`);\n }\n if (seen.has(index)) {\n throw new Error(`Duplicate entity index ${index} in snapshot`);\n }\n seen.add(index);\n };\n\n for (const index of snapshot.activeOrder) {\n noteIndex(index, 'activeOrder');\n }\n for (const index of snapshot.freeList) {\n noteIndex(index, 'freeList');\n }\n for (const index of snapshot.pendingFree) {\n noteIndex(index, 'pendingFree');\n }\n\n this.activeHead = null;\n this.freeList.length = 0;\n this.pendingFree.length = 0;\n\n for (const entity of this.entities) {\n entity.reset();\n }\n\n for (let i = snapshot.activeOrder.length - 1; i >= 0; i -= 1) {\n const entity = this.entities[snapshot.activeOrder[i]];\n entity.inUse = true;\n this.link(entity);\n }\n\n for (const index of snapshot.pendingFree) {\n const entity = this.entities[index];\n entity.inUse = false;\n entity.freePending = true;\n entity.linkNext = null;\n entity.linkPrevious = null;\n this.pendingFree.push(index);\n }\n\n for (const index of snapshot.freeList) {\n const entity = this.entities[index];\n entity.inUse = false;\n entity.freePending = false;\n entity.linkNext = null;\n entity.linkPrevious = null;\n this.freeList.push(index);\n }\n\n if (!snapshot.activeOrder.includes(WORLD_INDEX)) {\n throw new Error('Snapshot must include the world entity as active');\n }\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 interface ThinkScheduleEntry {\n readonly time: number;\n readonly entityIndex: number;\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 snapshot(): ThinkScheduleEntry[] {\n return this.queue.map(({ time, entity }) => ({ time, entityIndex: entity.index }));\n }\n\n restore(entries: ThinkScheduleEntry[], resolver: (index: number) => Entity | undefined): void {\n this.queue.length = 0;\n for (const entry of entries) {\n const entity = resolver(entry.entityIndex);\n if (!entity) {\n continue;\n }\n this.schedule(entity, entry.time);\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 { createRandomGenerator } from '@quake2ts/shared';\nimport {\n DeadFlag,\n ENTITY_FIELD_METADATA,\n Entity,\n ServerFlags,\n type EntityFieldDescriptor,\n Solid,\n} from './entity.js';\nimport { EntityPool, type EntityPoolSnapshot } from './pool.js';\nimport { ThinkScheduler, type ThinkScheduleEntry } 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\ntype SerializableVec3 = readonly [number, number, number];\n\ntype SerializableInventory = Record<string, number>;\n\ntype SerializableEntityFieldValue =\n | number\n | string\n | boolean\n | null\n | SerializableVec3\n | SerializableInventory;\n\ntype SerializableFieldName = Exclude<\n (typeof ENTITY_FIELD_METADATA)[number]['name'],\n 'think' | 'touch' | 'use' | 'pain' | 'die' | 'index'\n>;\ntype SerializableFieldDescriptor = EntityFieldDescriptor<SerializableFieldName>;\n\nconst SERIALIZABLE_FIELDS = ENTITY_FIELD_METADATA.filter(\n (field) => field.save,\n) as SerializableFieldDescriptor[];\nconst DESCRIPTORS = new Map(SERIALIZABLE_FIELDS.map((descriptor) => [descriptor.name, descriptor]));\n\nexport interface SerializedEntityState {\n readonly index: number;\n readonly fields: Partial<Record<SerializableFieldName, SerializableEntityFieldValue>>;\n}\n\nexport interface EntitySystemSnapshot {\n readonly timeSeconds: number;\n readonly pool: EntityPoolSnapshot;\n readonly entities: SerializedEntityState[];\n readonly thinks: ThinkScheduleEntry[];\n}\n\n\nfunction serializeVec3(vec: Vec3): SerializableVec3 {\n return [vec.x, vec.y, vec.z];\n}\n\nfunction deserializeVec3(value: SerializableEntityFieldValue): Vec3 {\n const vec = value as SerializableVec3;\n if (!Array.isArray(vec) || vec.length !== 3) {\n throw new Error('Invalid vec3 serialization');\n }\n const [x, y, z] = vec;\n return { x, y, z };\n}\n\nfunction assignField(entity: Entity, name: SerializableFieldName, value: Entity[SerializableFieldName]): void {\n (entity as Record<SerializableFieldName, Entity[SerializableFieldName]>)[name] = value;\n}\n\nfunction serializeInventory(inventory: Record<string, number>): SerializableInventory {\n return { ...inventory };\n}\n\nfunction deserializeInventory(value: SerializableEntityFieldValue): Record<string, number> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Invalid inventory serialization');\n }\n\n const parsed: Record<string, number> = {};\n for (const [key, entry] of Object.entries(value)) {\n parsed[key] = Number(entry);\n }\n return parsed;\n}\n\nexport class EntitySystem {\n private readonly pool: EntityPool;\n private readonly thinkScheduler: ThinkScheduler;\n private readonly targetNameIndex = new Map<string, Set<Entity>>();\n private readonly random = createRandomGenerator();\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.unregisterTarget(entity);\n this.thinkScheduler.cancel(entity);\n this.pool.deferFree(entity);\n }\n\n freeImmediate(entity: Entity): void {\n this.unregisterTarget(entity);\n this.thinkScheduler.cancel(entity);\n this.pool.freeImmediate(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 finalizeSpawn(entity: Entity): void {\n if (!entity.inUse || entity.freePending) {\n return;\n }\n this.registerTarget(entity);\n }\n\n findByClassname(classname: string): Entity[] {\n const matches: Entity[] = [];\n for (const entity of this.pool) {\n if (entity.classname === classname && entity.inUse && !entity.freePending) {\n matches.push(entity);\n }\n }\n return matches;\n }\n\n findByTargetName(targetname: string): Entity[] {\n const matches = this.targetNameIndex.get(targetname);\n if (!matches) {\n return [];\n }\n return Array.from(matches).filter((entity) => entity.inUse && !entity.freePending);\n }\n\n pickTarget(targetname: string | undefined): Entity | null {\n if (!targetname) {\n return null;\n }\n const matches = this.findByTargetName(targetname);\n if (matches.length === 0) {\n return null;\n }\n const choice = this.random.randomIndex(matches);\n return matches[choice] ?? null;\n }\n\n killBox(entity: Entity): void {\n const targetBounds = computeBounds(entity);\n for (const other of this.pool) {\n if (other === entity || other === this.pool.world) {\n continue;\n }\n if (!other.inUse || other.freePending || other.solid === Solid.Not) {\n continue;\n }\n if (other.svflags & ServerFlags.DeadMonster) {\n continue;\n }\n if (!boundsIntersect(targetBounds, computeBounds(other))) {\n continue;\n }\n other.health = 0;\n other.deadflag = DeadFlag.Dead;\n this.free(other);\n }\n }\n\n useTargets(entity: Entity, activator: Entity | null = null): void {\n if (entity.delay > 0) {\n const delayed = this.spawn();\n delayed.classname = 'DelayedUse';\n delayed.target = entity.target;\n delayed.killtarget = entity.killtarget;\n delayed.message = entity.message;\n delayed.think = (self) => {\n this.useTargetsImmediate(self, activator ?? entity);\n this.free(self);\n };\n this.scheduleThink(delayed, this.currentTimeSeconds + entity.delay);\n return;\n }\n\n this.useTargetsImmediate(entity, activator ?? entity);\n }\n\n runFrame(): void {\n this.thinkScheduler.runDueThinks(this.currentTimeSeconds);\n this.runTouches();\n this.pool.flushFreeList();\n }\n\n createSnapshot(): EntitySystemSnapshot {\n const entities: SerializedEntityState[] = [];\n for (const entity of this.pool) {\n const fields: Partial<Record<SerializableFieldName, SerializableEntityFieldValue>> = {};\n for (const descriptor of SERIALIZABLE_FIELDS) {\n const value = entity[descriptor.name];\n switch (descriptor.type) {\n case 'vec3':\n fields[descriptor.name] = serializeVec3(value as Vec3);\n break;\n case 'entity':\n fields[descriptor.name] = (value as Entity | null)?.index ?? null;\n break;\n case 'inventory':\n fields[descriptor.name] = serializeInventory(value as Record<string, number>);\n break;\n default:\n fields[descriptor.name] = (value as SerializableEntityFieldValue) ?? null;\n break;\n }\n }\n entities.push({\n index: entity.index,\n fields,\n });\n }\n\n return {\n timeSeconds: this.currentTimeSeconds,\n pool: this.pool.createSnapshot(),\n entities,\n thinks: this.thinkScheduler.snapshot(),\n };\n }\n\n restore(snapshot: EntitySystemSnapshot): void {\n this.currentTimeSeconds = snapshot.timeSeconds;\n this.pool.restore(snapshot.pool);\n\n const indexToEntity = new Map<number, Entity>();\n for (const entity of this.pool) {\n indexToEntity.set(entity.index, entity);\n }\n\n const pendingEntityRefs: Array<{ entity: Entity; name: SerializableFieldName; targetIndex: number | null }>\n = [];\n\n for (const serialized of snapshot.entities) {\n const entity = indexToEntity.get(serialized.index);\n if (!entity) {\n continue;\n }\n\n for (const [name, value] of Object.entries(serialized.fields) as [\n SerializableFieldName,\n SerializableEntityFieldValue,\n ][]) {\n const descriptor = DESCRIPTORS.get(name);\n if (!descriptor || value === undefined) {\n continue;\n }\n\n switch (descriptor.type) {\n case 'vec3':\n assignField(entity, name, deserializeVec3(value) as Entity[typeof name]);\n break;\n case 'entity':\n pendingEntityRefs.push({\n entity,\n name: descriptor.name,\n targetIndex: value as number | null,\n });\n break;\n case 'inventory':\n assignField(entity, name, deserializeInventory(value) as Entity[typeof name]);\n break;\n case 'boolean':\n assignField(entity, name, Boolean(value) as Entity[typeof name]);\n break;\n default:\n assignField(entity, name, value as Entity[typeof name]);\n break;\n }\n }\n }\n\n for (const ref of pendingEntityRefs) {\n const target = ref.targetIndex === null ? null : indexToEntity.get(ref.targetIndex) ?? null;\n assignField(ref.entity, ref.name, target as Entity[SerializableFieldName]);\n }\n\n this.thinkScheduler.restore(snapshot.thinks, (index) => indexToEntity.get(index));\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 || entity.solid === Solid.Not) {\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 private registerTarget(entity: Entity): void {\n if (!entity.targetname) {\n return;\n }\n let bucket = this.targetNameIndex.get(entity.targetname);\n if (!bucket) {\n bucket = new Set<Entity>();\n this.targetNameIndex.set(entity.targetname, bucket);\n }\n bucket.add(entity);\n }\n\n private unregisterTarget(entity: Entity): void {\n if (!entity.targetname) {\n return;\n }\n const bucket = this.targetNameIndex.get(entity.targetname);\n if (!bucket) {\n return;\n }\n bucket.delete(entity);\n if (bucket.size === 0) {\n this.targetNameIndex.delete(entity.targetname);\n }\n }\n\n private useTargetsImmediate(entity: Entity, activator: Entity | null): void {\n if (entity.target) {\n for (const target of this.findByTargetName(entity.target)) {\n if (target === entity) {\n continue;\n }\n target.use?.(target, entity, activator);\n }\n }\n\n if (entity.killtarget) {\n for (const victim of this.findByTargetName(entity.killtarget)) {\n if (victim === entity) {\n continue;\n }\n this.free(victim);\n }\n }\n }\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { angleVectors, ZERO_VEC3 } from '@quake2ts/shared';\n\nconst VEC_UP: Vec3 = { x: 0, y: -1, z: 0 } as const;\nconst MOVEDIR_UP: Vec3 = { x: 0, y: 0, z: 1 } as const;\nconst VEC_DOWN: Vec3 = { x: 0, y: -2, z: 0 } as const;\nconst MOVEDIR_DOWN: Vec3 = { x: 0, y: 0, z: -1 } as const;\n\nfunction vecEquals(a: Vec3, b: Vec3): boolean {\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nexport function isZeroVector(vector: Vec3): boolean {\n return vecEquals(vector, ZERO_VEC3 as Vec3);\n}\n\nexport function setMovedir(angles: Vec3): Vec3 {\n if (vecEquals(angles, VEC_UP)) {\n return { ...MOVEDIR_UP };\n }\n if (vecEquals(angles, VEC_DOWN)) {\n return { ...MOVEDIR_DOWN };\n }\n return { ...angleVectors(angles).forward };\n}\n","import { angleVectors } from '@quake2ts/shared';\nimport { EntityFlags, MoveType, ServerFlags, Solid, type Entity, type TouchCallback } from './entity.js';\nimport type { SpawnRegistry } from './spawn.js';\nimport { isZeroVector, setMovedir } from './utils.js';\nimport type { EntitySystem } from './system.js';\n\nconst FRAME_TIME_SECONDS = 1 / 40;\nconst THINK_INTERVAL = 0.1;\nconst HURT_INTERVAL = 0.1;\n\nconst TRIGGER_SPAWNFLAGS = {\n Monster: 1 << 0,\n NotPlayer: 1 << 1,\n Triggered: 1 << 2,\n Toggle: 1 << 3,\n Latched: 1 << 4,\n Clip: 1 << 5,\n} as const;\n\nconst RELAY_SPAWNFLAGS = {\n NoSound: 1 << 0,\n} as const;\n\nconst COUNTER_SPAWNFLAGS = {\n NoMessage: 1 << 0,\n} as const;\n\nconst PUSH_SPAWNFLAGS = {\n Once: 1 << 0,\n Plus: 1 << 1,\n Silent: 1 << 2,\n StartOff: 1 << 3,\n Clip: 1 << 4,\n} as const;\n\nconst HURT_SPAWNFLAGS = {\n StartOff: 1 << 0,\n Toggle: 1 << 1,\n Silent: 1 << 2,\n NoProtection: 1 << 3,\n Slow: 1 << 4,\n NoPlayers: 1 << 5,\n NoMonsters: 1 << 6,\n Clip: 1 << 7,\n} as const;\n\nconst TELEPORT_SPAWNFLAGS = {\n StartOn: 1 << 3,\n} as const;\n\nconst GRAVITY_SPAWNFLAGS = {\n Toggle: 1 << 0,\n StartOff: 1 << 1,\n Clip: 1 << 2,\n} as const;\n\nconst MONSTERJUMP_SPAWNFLAGS = {\n Toggle: 1 << 0,\n StartOff: 1 << 1,\n Clip: 1 << 2,\n} as const;\n\nfunction trainResume(train: Entity, entities: EntitySystem): void {\n if (!train.think) {\n train.think = (self) => {\n self.nextthink = 0;\n };\n }\n entities.scheduleThink(train, entities.timeSeconds + FRAME_TIME_SECONDS);\n}\n\nfunction initTrigger(entity: Entity): void {\n entity.movetype = MoveType.None;\n entity.solid = Solid.Trigger;\n entity.svflags |= ServerFlags.NoClient;\n entity.movedir = setMovedir(entity.angles);\n entity.angles = { x: 0, y: 0, z: 0 };\n}\n\nfunction multiWait(self: Entity): void {\n self.nextthink = 0;\n self.think = undefined;\n}\n\nfunction canActivate(trigger: Entity, other: Entity): boolean {\n if (trigger.solid === Solid.Not) {\n return false;\n }\n if (other.svflags & ServerFlags.Player) {\n if (trigger.spawnflags & TRIGGER_SPAWNFLAGS.NotPlayer) {\n return false;\n }\n } else if (other.svflags & ServerFlags.Monster) {\n if ((trigger.spawnflags & TRIGGER_SPAWNFLAGS.Monster) === 0) {\n return false;\n }\n } else {\n return false;\n }\n\n if (!isZeroVector(trigger.movedir)) {\n const forward = angleVectors(other.angles).forward;\n const dot = forward.x * trigger.movedir.x + forward.y * trigger.movedir.y + forward.z * trigger.movedir.z;\n if (dot < 0) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction multiTrigger(self: Entity, entities: EntitySystem): void {\n if (self.nextthink > entities.timeSeconds) {\n return;\n }\n\n entities.useTargets(self, self.activator);\n\n if (self.wait > 0) {\n self.think = multiWait;\n entities.scheduleThink(self, entities.timeSeconds + self.wait);\n } else {\n self.touch = undefined;\n self.think = (entity) => {\n entities.free(entity);\n };\n entities.scheduleThink(self, entities.timeSeconds + FRAME_TIME_SECONDS);\n }\n}\n\nfunction touchMulti(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n if (!canActivate(self, other)) {\n return;\n }\n\n self.activator = other;\n multiTrigger(self, entities);\n}\n\nfunction useMulti(self: Entity, _other: Entity | null, activator: Entity | null, entities: EntitySystem): void {\n if (self.spawnflags & TRIGGER_SPAWNFLAGS.Toggle) {\n self.solid = self.solid === Solid.Trigger ? Solid.Not : Solid.Trigger;\n return;\n }\n self.activator = activator;\n multiTrigger(self, entities);\n}\n\nfunction triggerEnable(self: Entity): void {\n self.solid = Solid.Trigger;\n}\n\nfunction registerTriggerMultiple(registry: SpawnRegistry): void {\n registry.register('trigger_multiple', (entity, context) => {\n initTrigger(entity);\n\n if (entity.wait === 0) {\n entity.wait = 0.2;\n }\n\n if (entity.spawnflags & TRIGGER_SPAWNFLAGS.Latched) {\n // Latched triggers rely on area queries; fall back to touch behaviour for now.\n }\n\n if (entity.spawnflags & (TRIGGER_SPAWNFLAGS.Triggered | TRIGGER_SPAWNFLAGS.Toggle)) {\n entity.solid = Solid.Not;\n entity.use = (self, other, activator) => {\n triggerEnable(self);\n useMulti(self, other, activator ?? other, context.entities);\n };\n } else {\n entity.use = (self, other, activator) => useMulti(self, other, activator ?? other, context.entities);\n }\n\n entity.touch = (self, other) => touchMulti(self, other, context.entities);\n });\n}\n\nfunction registerTriggerOnce(registry: SpawnRegistry): void {\n registry.register('trigger_once', (entity, context) => {\n entity.wait = -1;\n registry.get('trigger_multiple')?.(entity, context);\n });\n}\n\nfunction registerTriggerRelay(registry: SpawnRegistry): void {\n registry.register('trigger_relay', (entity, context) => {\n if (entity.spawnflags & RELAY_SPAWNFLAGS.NoSound) {\n entity.noise_index = -1;\n }\n\n entity.use = (self, _other, activator) => {\n context.entities.useTargets(self, activator ?? self);\n };\n });\n}\n\nfunction registerTriggerAlways(registry: SpawnRegistry): void {\n registry.register('trigger_always', (entity, context) => {\n if (entity.delay === 0) {\n entity.delay = 0.2;\n }\n\n context.entities.useTargets(entity, entity);\n });\n}\n\nfunction counterUse(self: Entity, _other: Entity | null, activator: Entity | null, entities: EntitySystem): void {\n if (self.count === 0) {\n return;\n }\n\n self.count -= 1;\n\n if (self.count > 0) {\n return;\n }\n\n self.activator = activator;\n multiTrigger(self, entities);\n}\n\nfunction registerTriggerCounter(registry: SpawnRegistry): void {\n registry.register('trigger_counter', (entity, context) => {\n entity.wait = -1;\n if (entity.count === 0) {\n entity.count = 2;\n }\n\n entity.use = (self, other, activator) => counterUse(self, other, activator ?? other, context.entities);\n if (!(entity.spawnflags & COUNTER_SPAWNFLAGS.NoMessage)) {\n entity.message = entity.message ?? 'sequence complete';\n }\n });\n}\n\nfunction triggerKeyUse(self: Entity, activator: Entity | null, entities: EntitySystem, warn: (message: string) => void): void {\n if (!self.item || !activator) {\n return;\n }\n\n const available = activator.inventory[self.item] ?? 0;\n if (available <= 0) {\n if (self.timestamp > entities.timeSeconds) {\n return;\n }\n self.timestamp = entities.timeSeconds + 5;\n warn(`Missing required key item: ${self.item}`);\n return;\n }\n\n activator.inventory[self.item] = available - 1;\n if (activator.inventory[self.item] <= 0) {\n delete activator.inventory[self.item];\n }\n\n entities.useTargets(self, activator);\n self.use = undefined;\n}\n\nfunction registerTriggerKey(registry: SpawnRegistry): void {\n registry.register('trigger_key', (entity, context) => {\n const requiredItem = context.keyValues.item;\n if (!requiredItem) {\n context.warn('trigger_key requires an item');\n context.free(entity);\n return;\n }\n\n entity.item = requiredItem;\n entity.use = (self, other, activator) => triggerKeyUse(self, activator ?? other, context.entities, context.warn);\n });\n}\n\nfunction triggerPushTouch(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n\n\n if (other.classname === 'grenade' || other.health > 0) {\n const scale = (self.speed || 1000) * 10;\n other.velocity = {\n x: self.movedir.x * scale,\n y: self.movedir.y * scale,\n z: self.movedir.z * scale,\n };\n }\n\n if (self.spawnflags & PUSH_SPAWNFLAGS.Once) {\n entities.free(self);\n }\n}\n\nfunction toggleSolid(self: Entity): void {\n self.solid = self.solid === Solid.Not ? Solid.Trigger : Solid.Not;\n}\n\nfunction triggerPushInactive(self: Entity, entities: EntitySystem, touchHandler: TouchCallback): void {\n if (self.delay > entities.timeSeconds) {\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n return;\n }\n\n self.touch = touchHandler;\n self.think = (entity) => triggerPushActive(entity, entities, touchHandler);\n self.delay = entities.timeSeconds + self.wait;\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n}\n\nfunction triggerPushActive(self: Entity, entities: EntitySystem, touchHandler: TouchCallback): void {\n if (self.delay > entities.timeSeconds) {\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n return;\n }\n\n self.touch = undefined;\n self.think = (entity) => triggerPushInactive(entity, entities, touchHandler);\n self.delay = entities.timeSeconds + self.wait;\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n}\n\nfunction registerTriggerPush(registry: SpawnRegistry): void {\n registry.register('trigger_push', (entity, context) => {\n initTrigger(entity);\n\n const touchHandler: TouchCallback = (self, other) => triggerPushTouch(self, other, context.entities);\n entity.touch = touchHandler;\n\n if (!entity.speed) {\n entity.speed = 1000;\n }\n\n if (entity.spawnflags & PUSH_SPAWNFLAGS.Plus) {\n if (!entity.wait) {\n entity.wait = 10;\n }\n entity.delay = context.entities.timeSeconds + entity.wait;\n entity.think = (self) => triggerPushActive(self, context.entities, touchHandler);\n context.entities.scheduleThink(entity, context.entities.timeSeconds + THINK_INTERVAL);\n }\n\n if (entity.targetname) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n if (entity.spawnflags & PUSH_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n } else if (entity.spawnflags & PUSH_SPAWNFLAGS.StartOff) {\n context.warn('trigger_push is START_OFF but not targeted.');\n entity.touch = undefined;\n entity.solid = Solid.Bsp;\n entity.movetype = MoveType.Push;\n }\n });\n}\n\nfunction hurtTouch(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n if (!other.takedamage && other.classname !== 'grenade') {\n return;\n }\n if (self.spawnflags & HURT_SPAWNFLAGS.NoMonsters && (other.svflags & ServerFlags.Monster)) {\n return;\n }\n if (self.spawnflags & HURT_SPAWNFLAGS.NoPlayers && (other.svflags & ServerFlags.Player)) {\n return;\n }\n if (self.timestamp > entities.timeSeconds) {\n return;\n }\n\n self.timestamp = entities.timeSeconds + (self.spawnflags & HURT_SPAWNFLAGS.Slow ? 1 : HURT_INTERVAL);\n\n const damage = self.dmg || 5;\n other.health -= damage;\n}\n\nfunction registerTriggerHurt(registry: SpawnRegistry): void {\n registry.register('trigger_hurt', (entity, context) => {\n initTrigger(entity);\n\n entity.dmg = entity.dmg || 5;\n const touchHandler: TouchCallback = (self, other) => hurtTouch(self, other, context.entities);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & HURT_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & HURT_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nfunction teleportTouch(\n self: Entity,\n other: Entity | null,\n entities: EntitySystem,\n warn: (message: string) => void,\n): void {\n if (!other) {\n return;\n }\n if (self.delay > 0) {\n return;\n }\n\n const destination = entities.pickTarget(self.target);\n if (!destination) {\n warn('trigger_teleport target not found');\n return;\n }\n\n const destOrigin = {\n x: destination.origin.x,\n y: destination.origin.y,\n z: destination.origin.z + 10,\n } as const;\n\n other.origin = { ...destOrigin };\n other.old_origin = { ...destOrigin };\n other.velocity = { x: 0, y: 0, z: 0 };\n other.groundentity = null;\n other.angles = { ...destination.angles };\n\n entities.killBox(other);\n}\n\nfunction registerTriggerTeleport(registry: SpawnRegistry): void {\n registry.register('trigger_teleport', (entity, context) => {\n if (!entity.wait) {\n entity.wait = 0.2;\n }\n\n initTrigger(entity);\n\n if (entity.targetname) {\n entity.use = (self) => {\n self.delay = self.delay > 0 ? 0 : 1;\n };\n if ((entity.spawnflags & TELEPORT_SPAWNFLAGS.StartOn) === 0) {\n entity.delay = 1;\n }\n }\n\n entity.touch = (self, other) => teleportTouch(self, other, context.entities, context.warn);\n });\n}\n\nfunction gravityTouch(self: Entity, other: Entity | null): void {\n if (!other) {\n return;\n }\n\n if (self.spawnflags & GRAVITY_SPAWNFLAGS.Clip) {\n // Clipping requires a trace against world geometry, which is not yet available.\n // Fall back to bounding-box overlap behaviour.\n }\n\n other.gravity = self.gravity;\n}\n\nfunction registerTriggerGravity(registry: SpawnRegistry): void {\n registry.register('trigger_gravity', (entity, context) => {\n const gravityText = context.keyValues.gravity;\n if (!gravityText) {\n context.warn('trigger_gravity requires a gravity value');\n context.free(entity);\n return;\n }\n\n initTrigger(entity);\n entity.gravity = Number.parseFloat(gravityText) || 0;\n\n const touchHandler: TouchCallback = (self, other) => gravityTouch(self, other);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & GRAVITY_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & GRAVITY_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nfunction monsterJumpTouch(self: Entity, other: Entity | null): void {\n if (!other) {\n return;\n }\n\n if ((other.flags & (EntityFlags.Fly | EntityFlags.Swim)) !== 0) {\n return;\n }\n if (other.svflags & ServerFlags.DeadMonster) {\n return;\n }\n if ((other.svflags & ServerFlags.Monster) === 0) {\n return;\n }\n\n other.velocity = {\n x: self.movedir.x * self.speed,\n y: self.movedir.y * self.speed,\n z: other.velocity.z,\n };\n\n if (!other.groundentity) {\n return;\n }\n\n other.groundentity = null;\n other.velocity = { x: other.velocity.x, y: other.velocity.y, z: self.movedir.z };\n}\n\nfunction triggerElevatorUse(\n self: Entity,\n other: Entity | null,\n entities: EntitySystem,\n warn: (message: string) => void,\n): void {\n if (!self.movetarget) {\n return;\n }\n if (self.movetarget.nextthink > 0) {\n return;\n }\n\n if (!other?.pathtarget) {\n warn('trigger_elevator used with no pathtarget');\n return;\n }\n\n const target = entities.pickTarget(other.pathtarget);\n if (!target) {\n warn(`trigger_elevator used with bad pathtarget: ${other.pathtarget}`);\n return;\n }\n\n self.movetarget.target_ent = target;\n trainResume(self.movetarget, entities);\n}\n\nfunction triggerElevatorInit(self: Entity, entities: EntitySystem, warn: (message: string) => void): void {\n if (!self.target) {\n warn('trigger_elevator has no target');\n return;\n }\n\n const target = entities.pickTarget(self.target);\n if (!target) {\n warn(`trigger_elevator unable to find target ${self.target}`);\n return;\n }\n\n self.movetarget = target;\n if (target.classname !== 'func_train') {\n warn(`trigger_elevator target ${self.target} is not a train`);\n return;\n }\n\n self.use = (entity, other, activator) =>\n triggerElevatorUse(entity, other ?? activator ?? null, entities, warn);\n self.svflags |= ServerFlags.NoClient;\n}\n\nfunction registerTriggerElevator(registry: SpawnRegistry): void {\n registry.register('trigger_elevator', (entity, context) => {\n entity.think = (self) => triggerElevatorInit(self, context.entities, context.warn);\n context.entities.scheduleThink(entity, context.entities.timeSeconds + FRAME_TIME_SECONDS);\n });\n}\n\nfunction registerTriggerMonsterJump(registry: SpawnRegistry): void {\n registry.register('trigger_monsterjump', (entity, context) => {\n const heightText = context.keyValues.height;\n const height = heightText ? Number.parseFloat(heightText) || 0 : 200;\n if (entity.angles.y === 0) {\n entity.angles = { ...entity.angles, y: 360 };\n }\n if (!entity.speed) {\n entity.speed = 200;\n }\n\n initTrigger(entity);\n entity.movedir = { ...entity.movedir, z: height };\n const touchHandler: TouchCallback = (self, other) => monsterJumpTouch(self, other);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & MONSTERJUMP_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & MONSTERJUMP_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nexport function registerTriggerSpawns(registry: SpawnRegistry): void {\n registerTriggerMultiple(registry);\n registerTriggerOnce(registry);\n registerTriggerRelay(registry);\n registerTriggerAlways(registry);\n registerTriggerCounter(registry);\n registerTriggerKey(registry);\n registerTriggerPush(registry);\n registerTriggerHurt(registry);\n registerTriggerTeleport(registry);\n registerTriggerGravity(registry);\n registerTriggerElevator(registry);\n registerTriggerMonsterJump(registry);\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { ENTITY_FIELD_METADATA, type EntityFieldDescriptor, Entity, MoveType, Solid } from './entity.js';\nimport { registerTriggerSpawns } from './triggers.js';\nimport type { EntitySystem } from './system.js';\n\nexport type ParsedEntity = Record<string, string>;\n\ntype ParseableKeys = keyof Entity & string;\ntype FieldLookupEntry = EntityFieldDescriptor<ParseableKeys>;\n\nconst FIELD_LOOKUP: ReadonlyMap<ParseableKeys, FieldLookupEntry> = new Map(\n ENTITY_FIELD_METADATA.map((field) => [field.name as ParseableKeys, field as FieldLookupEntry]),\n);\n\nfunction parseVec3(text: string): Vec3 {\n const parts = text.trim().split(/\\s+/);\n const [x = 0, y = 0, z = 0] = parts.map((part) => Number.parseFloat(part)).map((value) => (Number.isNaN(value) ? 0 : value));\n return { x, y, z } as const;\n}\n\nfunction parseBoolean(text: string): boolean {\n const normalized = text.trim().toLowerCase();\n return normalized === '1' || normalized === 'true' || normalized === 'yes';\n}\n\nfunction parseValue(type: FieldLookupEntry['type'], value: string): unknown {\n switch (type) {\n case 'int':\n return Number.parseInt(value, 10) || 0;\n case 'float':\n return Number.parseFloat(value) || 0;\n case 'boolean':\n return parseBoolean(value);\n case 'vec3':\n return parseVec3(value);\n case 'string':\n return value;\n case 'entity':\n case 'callback':\n return undefined;\n default:\n return value;\n }\n}\n\nexport function applyEntityKeyValues(entity: Entity, values: ParsedEntity): void {\n if ('angle' in values && !('angles' in values)) {\n entity.angles = { x: 0, y: Number.parseFloat(values.angle) || 0, z: 0 };\n }\n\n for (const [key, rawValue] of Object.entries(values)) {\n if (key.startsWith('_')) {\n continue;\n }\n\n const descriptor = FIELD_LOOKUP.get(key as ParseableKeys);\n if (!descriptor) {\n continue;\n }\n\n const parsed = parseValue(descriptor.type, rawValue);\n if (parsed !== undefined) {\n (entity as unknown as Record<ParseableKeys, unknown>)[descriptor.name] = parsed;\n }\n }\n\n entity.size = {\n x: entity.maxs.x - entity.mins.x,\n y: entity.maxs.y - entity.mins.y,\n z: entity.maxs.z - entity.mins.z,\n } as const;\n}\n\nfunction parseQuoted(text: string, start: number): { value: string; nextIndex: number } {\n let index = start;\n let result = '';\n while (index < text.length) {\n const char = text[index];\n if (char === '\"') {\n return { value: result, nextIndex: index + 1 };\n }\n result += char;\n index += 1;\n }\n throw new Error('Unterminated quoted string in entity lump');\n}\n\nfunction consumeWhitespace(text: string, start: number): number {\n let index = start;\n while (index < text.length && /\\s/.test(text[index] ?? '')) {\n index += 1;\n }\n return index;\n}\n\nfunction parseToken(text: string, start: number): { token: string | null; nextIndex: number } {\n const index = consumeWhitespace(text, start);\n if (index >= text.length) {\n return { token: null, nextIndex: index };\n }\n\n const current = text[index];\n if (current === '{' || current === '}') {\n return { token: current, nextIndex: index + 1 };\n }\n\n if (current !== '\"') {\n throw new Error(`Unexpected token in entity lump: ${current}`);\n }\n\n const quoted = parseQuoted(text, index + 1);\n return { token: quoted.value, nextIndex: quoted.nextIndex };\n}\n\nexport function parseEntityLump(text: string): ParsedEntity[] {\n const entities: ParsedEntity[] = [];\n let index = 0;\n\n while (index < text.length) {\n const open = parseToken(text, index);\n index = open.nextIndex;\n if (open.token === null) {\n break;\n }\n if (open.token !== '{') {\n throw new Error('Expected { at start of entity definition');\n }\n\n const entity: ParsedEntity = {};\n\n while (true) {\n const keyToken = parseToken(text, index);\n index = keyToken.nextIndex;\n if (keyToken.token === null) {\n throw new Error('EOF reached while parsing entity');\n }\n if (keyToken.token === '}') {\n break;\n }\n\n const valueToken = parseToken(text, index);\n index = valueToken.nextIndex;\n if (valueToken.token === null || valueToken.token === '{' || valueToken.token === '}') {\n throw new Error('Malformed entity key/value pair');\n }\n\n if (!keyToken.token.startsWith('_')) {\n entity[keyToken.token] = valueToken.token;\n }\n }\n\n entities.push(entity);\n }\n\n return entities;\n}\n\nexport interface SpawnContext {\n readonly keyValues: ParsedEntity;\n readonly entities: EntitySystem;\n warn(message: string): void;\n free(entity: Entity): void;\n}\n\nexport type SpawnFunction = (entity: Entity, context: SpawnContext) => void;\n\nexport class SpawnRegistry {\n private readonly registry = new Map<string, SpawnFunction>();\n\n register(classname: string, spawn: SpawnFunction): void {\n this.registry.set(classname, spawn);\n }\n\n get(classname: string): SpawnFunction | undefined {\n return this.registry.get(classname);\n }\n}\n\nfunction defaultWarn(message: string): void {\n void message;\n}\n\nexport interface SpawnOptions {\n readonly registry: SpawnRegistry;\n readonly entities: EntitySystem;\n readonly onWarning?: (message: string) => void;\n}\n\nexport function spawnEntityFromDictionary(dictionary: ParsedEntity, options: SpawnOptions): Entity | null {\n const warn = options.onWarning ?? defaultWarn;\n const classname = dictionary.classname;\n if (!classname) {\n warn('Encountered entity with no classname');\n return null;\n }\n\n const isWorld = classname === 'worldspawn';\n const entity = isWorld ? options.entities.world : options.entities.spawn();\n applyEntityKeyValues(entity, dictionary);\n\n const context: SpawnContext = {\n keyValues: dictionary,\n entities: options.entities,\n warn,\n free(target) {\n options.entities.freeImmediate(target);\n },\n };\n\n const spawnFunc = options.registry.get(classname);\n if (!spawnFunc) {\n warn(`${classname} does not have a spawn function`);\n if (!isWorld) {\n options.entities.freeImmediate(entity);\n }\n return null;\n }\n\n spawnFunc(entity, context);\n\n if (!entity.inUse) {\n return null;\n }\n\n options.entities.finalizeSpawn(entity);\n\n return entity;\n}\n\nexport function spawnEntitiesFromText(text: string, options: SpawnOptions): Entity[] {\n const parsed = parseEntityLump(text);\n const spawned: Entity[] = [];\n\n for (const dictionary of parsed) {\n const entity = spawnEntityFromDictionary(dictionary, options);\n if (entity) {\n spawned.push(entity);\n }\n }\n\n return spawned;\n}\n\nexport function registerDefaultSpawns(registry: SpawnRegistry): void {\n registry.register('worldspawn', (entity) => {\n entity.movetype = MoveType.Push;\n entity.solid = Solid.Bsp;\n entity.modelindex = entity.modelindex || 1;\n });\n\n registry.register('info_player_start', () => {\n // No-op spawn point\n });\n\n registry.register('info_player_deathmatch', () => {\n // Deathmatch handling is deferred until game rules are implemented\n });\n\n registry.register('info_player_coop', () => {\n // Coop spawn points share info_player_start behaviour for now\n });\n\n registry.register('info_null', (entity, context) => {\n context.free(entity);\n });\n\n registry.register('info_notnull', () => {\n // Placeholder positional target\n });\n\n registry.register('info_teleport_destination', () => {\n // Destination marker for trigger_teleport\n });\n\n registerTriggerSpawns(registry);\n}\n\nexport function createDefaultSpawnRegistry(): SpawnRegistry {\n const registry = new SpawnRegistry();\n registerDefaultSpawns(registry);\n return registry;\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 restore(state: LevelFrameState): void {\n this.state = { ...state };\n }\n}\n","export const RANGE_MELEE = 20; // bboxes basically touching\nexport const RANGE_NEAR = 440;\nexport const RANGE_MID = 940;\n\nexport const FL_NOVISIBLE = 1 << 24; // super invisibility\nexport const SPAWNFLAG_MONSTER_AMBUSH = 1 << 0;\n\nexport enum AIFlags {\n Pathing = 1 << 30,\n}\n\nexport enum TraceMask {\n Opaque = 1 << 0,\n Window = 1 << 1,\n}\n","import { angleMod, degToRad, vectorToYaw } from '@quake2ts/shared';\nimport type { Vec3 } from '@quake2ts/shared';\nimport type { Entity } from '../entities/entity.js';\nimport { AIFlags } from './constants.js';\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction yawVector(yawDegrees: number, distance: number): Vec3 {\n if (distance === 0) {\n return { x: 0, y: 0, z: 0 };\n }\n const radians = degToRad(yawDegrees);\n return {\n x: Math.cos(radians) * distance,\n y: Math.sin(radians) * distance,\n z: 0,\n };\n}\n\n/**\n * Mirror of the rerelease `M_walkmove` helper without collision.\n * Moves the entity along its yaw plane and always reports success.\n */\nexport function walkMove(self: Entity, yawDegrees: number, distance: number): boolean {\n const delta = yawVector(yawDegrees, distance);\n const origin = self.origin as MutableVec3;\n origin.x += delta.x;\n origin.y += delta.y;\n origin.z += delta.z;\n return true;\n}\n\n/**\n * Match the rerelease `M_ChangeYaw` turning speed rules.\n * `yaw_speed` is interpreted the same way as Quake II: degrees per tenth-second.\n */\nexport function changeYaw(self: Entity, deltaSeconds: number): void {\n const current = angleMod(self.angles.y);\n const ideal = self.ideal_yaw;\n\n if (current === ideal) {\n (self.angles as MutableVec3).y = current;\n return;\n }\n\n // The rerelease scales yaw_speed by (10 / tick_rate); using deltaSeconds keeps that\n // behavior across arbitrary fixed-step rates.\n const speed = self.yaw_speed * deltaSeconds * 10;\n\n let move = ideal - current;\n if (ideal > current) {\n if (move >= 180) move -= 360;\n } else if (move <= -180) {\n move += 360;\n }\n\n if (move > speed) move = speed;\n else if (move < -speed) move = -speed;\n\n (self.angles as MutableVec3).y = angleMod(current + move);\n}\n\nexport function facingIdeal(self: Entity): boolean {\n const delta = angleMod(self.angles.y - self.ideal_yaw);\n const hasPathing = (self.monsterinfo.aiflags & AIFlags.Pathing) !== 0;\n\n if (hasPathing) {\n return !(delta > 5 && delta < 355);\n }\n\n return !(delta > 45 && delta < 315);\n}\n\nexport function ai_move(self: Entity, distance: number): void {\n walkMove(self, self.angles.y, distance);\n}\n\nfunction setIdealYawTowards(self: Entity, target: Entity | null): void {\n if (!target) return;\n\n const toTarget: Vec3 = {\n x: target.origin.x - self.origin.x,\n y: target.origin.y - self.origin.y,\n z: target.origin.z - self.origin.z,\n };\n self.ideal_yaw = vectorToYaw(toTarget);\n}\n\nexport function ai_stand(self: Entity, deltaSeconds: number): void {\n changeYaw(self, deltaSeconds);\n}\n\nexport function ai_walk(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.goalentity);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_turn(self: Entity, distance: number, deltaSeconds: number): void {\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n changeYaw(self, deltaSeconds);\n}\n\nexport function ai_run(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.enemy ?? self.goalentity);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_face(\n self: Entity,\n enemy: Entity | null,\n distance: number,\n deltaSeconds: number,\n): void {\n if (enemy) {\n setIdealYawTowards(self, enemy);\n }\n\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_charge(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.enemy);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { angleVectors, dotVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { distanceBetweenBoxesSquared } from '@quake2ts/shared';\nimport type { Entity } from '../entities/entity.js';\nimport { FL_NOVISIBLE, RANGE_MELEE, RANGE_MID, RANGE_NEAR, SPAWNFLAG_MONSTER_AMBUSH, TraceMask } from './constants.js';\n\nexport enum RangeCategory {\n Melee = 'melee',\n Near = 'near',\n Mid = 'mid',\n Far = 'far',\n}\n\nexport interface TraceResult {\n readonly fraction: number;\n readonly entity: Entity | null;\n}\n\nexport type TraceFunction = (start: Vec3, end: Vec3, ignore: Entity, mask: TraceMask) => TraceResult;\n\nfunction absBounds(entity: Entity): { mins: Vec3; maxs: Vec3 } {\n return {\n mins: {\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 maxs: {\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\nexport function rangeTo(self: Entity, other: Entity): number {\n const a = absBounds(self);\n const b = absBounds(other);\n const distanceSquared = distanceBetweenBoxesSquared(a.mins, a.maxs, b.mins, b.maxs);\n return Math.sqrt(distanceSquared);\n}\n\nexport function classifyRange(distance: number): RangeCategory {\n if (distance <= RANGE_MELEE) {\n return RangeCategory.Melee;\n }\n if (distance <= RANGE_NEAR) {\n return RangeCategory.Near;\n }\n if (distance <= RANGE_MID) {\n return RangeCategory.Mid;\n }\n return RangeCategory.Far;\n}\n\nexport function infront(self: Entity, other: Entity): boolean {\n const { forward } = angleVectors(self.angles);\n const direction = normalizeVec3(subtractVec3(other.origin, self.origin));\n const dot = dotVec3(direction, forward);\n\n if (\n (self.spawnflags & SPAWNFLAG_MONSTER_AMBUSH) !== 0 &&\n self.trail_time === 0 &&\n self.enemy === null\n ) {\n return dot > 0.15;\n }\n\n return dot > -0.3;\n}\n\nexport function visible(\n self: Entity,\n other: Entity,\n trace: TraceFunction,\n options?: { throughGlass?: boolean },\n): boolean {\n if ((other.flags & FL_NOVISIBLE) !== 0) {\n return false;\n }\n\n const start: Vec3 = { x: self.origin.x, y: self.origin.y, z: self.origin.z + self.viewheight };\n const end: Vec3 = { x: other.origin.x, y: other.origin.y, z: other.origin.z + other.viewheight };\n\n const mask = options?.throughGlass ? TraceMask.Opaque : TraceMask.Opaque | TraceMask.Window;\n const result = trace(start, end, self, mask);\n return result.fraction === 1 || result.entity === other;\n}\n","import type { GameStateSnapshot } from './index.js';\n\nconst FNV_OFFSET_BASIS = 0x811c9dc5;\nconst FNV_PRIME = 0x01000193;\n\nfunction hashBytes(hash: number, bytes: ArrayLike<number>): number {\n let h = hash >>> 0;\n for (let i = 0; i < bytes.length; i += 1) {\n h ^= bytes[i]! & 0xff;\n h = Math.imul(h, FNV_PRIME) >>> 0;\n }\n return h >>> 0;\n}\n\nfunction hashNumber(hash: number, value: number): number {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setFloat64(0, value, true);\n const bytes = new Uint8Array(buffer);\n return hashBytes(hash, bytes);\n}\n\nfunction hashString(hash: number, value: string): number {\n const bytes = new Uint8Array(value.length);\n for (let i = 0; i < value.length; i += 1) {\n bytes[i] = value.charCodeAt(i) & 0xff;\n }\n return hashBytes(hash, bytes);\n}\n\nexport function hashGameState(state: GameStateSnapshot): number {\n let hash = FNV_OFFSET_BASIS;\n\n hash = hashNumber(hash, state.gravity.x);\n hash = hashNumber(hash, state.gravity.y);\n hash = hashNumber(hash, state.gravity.z);\n\n hash = hashNumber(hash, state.origin.x);\n hash = hashNumber(hash, state.origin.y);\n hash = hashNumber(hash, state.origin.z);\n\n hash = hashNumber(hash, state.velocity.x);\n hash = hashNumber(hash, state.velocity.y);\n hash = hashNumber(hash, state.velocity.z);\n\n hash = hashNumber(hash, state.level.frameNumber);\n hash = hashNumber(hash, state.level.timeSeconds);\n hash = hashNumber(hash, state.level.previousTimeSeconds);\n hash = hashNumber(hash, state.level.deltaSeconds);\n\n hash = hashNumber(hash, state.entities.activeCount);\n hash = hashString(hash, state.entities.worldClassname);\n\n return hash >>> 0;\n}\n","import type { CvarRegistry } from '@quake2ts/engine';\nimport { CvarFlags, RandomGenerator, type RandomGeneratorState } from '@quake2ts/shared';\nimport type { RandomGenerator as RandomGeneratorType } from '@quake2ts/shared';\nimport type { EntitySystem, EntitySystemSnapshot, SerializedEntityState } from '../entities/index.js';\nimport type { LevelClock, LevelFrameState } from '../level.js';\n\nexport const SAVE_FORMAT_VERSION = 1;\n\nexport interface CvarSaveEntry {\n readonly name: string;\n readonly value: string;\n readonly flags: CvarFlags;\n}\n\nexport interface GameSaveFile {\n readonly version: number;\n readonly timestamp: number;\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly gameState: Record<string, unknown>;\n readonly level: LevelFrameState;\n readonly rng: RandomGeneratorState;\n readonly entities: EntitySystemSnapshot;\n readonly cvars: readonly CvarSaveEntry[];\n readonly configstrings: readonly string[];\n}\n\nexport interface SaveCreationOptions {\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly levelState: LevelFrameState;\n readonly entitySystem: EntitySystem;\n readonly rngState: RandomGeneratorState;\n readonly configstrings?: readonly string[];\n readonly cvars?: CvarRegistry;\n readonly gameState?: Record<string, unknown>;\n readonly timestamp?: number;\n}\n\nexport interface SaveApplyTargets {\n readonly levelClock: LevelClock;\n readonly entitySystem: EntitySystem;\n readonly rng: RandomGeneratorType;\n readonly cvars?: CvarRegistry;\n}\n\nexport interface ParseSaveOptions {\n readonly allowNewerVersion?: boolean;\n}\n\nconst MIN_SUPPORTED_VERSION = 1;\n\nfunction ensureObject(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction ensureNumber(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`${label} must be a finite number`);\n }\n return value;\n}\n\nfunction ensureNumberOrDefault(value: unknown, label: string, defaultValue: number): number {\n if (value === undefined) {\n return defaultValue;\n }\n return ensureNumber(value, label);\n}\n\nfunction ensureString(value: unknown, label: string): string {\n if (typeof value !== 'string') {\n throw new Error(`${label} must be a string`);\n }\n return value;\n}\n\nfunction ensureNumberArray(value: unknown, label: string): readonly number[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n for (const element of value) {\n ensureNumber(element, `${label} element`);\n }\n return value;\n}\n\nfunction parseLevelState(raw: unknown): LevelFrameState {\n if (raw === undefined) {\n return { frameNumber: 0, timeSeconds: 0, previousTimeSeconds: 0, deltaSeconds: 0 };\n }\n\n const level = ensureObject(raw, 'level');\n return {\n frameNumber: ensureNumberOrDefault(level.frameNumber, 'level.frameNumber', 0),\n timeSeconds: ensureNumberOrDefault(level.timeSeconds, 'level.timeSeconds', 0),\n previousTimeSeconds: ensureNumberOrDefault(level.previousTimeSeconds, 'level.previousTimeSeconds', 0),\n deltaSeconds: ensureNumberOrDefault(level.deltaSeconds, 'level.deltaSeconds', 0),\n };\n}\n\nfunction parseRngState(raw: unknown): RandomGeneratorState {\n if (raw === undefined) {\n return new RandomGenerator().getState();\n }\n\n const rng = ensureObject(raw, 'rng');\n const mt = ensureObject(rng.mt, 'rng.mt');\n const state = ensureNumberArray(mt.state, 'rng.mt.state');\n return {\n mt: {\n index: ensureNumber(mt.index, 'rng.mt.index'),\n state,\n },\n };\n}\n\nfunction parseThinkEntries(raw: unknown): EntitySystemSnapshot['thinks'] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('thinks must be an array');\n }\n\n return raw.map((entry, idx) => {\n const think = ensureObject(entry, `thinks[${idx}]`);\n return {\n time: ensureNumber(think.time, `thinks[${idx}].time`),\n entityIndex: ensureNumber(think.entityIndex, `thinks[${idx}].entityIndex`),\n };\n });\n}\n\nfunction parseEntityFields(raw: unknown): SerializedEntityState['fields'] {\n if (raw === undefined) {\n return {};\n }\n\n const fields = ensureObject(raw, 'entity.fields');\n const parsed: SerializedEntityState['fields'] = {};\n for (const [name, value] of Object.entries(fields)) {\n if (value === null) {\n parsed[name as keyof SerializedEntityState['fields']] = null;\n continue;\n }\n\n switch (typeof value) {\n case 'number':\n case 'string':\n case 'boolean':\n parsed[name as keyof SerializedEntityState['fields']] = value;\n break;\n default: {\n if (!Array.isArray(value)) {\n const object = ensureObject(value, name);\n const inventory: Record<string, number> = {};\n for (const [entryName, entryValue] of Object.entries(object)) {\n inventory[entryName] = ensureNumber(entryValue, `${name}.${entryName}`);\n }\n parsed[name as keyof SerializedEntityState['fields']] = inventory;\n break;\n }\n if (Array.isArray(value) && value.length === 3) {\n const [x, y, z] = value;\n parsed[name as keyof SerializedEntityState['fields']] = [\n ensureNumber(x, `${name}[0]`),\n ensureNumber(y, `${name}[1]`),\n ensureNumber(z, `${name}[2]`),\n ];\n break;\n }\n throw new Error(`Unsupported entity field value for ${name}`);\n }\n }\n }\n return parsed;\n}\n\nfunction parseEntities(raw: unknown): SerializedEntityState[] {\n if (!Array.isArray(raw)) {\n throw new Error('entities must be an array');\n }\n\n return raw.map((entry, idx) => {\n const entity = ensureObject(entry, `entities[${idx}]`);\n return {\n index: ensureNumber(entity.index, `entities[${idx}].index`),\n fields: parseEntityFields(entity.fields),\n };\n });\n}\n\nfunction parsePool(raw: unknown): EntitySystemSnapshot['pool'] {\n const pool = ensureObject(raw, 'pool');\n return {\n capacity: ensureNumber(pool.capacity, 'pool.capacity'),\n activeOrder: ensureNumberArray(pool.activeOrder, 'pool.activeOrder'),\n freeList: ensureNumberArray(pool.freeList, 'pool.freeList'),\n pendingFree: ensureNumberArray(pool.pendingFree, 'pool.pendingFree'),\n };\n}\n\nfunction parseEntitySnapshot(raw: unknown): EntitySystemSnapshot {\n const snapshot = ensureObject(raw, 'entities');\n return {\n timeSeconds: ensureNumber(snapshot.timeSeconds, 'entities.timeSeconds'),\n pool: parsePool(snapshot.pool),\n entities: parseEntities(snapshot.entities),\n thinks: parseThinkEntries(snapshot.thinks),\n };\n}\n\nfunction parseCvars(raw: unknown): CvarSaveEntry[] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('cvars must be an array');\n }\n\n return raw.map((entry, idx) => {\n const cvar = ensureObject(entry, `cvars[${idx}]`);\n return {\n name: ensureString(cvar.name, `cvars[${idx}].name`),\n value: ensureString(cvar.value, `cvars[${idx}].value`),\n flags: ensureNumber(cvar.flags, `cvars[${idx}].flags`) as CvarFlags,\n };\n });\n}\n\nfunction parseConfigstrings(raw: unknown): string[] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('configstrings must be an array');\n }\n\n return raw.map((value, idx) => ensureString(value, `configstrings[${idx}]`));\n}\n\nfunction parseGameState(raw: unknown): Record<string, unknown> {\n if (raw === undefined) {\n return {};\n }\n\n return ensureObject(raw, 'gameState');\n}\n\nfunction serializeCvars(registry: CvarRegistry | undefined): CvarSaveEntry[] {\n if (!registry) {\n return [];\n }\n\n return registry\n .list()\n .filter((cvar) => (cvar.flags & CvarFlags.Archive) !== 0)\n .map((cvar) => ({ name: cvar.name, value: cvar.string, flags: cvar.flags }));\n}\n\nfunction applyCvars(entries: readonly CvarSaveEntry[], registry: CvarRegistry | undefined): void {\n if (!registry) {\n return;\n }\n\n for (const entry of entries) {\n const existing = registry.get(entry.name);\n if (existing) {\n existing.set(entry.value);\n } else {\n registry.register({ name: entry.name, defaultValue: entry.value, flags: entry.flags });\n }\n }\n}\n\nfunction cloneRngState(state: RandomGeneratorState): RandomGeneratorState {\n return {\n mt: {\n index: state.mt.index,\n state: [...state.mt.state],\n },\n };\n}\n\nexport function createSaveFile(options: SaveCreationOptions): GameSaveFile {\n const {\n map,\n difficulty,\n playtimeSeconds,\n levelState,\n entitySystem,\n rngState,\n configstrings = [],\n cvars,\n gameState = {},\n timestamp = Date.now(),\n } = options;\n\n return {\n version: SAVE_FORMAT_VERSION,\n timestamp,\n map,\n difficulty,\n playtimeSeconds,\n gameState: { ...gameState },\n level: { ...levelState },\n rng: cloneRngState(rngState),\n entities: entitySystem.createSnapshot(),\n cvars: serializeCvars(cvars),\n configstrings: [...configstrings],\n };\n}\n\nexport function parseSaveFile(serialized: unknown, options: ParseSaveOptions = {}): GameSaveFile {\n const { allowNewerVersion = true } = options;\n const raw = typeof serialized === 'string' ? JSON.parse(serialized) : serialized;\n const save = ensureObject(raw, 'save');\n\n const versionValue = save.version ?? SAVE_FORMAT_VERSION;\n const version = ensureNumber(versionValue, 'version');\n if (version < MIN_SUPPORTED_VERSION) {\n throw new Error(`Unsupported save version ${version}`);\n }\n if (version > SAVE_FORMAT_VERSION && !allowNewerVersion) {\n throw new Error(`Save version ${version} is newer than supported ${SAVE_FORMAT_VERSION}`);\n }\n\n return {\n version,\n timestamp: ensureNumber(save.timestamp, 'timestamp'),\n map: ensureString(save.map, 'map'),\n difficulty: ensureNumber(save.difficulty, 'difficulty'),\n playtimeSeconds: ensureNumber(save.playtimeSeconds, 'playtimeSeconds'),\n gameState: parseGameState(save.gameState),\n level: parseLevelState(save.level),\n rng: parseRngState(save.rng),\n entities: parseEntitySnapshot(save.entities),\n cvars: parseCvars(save.cvars),\n configstrings: parseConfigstrings(save.configstrings),\n };\n}\n\nexport function applySaveFile(save: GameSaveFile, targets: SaveApplyTargets): void {\n targets.levelClock.restore(save.level);\n targets.entitySystem.restore(save.entities);\n targets.rng.setState(save.rng);\n applyCvars(save.cvars, targets.cvars);\n}\n","export type JsonObject = Record<string, unknown>;\n\nexport interface RereleaseGameSave {\n readonly saveVersion: number;\n readonly game: JsonObject & { readonly maxclients?: number };\n readonly clients: readonly JsonObject[];\n}\n\nexport interface RereleaseLevelSave {\n readonly saveVersion: number;\n readonly level: JsonObject;\n readonly entities: ReadonlyMap<number, JsonObject>;\n}\n\nexport type RereleaseSave = RereleaseGameSave | RereleaseLevelSave;\n\nexport interface RereleaseSaveSummary {\n readonly version: number;\n readonly kind: 'game' | 'level';\n readonly maxClients?: number;\n readonly clientCount?: number;\n readonly entityCount?: number;\n readonly highestEntityIndex?: number;\n}\n\nfunction ensureObject(value: unknown, label: string): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as JsonObject;\n}\n\nfunction ensureNumber(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`${label} must be a finite number`);\n }\n return value;\n}\n\nfunction ensureArray(value: unknown, label: string): readonly unknown[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n return value;\n}\n\nfunction parseEntityMap(raw: JsonObject): ReadonlyMap<number, JsonObject> {\n const map = new Map<number, JsonObject>();\n for (const [rawIndex, value] of Object.entries(raw)) {\n const index = Number(rawIndex);\n if (!Number.isInteger(index)) {\n throw new Error(`entities[${rawIndex}] must use an integer key`);\n }\n map.set(index, ensureObject(value, `entities[${rawIndex}]`));\n }\n return map;\n}\n\nexport function parseRereleaseSave(raw: unknown): RereleaseSave {\n const root = ensureObject(raw, 'rerelease save');\n const saveVersion = ensureNumber(root.save_version, 'save_version');\n const hasGame = 'game' in root;\n const hasLevel = 'level' in root;\n\n if (hasGame === hasLevel) {\n throw new Error('save must contain either game or level data');\n }\n\n if (hasGame) {\n const game = ensureObject((root as Record<string, unknown>).game, 'game');\n const clients = ensureArray((root as Record<string, unknown>).clients, 'clients').map((entry, idx) =>\n ensureObject(entry, `clients[${idx}]`),\n );\n const maxclients = game.maxclients !== undefined ? ensureNumber(game.maxclients, 'game.maxclients') : clients.length;\n if (clients.length !== maxclients) {\n throw new Error(`clients length ${clients.length} does not match game.maxclients ${maxclients}`);\n }\n return { saveVersion, game, clients };\n }\n\n const level = ensureObject((root as Record<string, unknown>).level, 'level');\n const entitiesRoot = ensureObject((root as Record<string, unknown>).entities, 'entities');\n const entities = parseEntityMap(entitiesRoot);\n return { saveVersion, level, entities };\n}\n\nexport function summarizeRereleaseSave(raw: unknown): RereleaseSaveSummary {\n const parsed = parseRereleaseSave(raw);\n if ('game' in parsed) {\n const maxClients = parsed.game.maxclients ?? parsed.clients.length;\n return {\n version: parsed.saveVersion,\n kind: 'game',\n maxClients,\n clientCount: parsed.clients.length,\n };\n }\n\n let highestEntityIndex = -1;\n for (const index of parsed.entities.keys()) {\n if (index > highestEntityIndex) {\n highestEntityIndex = index;\n }\n }\n\n return {\n version: parsed.saveVersion,\n kind: 'level',\n entityCount: parsed.entities.size,\n highestEntityIndex: highestEntityIndex >= 0 ? highestEntityIndex : undefined,\n };\n}\n","import { parseSaveFile, type GameSaveFile, type ParseSaveOptions } from './save.js';\n\nexport interface SaveSlotMetadata {\n readonly id: string;\n readonly name: string;\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly timestamp: number;\n readonly version: number;\n readonly bytes: number;\n}\n\ninterface SaveRecord {\n readonly id: string;\n readonly metadata: SaveSlotMetadata;\n readonly save: GameSaveFile;\n}\n\ninterface SaveStorageAdapter {\n init(): Promise<void>;\n put(record: SaveRecord): Promise<void>;\n get(id: string): Promise<SaveRecord | null>;\n delete(id: string): Promise<boolean>;\n list(): Promise<SaveRecord[]>;\n}\n\ntype TextEncoderLike = { encode(input?: string): Uint8Array };\ntype TextEncoderCtor = new () => TextEncoderLike;\nconst TEXT_ENCODER_CTOR: TextEncoderCtor | undefined =\n (globalThis as Record<string, unknown>).TextEncoder as TextEncoderCtor | undefined;\n\nfunction cloneSave(save: GameSaveFile): GameSaveFile {\n return parseSaveFile({ ...save }, { allowNewerVersion: true });\n}\n\nfunction estimateSizeBytes(save: GameSaveFile): number {\n if (TEXT_ENCODER_CTOR) {\n const encoder = new TEXT_ENCODER_CTOR();\n return encoder.encode(JSON.stringify(save)).length;\n }\n return JSON.stringify(save).length;\n}\n\nclass MemorySaveAdapter implements SaveStorageAdapter {\n private readonly records = new Map<string, SaveRecord>();\n\n async init(): Promise<void> {\n return Promise.resolve();\n }\n\n async put(record: SaveRecord): Promise<void> {\n const copy: SaveRecord = {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n this.records.set(record.id, copy);\n }\n\n async get(id: string): Promise<SaveRecord | null> {\n const record = this.records.get(id);\n if (!record) {\n return null;\n }\n return {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n }\n\n async delete(id: string): Promise<boolean> {\n return this.records.delete(id);\n }\n\n async list(): Promise<SaveRecord[]> {\n return Array.from(this.records.values()).map((record) => ({\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n }));\n }\n}\n\ntype IndexedDbFactory = { open(name: string, version?: number): unknown };\n\nclass IndexedDbSaveAdapter implements SaveStorageAdapter {\n private db: unknown = null;\n\n constructor(\n private readonly indexedDB: IndexedDbFactory,\n private readonly dbName: string,\n private readonly storeName: string,\n ) {}\n\n async init(): Promise<void> {\n if (this.db) {\n return;\n }\n\n this.db = await new Promise<unknown>((resolve, reject) => {\n const request = this.indexedDB.open(this.dbName, 1) as any;\n request.onupgradeneeded = () => {\n request.result.createObjectStore(this.storeName, { keyPath: 'id' });\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to open IndexedDB'));\n request.onsuccess = () => resolve(request.result);\n });\n }\n\n private async runTransaction<T>(mode: 'readonly' | 'readwrite', operation: (store: any) => any): Promise<T> {\n await this.init();\n const database = this.db as any;\n return new Promise<T>((resolve, reject) => {\n const transaction = database.transaction(this.storeName, mode);\n const store = transaction.objectStore(this.storeName);\n const request = operation(store);\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));\n });\n }\n\n async put(record: SaveRecord): Promise<void> {\n await this.runTransaction('readwrite', (store) => store.put(record));\n }\n\n async get(id: string): Promise<SaveRecord | null> {\n const record = await this.runTransaction<SaveRecord | null>('readonly', (store) => store.get(id));\n if (!record) {\n return null;\n }\n return {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n }\n\n async delete(id: string): Promise<boolean> {\n const existing = await this.get(id);\n if (!existing) {\n return false;\n }\n await this.runTransaction('readwrite', (store) => store.delete(id));\n return true;\n }\n\n async list(): Promise<SaveRecord[]> {\n const all = await this.runTransaction<SaveRecord[]>('readonly', (store) => store.getAll());\n return all.map((record) => ({\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n }));\n }\n}\n\nexport interface SaveStorageOptions {\n readonly dbName?: string;\n readonly storeName?: string;\n readonly indexedDB?: IndexedDbFactory | null;\n}\n\nexport interface SaveWriteOptions {\n readonly name?: string;\n}\n\nexport class SaveStorage {\n private static readonly DEFAULT_DB_NAME = 'quake2ts-saves';\n private static readonly DEFAULT_STORE = 'saves';\n private static readonly QUICK_SLOT = 'quicksave';\n\n private readonly adapter: SaveStorageAdapter;\n\n constructor(options: SaveStorageOptions = {}) {\n const { dbName = SaveStorage.DEFAULT_DB_NAME, storeName = SaveStorage.DEFAULT_STORE } = options;\n const indexedDBFactory =\n options.indexedDB ?? ((globalThis as Record<string, unknown>).indexedDB as IndexedDbFactory | undefined);\n if (indexedDBFactory) {\n this.adapter = new IndexedDbSaveAdapter(indexedDBFactory, dbName, storeName);\n } else {\n this.adapter = new MemorySaveAdapter();\n }\n }\n\n async save(slotId: string, save: GameSaveFile, options: SaveWriteOptions = {}): Promise<SaveSlotMetadata> {\n const normalized = cloneSave(save);\n const metadata: SaveSlotMetadata = {\n id: slotId,\n name: options.name ?? slotId,\n map: normalized.map,\n difficulty: normalized.difficulty,\n playtimeSeconds: normalized.playtimeSeconds,\n timestamp: normalized.timestamp,\n version: normalized.version,\n bytes: estimateSizeBytes(normalized),\n };\n\n await this.adapter.init();\n await this.adapter.put({ id: slotId, metadata, save: normalized });\n return metadata;\n }\n\n async load(slotId: string, options: ParseSaveOptions = {}): Promise<GameSaveFile> {\n await this.adapter.init();\n const record = await this.adapter.get(slotId);\n if (!record) {\n throw new Error(`Save slot ${slotId} not found`);\n }\n return parseSaveFile(record.save, options);\n }\n\n async delete(slotId: string): Promise<boolean> {\n await this.adapter.init();\n return this.adapter.delete(slotId);\n }\n\n async list(): Promise<SaveSlotMetadata[]> {\n await this.adapter.init();\n const records = await this.adapter.list();\n return records\n .map((record) => ({ ...record.metadata }))\n .sort((a, b) => b.timestamp - a.timestamp || a.id.localeCompare(b.id));\n }\n\n async quickSave(save: GameSaveFile): Promise<SaveSlotMetadata> {\n return this.save(SaveStorage.QUICK_SLOT, save, { name: 'Quick Save' });\n }\n\n async quickLoad(options: ParseSaveOptions = {}): Promise<GameSaveFile> {\n return this.load(SaveStorage.QUICK_SLOT, options);\n }\n}\n","export enum DamageFlags {\n NONE = 0,\n RADIUS = 0x00000001,\n NO_ARMOR = 0x00000002,\n ENERGY = 0x00000004,\n NO_KNOCKBACK = 0x00000008,\n BULLET = 0x00000010,\n NO_PROTECTION = 0x00000020,\n DESTROY_ARMOR = 0x00000040,\n NO_REG_ARMOR = 0x00000080,\n NO_POWER_ARMOR = 0x00000100,\n NO_INDICATOR = 0x00000200,\n}\n\nexport function hasAnyDamageFlag(flags: number, mask: DamageFlags): boolean {\n return (flags & mask) !== 0;\n}\n","import { angleVectors, type Vec3 } from '@quake2ts/shared';\nimport { DamageFlags, hasAnyDamageFlag } from './damageFlags.js';\n\nexport enum ArmorType {\n BODY = 'body',\n COMBAT = 'combat',\n JACKET = 'jacket',\n}\n\nexport interface ArmorInfo {\n readonly baseCount: number;\n readonly maxCount: number;\n readonly normalProtection: number;\n readonly energyProtection: number;\n}\n\nexport const ARMOR_INFO: Record<ArmorType, ArmorInfo> = {\n [ArmorType.JACKET]: {\n baseCount: 25,\n maxCount: 50,\n normalProtection: 0.3,\n energyProtection: 0,\n },\n [ArmorType.COMBAT]: {\n baseCount: 50,\n maxCount: 100,\n normalProtection: 0.6,\n energyProtection: 0.3,\n },\n [ArmorType.BODY]: {\n baseCount: 100,\n maxCount: 200,\n normalProtection: 0.8,\n energyProtection: 0.6,\n },\n};\n\nexport interface RegularArmorState {\n readonly armorType: ArmorType | null;\n armorCount: number;\n}\n\nexport interface RegularArmorResult {\n readonly saved: number;\n readonly remainingArmor: number;\n}\n\nexport function applyRegularArmor(\n damage: number,\n flags: number,\n state: RegularArmorState,\n): RegularArmorResult {\n if (\n damage <= 0 ||\n hasAnyDamageFlag(flags, DamageFlags.NO_ARMOR | DamageFlags.NO_REG_ARMOR) ||\n !state.armorType ||\n state.armorCount <= 0\n ) {\n return { saved: 0, remainingArmor: state.armorCount };\n }\n\n const info = ARMOR_INFO[state.armorType];\n const protection = hasAnyDamageFlag(flags, DamageFlags.ENERGY)\n ? info.energyProtection\n : info.normalProtection;\n\n let saved = Math.ceil(protection * damage);\n if (saved >= state.armorCount) {\n saved = state.armorCount;\n }\n\n if (saved <= 0) {\n return { saved: 0, remainingArmor: state.armorCount };\n }\n\n return { saved, remainingArmor: state.armorCount - saved };\n}\n\nexport type PowerArmorType = 'screen' | 'shield';\n\nexport interface PowerArmorState {\n readonly type: PowerArmorType | null;\n cellCount: number;\n readonly angles: Vec3;\n readonly origin: Vec3;\n readonly health: number;\n}\n\nexport interface PowerArmorOptions {\n readonly ctfMode?: boolean;\n}\n\nexport interface PowerArmorResult {\n readonly saved: number;\n readonly remainingCells: number;\n}\n\nexport function applyPowerArmor(\n damage: number,\n flags: number,\n hitPoint: Vec3,\n _hitNormal: Vec3,\n state: PowerArmorState,\n options: PowerArmorOptions = {},\n): PowerArmorResult {\n if (state.health <= 0 || damage <= 0) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n if (hasAnyDamageFlag(flags, DamageFlags.NO_ARMOR | DamageFlags.NO_POWER_ARMOR)) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n if (!state.type || state.cellCount <= 0) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n const { forward } = angleVectors(state.angles);\n const toImpact = {\n x: hitPoint.x - state.origin.x,\n y: hitPoint.y - state.origin.y,\n z: hitPoint.z - state.origin.z,\n };\n const toImpactLength = Math.hypot(toImpact.x, toImpact.y, toImpact.z);\n\n if (state.type === 'screen' && toImpactLength > 0) {\n const dir = {\n x: toImpact.x / toImpactLength,\n y: toImpact.y / toImpactLength,\n z: toImpact.z / toImpactLength,\n };\n const dot = dir.x * forward.x + dir.y * forward.y + dir.z * forward.z;\n if (dot <= 0.3) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n }\n\n const ctfMode = options.ctfMode ?? false;\n const damagePerCell = state.type === 'screen' ? 1 : ctfMode ? 1 : 2;\n let adjustedDamage = state.type === 'screen' ? damage / 3 : (2 * damage) / 3;\n adjustedDamage = Math.max(1, adjustedDamage);\n\n let saved = state.cellCount * damagePerCell;\n if (hasAnyDamageFlag(flags, DamageFlags.ENERGY)) {\n saved = Math.max(1, Math.floor(saved / 2));\n }\n\n if (saved > adjustedDamage) {\n saved = Math.floor(adjustedDamage);\n }\n\n let powerUsed = saved / damagePerCell;\n if (hasAnyDamageFlag(flags, DamageFlags.ENERGY)) {\n powerUsed *= 2;\n }\n powerUsed = Math.max(1, Math.floor(powerUsed));\n\n const cellsSpent = Math.max(damagePerCell, powerUsed);\n const remainingCells = Math.max(0, state.cellCount - cellsSpent);\n\n return { saved, remainingCells };\n}\n","import { addVec3, closestPointToBox, lengthVec3, normalizeVec3, scaleVec3, subtractVec3, type Vec3 } from '@quake2ts/shared';\nimport { applyPowerArmor, applyRegularArmor, type PowerArmorState, type RegularArmorState } from './armor.js';\nimport { DamageFlags, hasAnyDamageFlag } from './damageFlags.js';\nimport { DamageMod } from './damageMods.js';\n\nexport interface DamageableCallbacks {\n pain?: (self: Damageable, attacker: Damageable | null, knockback: number, take: number, mod: DamageMod) => void;\n die?: (self: Damageable, inflictor: Damageable | null, attacker: Damageable | null, take: number, point: Vec3, mod: DamageMod) => void;\n}\n\nexport interface Damageable extends DamageableCallbacks {\n readonly id?: string;\n takedamage: boolean;\n health: number;\n readonly maxHealth?: number;\n readonly mass?: number;\n velocity: Vec3;\n readonly origin: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly flags?: EntityDamageFlags;\n readonly regularArmor?: RegularArmorState;\n readonly powerArmor?: PowerArmorState;\n}\n\nexport enum EntityDamageFlags {\n GODMODE = 1 << 0,\n IMMORTAL = 1 << 1,\n NO_KNOCKBACK = 1 << 2,\n NO_DAMAGE_EFFECTS = 1 << 3,\n}\n\nexport interface DamageApplicationResult {\n readonly take: number;\n readonly psave: number;\n readonly asave: number;\n readonly knocked: Vec3;\n readonly killed: boolean;\n readonly remainingArmor?: number;\n readonly remainingCells?: number;\n}\n\nexport interface DamageSource {\n readonly origin: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface RadiusDamageHit {\n readonly target: Damageable;\n readonly result: DamageApplicationResult | null;\n readonly appliedDamage: number;\n}\n\nexport interface RadiusDamageOptions {\n readonly canDamage?: (ent: Damageable, inflictor: DamageSource) => boolean;\n}\n\nfunction applyKnockback(\n targ: Damageable,\n attacker: Damageable | null,\n dir: Vec3,\n knockback: number,\n dflags: number,\n): Vec3 {\n const hasNoKnockback =\n hasAnyDamageFlag(dflags, DamageFlags.NO_KNOCKBACK) || ((targ.flags ?? 0) & EntityDamageFlags.NO_KNOCKBACK) !== 0;\n if (hasNoKnockback || knockback === 0) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const mass = Math.max(50, targ.mass ?? 200);\n const normalized = normalizeVec3(dir);\n const scale = attacker === targ ? 1600 : 500;\n const delta = scaleVec3(normalized, (scale * knockback) / mass);\n targ.velocity = addVec3(targ.velocity, delta);\n return delta;\n}\n\nfunction applyProtection(\n targ: Damageable,\n point: Vec3,\n normal: Vec3,\n damage: number,\n dflags: number,\n): [number, number, number, number?, number?] {\n let take = damage;\n let psave = 0;\n let asave = 0;\n let remainingCells: number | undefined;\n let remainingArmor: number | undefined;\n\n if (targ.powerArmor) {\n const result = applyPowerArmor(damage, dflags, point, normal, targ.powerArmor);\n psave = result.saved;\n remainingCells = result.remainingCells;\n take -= psave;\n }\n\n if (targ.regularArmor) {\n const result = applyRegularArmor(take, dflags, targ.regularArmor);\n asave = result.saved;\n remainingArmor = result.remainingArmor;\n take -= asave;\n }\n\n return [Math.max(0, take), psave, asave, remainingCells, remainingArmor];\n}\n\nfunction targetCenter(ent: DamageSource | Damageable): Vec3 {\n if (ent.mins && ent.maxs) {\n return {\n x: ent.origin.x + (ent.mins.x + ent.maxs.x) * 0.5,\n y: ent.origin.y + (ent.mins.y + ent.maxs.y) * 0.5,\n z: ent.origin.z + (ent.mins.z + ent.maxs.z) * 0.5,\n };\n }\n return ent.origin;\n}\n\nexport function T_Damage(\n targ: Damageable,\n inflictor: Damageable | null,\n attacker: Damageable | null,\n dir: Vec3,\n point: Vec3,\n normal: Vec3,\n damage: number,\n knockback: number,\n dflags: number,\n mod: DamageMod,\n): DamageApplicationResult | null {\n if (!targ.takedamage || damage <= 0) {\n return null;\n }\n\n const protectedByGod =\n !hasAnyDamageFlag(dflags, DamageFlags.NO_PROTECTION) && ((targ.flags ?? 0) & EntityDamageFlags.GODMODE) !== 0;\n\n if (protectedByGod) {\n return {\n take: 0,\n psave: 0,\n asave: damage,\n knocked: { x: 0, y: 0, z: 0 },\n killed: false,\n };\n }\n\n const knocked = applyKnockback(targ, attacker, dir, knockback, dflags);\n const [take, psave, asave, remainingCells, remainingArmor] = applyProtection(targ, point, normal, damage, dflags);\n\n if (targ.powerArmor && remainingCells !== undefined) {\n (targ.powerArmor as PowerArmorState).cellCount = remainingCells;\n }\n if (targ.regularArmor) {\n (targ.regularArmor as RegularArmorState).armorCount = remainingArmor ?? targ.regularArmor.armorCount;\n }\n\n let actualTake = take;\n\n if (actualTake > 0) {\n targ.health -= actualTake;\n }\n\n const killed = targ.health <= 0;\n if (killed) {\n if (targ.flags && (targ.flags & EntityDamageFlags.IMMORTAL)) {\n targ.health = Math.max(1, targ.health);\n } else if (targ.die) {\n targ.die(targ, inflictor, attacker, actualTake, point, mod);\n }\n } else if (actualTake > 0 && targ.pain) {\n targ.pain(targ, attacker, knockback, actualTake, mod);\n }\n\n return { take: actualTake, psave, asave, knocked, killed, remainingCells, remainingArmor };\n}\n\nexport function T_RadiusDamage(\n entities: readonly Damageable[],\n inflictor: DamageSource,\n attacker: Damageable | null,\n damage: number,\n ignore: Damageable | null,\n radius: number,\n dflags: number,\n mod: DamageMod,\n options: RadiusDamageOptions = {},\n): RadiusDamageHit[] {\n const hits: RadiusDamageHit[] = [];\n const inflictorCenter = targetCenter(inflictor);\n const canDamage = options.canDamage ?? (() => true);\n\n for (const ent of entities) {\n if (ent === ignore || !ent.takedamage || !canDamage(ent, inflictor)) {\n continue;\n }\n\n const entCenter = ent.mins && ent.maxs\n ? closestPointToBox(inflictorCenter, addVec3(ent.origin, ent.mins), addVec3(ent.origin, ent.maxs))\n : targetCenter(ent);\n const toTarget = subtractVec3(inflictorCenter, entCenter);\n const distance = lengthVec3(toTarget);\n if (radius > 0 && distance > radius) {\n continue;\n }\n\n const points = damage - 0.5 * distance;\n if (points <= 0) {\n continue;\n }\n\n const adjustedDamage = ent === attacker ? points * 0.5 : points;\n const dir = normalizeVec3(subtractVec3(ent.origin, inflictorCenter));\n const result = T_Damage(ent, inflictor as Damageable | null, attacker, dir, entCenter, dir, adjustedDamage, adjustedDamage, dflags | DamageFlags.RADIUS, mod);\n hits.push({ target: ent, result, appliedDamage: adjustedDamage });\n }\n\n return hits;\n}\n","/**\n * Means-of-death identifiers mirrored from the Quake II rerelease `mod_id_t`\n * enumeration in `g_local.h`. The numeric ordering is significant for\n * obituary strings and damage filtering, so we retain the exact sequence from\n * the C++ sources.\n */\nexport enum DamageMod {\n UNKNOWN = 0,\n BLASTER = 1,\n SHOTGUN = 2,\n SSHOTGUN = 3,\n MACHINEGUN = 4,\n CHAINGUN = 5,\n GRENADE = 6,\n G_SPLASH = 7,\n ROCKET = 8,\n R_SPLASH = 9,\n HYPERBLASTER = 10,\n RAILGUN = 11,\n BFG_LASER = 12,\n BFG_BLAST = 13,\n BFG_EFFECT = 14,\n HANDGRENADE = 15,\n HG_SPLASH = 16,\n WATER = 17,\n SLIME = 18,\n LAVA = 19,\n CRUSH = 20,\n TELEFRAG = 21,\n TELEFRAG_SPAWN = 22,\n FALLING = 23,\n SUICIDE = 24,\n HELD_GRENADE = 25,\n EXPLOSIVE = 26,\n BARREL = 27,\n BOMB = 28,\n EXIT = 29,\n SPLASH = 30,\n TARGET_LASER = 31,\n TRIGGER_HURT = 32,\n HIT = 33,\n TARGET_BLASTER = 34,\n RIPPER = 35,\n PHALANX = 36,\n BRAINTENTACLE = 37,\n BLASTOFF = 38,\n GEKK = 39,\n TRAP = 40,\n CHAINFIST = 41,\n DISINTEGRATOR = 42,\n ETF_RIFLE = 43,\n BLASTER2 = 44,\n HEATBEAM = 45,\n TESLA = 46,\n PROX = 47,\n NUKE = 48,\n VENGEANCE_SPHERE = 49,\n HUNTER_SPHERE = 50,\n DEFENDER_SPHERE = 51,\n TRACKER = 52,\n DBALL_CRUSH = 53,\n DOPPLE_EXPLODE = 54,\n DOPPLE_VENGEANCE = 55,\n DOPPLE_HUNTER = 56,\n GRAPPLE = 57,\n BLUEBLASTER = 58,\n}\n\n/**\n * Ordered list of the MOD_* identifiers. Tests use this to verify we stay in\n * lockstep with the rerelease values and to drive lookup helpers that need a\n * stable iteration order.\n */\nexport const ORDERED_DAMAGE_MODS: readonly DamageMod[] = [\n DamageMod.UNKNOWN,\n DamageMod.BLASTER,\n DamageMod.SHOTGUN,\n DamageMod.SSHOTGUN,\n DamageMod.MACHINEGUN,\n DamageMod.CHAINGUN,\n DamageMod.GRENADE,\n DamageMod.G_SPLASH,\n DamageMod.ROCKET,\n DamageMod.R_SPLASH,\n DamageMod.HYPERBLASTER,\n DamageMod.RAILGUN,\n DamageMod.BFG_LASER,\n DamageMod.BFG_BLAST,\n DamageMod.BFG_EFFECT,\n DamageMod.HANDGRENADE,\n DamageMod.HG_SPLASH,\n DamageMod.WATER,\n DamageMod.SLIME,\n DamageMod.LAVA,\n DamageMod.CRUSH,\n DamageMod.TELEFRAG,\n DamageMod.TELEFRAG_SPAWN,\n DamageMod.FALLING,\n DamageMod.SUICIDE,\n DamageMod.HELD_GRENADE,\n DamageMod.EXPLOSIVE,\n DamageMod.BARREL,\n DamageMod.BOMB,\n DamageMod.EXIT,\n DamageMod.SPLASH,\n DamageMod.TARGET_LASER,\n DamageMod.TRIGGER_HURT,\n DamageMod.HIT,\n DamageMod.TARGET_BLASTER,\n DamageMod.RIPPER,\n DamageMod.PHALANX,\n DamageMod.BRAINTENTACLE,\n DamageMod.BLASTOFF,\n DamageMod.GEKK,\n DamageMod.TRAP,\n DamageMod.CHAINFIST,\n DamageMod.DISINTEGRATOR,\n DamageMod.ETF_RIFLE,\n DamageMod.BLASTER2,\n DamageMod.HEATBEAM,\n DamageMod.TESLA,\n DamageMod.PROX,\n DamageMod.NUKE,\n DamageMod.VENGEANCE_SPHERE,\n DamageMod.HUNTER_SPHERE,\n DamageMod.DEFENDER_SPHERE,\n DamageMod.TRACKER,\n DamageMod.DBALL_CRUSH,\n DamageMod.DOPPLE_EXPLODE,\n DamageMod.DOPPLE_VENGEANCE,\n DamageMod.DOPPLE_HUNTER,\n DamageMod.GRAPPLE,\n DamageMod.BLUEBLASTER,\n];\n\n/**\n * Returns the stable string name (e.g. `MOD_RAILGUN`) used by the rerelease\n * for obituary strings and logging.\n */\nexport function damageModName(mod: DamageMod): string {\n return `MOD_${DamageMod[mod]}`;\n}\n","import {\n CONTENTS_LAVA,\n CONTENTS_SLIME,\n WaterLevel,\n addVec3,\n boxesIntersect,\n type Bounds3,\n type Vec3,\n} from '@quake2ts/shared';\n\nimport { DamageFlags } from './damageFlags.js';\nimport { DamageMod } from './damageMods.js';\nimport { T_Damage, type Damageable, type DamageApplicationResult } from './damage.js';\nimport { MoveType, Solid } from '../entities/entity.js';\n\nconst ZERO: Vec3 = { x: 0, y: 0, z: 0 };\n\nexport enum EnvironmentalFlags {\n IN_WATER = 1 << 0,\n IMMUNE_LAVA = 1 << 1,\n IMMUNE_SLIME = 1 << 2,\n}\n\nexport interface EnvironmentalDamageTarget extends Damageable {\n waterlevel: WaterLevel;\n watertype: number;\n airFinished: number;\n painDebounceTime: number;\n damageDebounceTime: number;\n environmentFlags?: EnvironmentalFlags;\n}\n\nexport interface EnvironmentalDamageEvent {\n readonly mod: DamageMod;\n readonly amount: number;\n readonly result: DamageApplicationResult | null;\n}\n\nexport interface EnvironmentalDamageResult {\n readonly events: EnvironmentalDamageEvent[];\n readonly enteredWater: boolean;\n readonly leftWater: boolean;\n}\n\nfunction applyDamageEvent(\n target: EnvironmentalDamageTarget,\n amount: number,\n mod: DamageMod,\n): DamageApplicationResult | null {\n return T_Damage(target, null, null, ZERO, target.origin, ZERO, amount, 0, DamageFlags.NO_ARMOR, mod);\n}\n\nexport function applyEnvironmentalDamage(\n target: EnvironmentalDamageTarget,\n nowMs: number,\n): EnvironmentalDamageResult {\n const events: EnvironmentalDamageEvent[] = [];\n let flags = target.environmentFlags ?? 0;\n let enteredWater = false;\n let leftWater = false;\n\n if (target.waterlevel === WaterLevel.None) {\n if ((flags & EnvironmentalFlags.IN_WATER) !== 0) {\n flags &= ~EnvironmentalFlags.IN_WATER;\n leftWater = true;\n }\n\n if (target.airFinished < nowMs && target.painDebounceTime <= nowMs) {\n const elapsedSeconds = Math.floor((nowMs - target.airFinished) / 1000);\n const amount = Math.min(15, 2 + 2 * elapsedSeconds);\n const result = applyDamageEvent(target, amount, DamageMod.WATER);\n target.painDebounceTime = nowMs + 1000;\n events.push({ mod: DamageMod.WATER, amount, result });\n }\n } else {\n target.airFinished = nowMs + 9000;\n if ((flags & EnvironmentalFlags.IN_WATER) === 0) {\n flags |= EnvironmentalFlags.IN_WATER;\n enteredWater = true;\n target.damageDebounceTime = 0;\n }\n\n if (target.damageDebounceTime <= nowMs) {\n if ((target.watertype & CONTENTS_LAVA) !== 0 && (flags & EnvironmentalFlags.IMMUNE_LAVA) === 0) {\n const amount = 10 * target.waterlevel;\n const result = applyDamageEvent(target, amount, DamageMod.LAVA);\n target.damageDebounceTime = nowMs + 100;\n events.push({ mod: DamageMod.LAVA, amount, result });\n } else if ((target.watertype & CONTENTS_SLIME) !== 0 && (flags & EnvironmentalFlags.IMMUNE_SLIME) === 0) {\n const amount = 4 * target.waterlevel;\n const result = applyDamageEvent(target, amount, DamageMod.SLIME);\n target.damageDebounceTime = nowMs + 100;\n events.push({ mod: DamageMod.SLIME, amount, result });\n }\n }\n }\n\n target.environmentFlags = flags;\n\n return { events, enteredWater, leftWater };\n}\n\nexport type FallingEvent = 'footstep' | 'fallshort' | 'fall' | 'fallfar' | null;\n\nexport interface FallingDamageContext {\n readonly impactDelta: number;\n readonly waterLevel: WaterLevel;\n readonly onLadder?: boolean;\n readonly isDead?: boolean;\n readonly isPlayerModel?: boolean;\n readonly isNoClip?: boolean;\n readonly grappleBlockingFallDamage?: boolean;\n readonly clampFreeFall?: boolean;\n readonly skipDamage?: boolean;\n}\n\nexport interface FallingDamageResult {\n readonly damage: number;\n readonly event: FallingEvent;\n readonly fallValue: number;\n readonly adjustedDelta: number;\n}\n\nexport function calculateFallingDamage(context: FallingDamageContext): FallingDamageResult {\n const {\n impactDelta,\n waterLevel,\n onLadder = false,\n isDead = false,\n isPlayerModel = true,\n isNoClip = false,\n grappleBlockingFallDamage = false,\n clampFreeFall = false,\n skipDamage = false,\n } = context;\n\n if (isDead || !isPlayerModel || isNoClip || grappleBlockingFallDamage || waterLevel === WaterLevel.Under) {\n return { damage: 0, event: null, fallValue: 0, adjustedDelta: 0 };\n }\n\n let delta = impactDelta * impactDelta * 0.0001;\n\n if (waterLevel === WaterLevel.Waist) {\n delta *= 0.25;\n } else if (waterLevel === WaterLevel.Feet) {\n delta *= 0.5;\n }\n\n if (clampFreeFall) {\n delta = Math.min(30, delta);\n }\n\n if (delta < 1) {\n return { damage: 0, event: null, fallValue: 0, adjustedDelta: delta };\n }\n\n let event: FallingEvent = null;\n let damage = 0;\n let fallValue = 0;\n\n if (delta < 15) {\n event = onLadder ? null : 'footstep';\n } else {\n fallValue = Math.min(delta * 0.5, 40);\n\n if (delta > 30) {\n event = delta >= 55 ? 'fallfar' : 'fall';\n damage = Math.max(1, (delta - 30) * 0.5);\n } else {\n event = 'fallshort';\n }\n }\n\n if (skipDamage) {\n damage = 0;\n }\n\n return { damage, event, fallValue, adjustedDelta: delta };\n}\n\nexport function applyFallingDamage(\n target: Damageable,\n context: FallingDamageContext,\n): FallingDamageResult {\n const result = calculateFallingDamage(context);\n\n if (result.damage > 0 && !context.skipDamage) {\n T_Damage(\n target,\n null,\n null,\n { x: 0, y: 0, z: 1 },\n target.origin,\n ZERO,\n result.damage,\n 0,\n DamageFlags.NO_ARMOR,\n DamageMod.FALLING,\n );\n }\n\n return result;\n}\n\nexport interface CrushableTarget extends Damageable {\n readonly isMonster?: boolean;\n readonly isClient?: boolean;\n}\n\nexport interface CrushDamageOptions {\n readonly baseDamage?: number;\n readonly nonLivingDamage?: number;\n readonly gibDamage?: number;\n}\n\nexport interface CrushDamageResult {\n readonly amount: number;\n readonly result: DamageApplicationResult | null;\n}\n\nexport function applyCrushDamage(\n crusher: Damageable,\n target: CrushableTarget,\n options: CrushDamageOptions = {},\n): CrushDamageResult {\n const nonLivingDamage = options.nonLivingDamage ?? 100_000;\n const gibDamage = options.gibDamage ?? 100;\n const baseDamage = options.baseDamage ?? (crusher as any).dmg ?? 10;\n\n const amount = !target.isMonster && !target.isClient ? nonLivingDamage : target.health < 1 ? gibDamage : baseDamage;\n const result = T_Damage(target, crusher, crusher, ZERO, target.origin, ZERO, amount, 1, DamageFlags.NONE, DamageMod.CRUSH);\n\n return { amount, result };\n}\n\nexport interface TelefragEntity extends Damageable {\n readonly movetype?: MoveType;\n readonly solid?: Solid;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface TelefragTarget extends Damageable {\n readonly inUse?: boolean;\n readonly movetype?: MoveType;\n readonly solid?: Solid;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface TelefragEvent {\n readonly target: TelefragTarget;\n readonly result: DamageApplicationResult | null;\n}\n\nexport interface TelefragResult {\n readonly events: TelefragEvent[];\n readonly cleared: boolean;\n}\n\nexport interface TelefragOptions {\n readonly mod?: DamageMod;\n}\n\nfunction absoluteBounds(ent: { readonly origin: Vec3; readonly mins?: Vec3; readonly maxs?: Vec3 }): Bounds3 {\n const mins = ent.mins ?? ZERO;\n const maxs = ent.maxs ?? ZERO;\n\n return {\n mins: addVec3(ent.origin, mins),\n maxs: addVec3(ent.origin, maxs),\n };\n}\n\nexport function killBox(\n teleporter: TelefragEntity,\n targets: readonly TelefragTarget[],\n options: TelefragOptions = {},\n): TelefragResult {\n if (teleporter.movetype === MoveType.Noclip) {\n return { events: [], cleared: true };\n }\n\n const mod = options.mod ?? DamageMod.TELEFRAG;\n const teleBounds = absoluteBounds(teleporter);\n const events: TelefragEvent[] = [];\n let cleared = true;\n\n for (const target of targets) {\n if (target === teleporter || target.inUse === false) {\n continue;\n }\n\n const solidity = target.solid ?? Solid.Not;\n if (!target.takedamage || solidity === Solid.Not || solidity === Solid.Trigger || solidity === Solid.Bsp) {\n continue;\n }\n\n if (!boxesIntersect(teleBounds, absoluteBounds(target))) {\n continue;\n }\n\n const result = T_Damage(target, teleporter, teleporter, ZERO, target.origin, ZERO, 100_000, 0, DamageFlags.NO_PROTECTION, mod);\n events.push({ target, result });\n\n if (!result || !result.killed || target.health > 0) {\n cleared = false;\n }\n }\n\n return { events, cleared };\n}\n","export enum AmmoType {\n Bullets = 0,\n Shells,\n Rockets,\n Grenades,\n Cells,\n Slugs,\n}\n\nexport const AMMO_TYPE_COUNT = Object.keys(AmmoType).length / 2;\n\nexport type AmmoCaps = readonly number[];\n\n/**\n * Mirrors the rerelease defaults in p_client.cpp where max ammo counts are\n * seeded to 50, then overridden for select types (bullets/shells/cells).\n */\nexport function createBaseAmmoCaps(): number[] {\n const caps = Array(AMMO_TYPE_COUNT).fill(50);\n caps[AmmoType.Bullets] = 200;\n caps[AmmoType.Shells] = 100;\n caps[AmmoType.Cells] = 200;\n return caps;\n}\n\nexport function clampAmmoCounts(counts: readonly number[], caps: AmmoCaps): number[] {\n const limit = Math.min(counts.length, caps.length);\n const clamped: number[] = counts.slice(0, limit);\n\n for (let i = 0; i < limit; i++) {\n const cap = caps[i];\n if (cap !== undefined) {\n clamped[i] = Math.min(counts[i], cap);\n }\n }\n\n return clamped;\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';\nexport * from './ai/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 { hashGameState } from './checksum.js';\nexport * from './save/index.js';\nexport * from './combat/index.js';\nexport * from './inventory/index.js';\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n"],"mappings":"wcAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,qBAAAE,KCOO,IAAMC,GAAkB,CAAE,EAAG,EAAG,EAAG,EAAG,EAAG,CAAE,EAK5CC,GAAa,KAAK,GAAK,IAUt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EAEnBC,EAASC,GAAa,CAAE,OAAQ,CAAE,MAAO,KAAO,CAAE,MAAOF,GAAW,IAAKA,GAAW,SAAU,CAAE,EAAG,CAAE,CAAC,EAEtGG,EAAUC,GAAoBV,EAAQI,EAAMG,CAAmC,EACrF,OAAAE,EAAQ,MAAM,EAEP,CAAE,OAAAT,EAAQ,KAAAI,EAAM,OAAAG,EAAQ,QAAAE,CAAQ,CACzC","names":["src_exports","__export","bootstrapViewer","ZERO_VEC3","DEG_TO_RAD","addVec3","a","b","scaleVec3","scalar","dotVec3","lengthSquaredVec3","lengthVec3","normalizeVec3","len","PITCH","YAW","ROLL","DEG2RAD_FACTOR","RAD2DEG_FACTOR","axisComponent","vec","axis","degToRad","degrees","angleMod","angle","value","angleVectors","angles","yaw","pitch","roll","sy","cy","sp","cp","sr","cr","forward","right","up","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_CHECKCOUNT","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_CONFIGSTRINGS","WaterLevel","PmFlag","hasPmFlag","flags","flag","PmType","PlayerButton","applyPmoveFriction","params","velocity","frametime","onGround","groundIsSlick","onLadder","waterlevel","pmFriction","pmStopSpeed","pmWaterFriction","speed","lengthVec3","drop","control","newspeed","scale","scaleVec3","applyPmoveAccelerate","wishdir","wishspeed","accel","currentSpeed","dotVec3","addSpeed","accelSpeed","applyPmoveAirAccelerate","wishspd","buildAirGroundWish","forward","right","cmd","maxSpeed","wishvel","normalizeVec3","buildWaterWish","addVec3","addAngles","cmdAngles","deltaAngles","clampPitch","pitch","clampViewAngles","params","pmFlags","viewangles","vectors","angleVectors","DEFAULTS","DEFAULT_GRAVITY","ZERO_VEC3","MSEC_MAX","defaultPredictionState","PmFlag","PmType","WaterLevel","normalizeState","state","lerp","a","b","t","lerpAngle","delta","angleMod","interpolatePredictionState","previous","latest","alpha","clamped","simulateCommand","cmd","settings","frametime","onGround","hasPmFlag","onLadder","velocity","applyPmoveFriction","viewangles","forward","right","clampViewAngles","wish","buildWaterWish","buildAirGroundWish","applyPmoveAccelerate","maxSpeed","clampedWish","applyPmoveAirAccelerate","originDelta","scaleVec3","origin","addVec3","ClientPrediction","frame","normalized","DEFAULT_SETTINGS","clampViewOffset","offset","computeBobMove","xyspeed","frameTimeMs","computeBobValues","previousBobTime","pmFlags","bobMove","bobTimeRun","bobTime","ViewEffects","kick","angleVectors","bobValues","pitchTilt","dotVec3","rollTilt","pitchDelta","rollDelta","bobHeight","kickPitch","kickRoll","ratio","sample","normalizeCommand","command","InputAction","BUTTON_ACTIONS","PlayerButton","ACTION_LOOKUP","action","normalizeCommand","createClient","imports","prediction","ClientPrediction","view","ViewEffects","latestFrame","lastRendered","lastView","initial","command","sample","interpolatePredictionState","frameTimeMs","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_CHECKCOUNT","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","RERELEASE_KNOWN_PAKS","FLOAT_BYTES","STRIDE","BSP_VERTEX_LAYOUT","SKYBOX_POSITIONS","createEngine","imports","callbacks","options","FixedTimestepLoop","ZERO_VEC3","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","STATE_SIZE","MIDDLE_WORD","MATRIX_A","UPPER_MASK","LOWER_MASK","TWO_POW_32","MersenneTwister19937","seed","i","prev","next","y","snapshot","value","RandomGenerator","options","minInclusive","maxExclusive","epsilon","span","limit","sample","minMs","maxMs","container","createRandomGenerator","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_CHECKCOUNT","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","DEFAULT_MONSTER_INFO","Entity","index","ENTITY_FIELD_METADATA","MAX_EDICTS","WORLD_INDEX","EntityPool","maxEntities","i","world","count","_","current","value","entity","activeOrder","snapshot","seen","noteIndex","label","ThinkScheduler","timeSeconds","a","b","time","entries","resolver","entry","currentTimeSeconds","next","computeBounds","boundsIntersect","SERIALIZABLE_FIELDS","field","DESCRIPTORS","descriptor","serializeVec3","vec","deserializeVec3","x","y","z","assignField","name","serializeInventory","inventory","deserializeInventory","parsed","key","EntitySystem","createRandomGenerator","callback","nextThinkSeconds","classname","matches","targetname","choice","targetBounds","other","activator","delayed","self","entities","fields","indexToEntity","pendingEntityRefs","serialized","ref","target","activeEntities","first","firstBounds","j","second","secondBounds","bucket","victim","FRAME_TIME_SECONDS","FIELD_LOOKUP","ENTITY_FIELD_METADATA","field","orderedStageNames","GameFrameLoop","initialStages","stageName","handler","stage","handlers","index","startTimeMs","step","previousTimeMs","context","i","writeIndex","readIndex","ZERO_STATE","LevelClock","startSeconds","state","FL_NOVISIBLE","SAVE_FORMAT_VERSION","MIN_SUPPORTED_VERSION","ensureObject","value","label","ensureNumber","ensureNumberOrDefault","defaultValue","ensureString","ensureNumberArray","element","parseLevelState","raw","level","parseRngState","RandomGenerator","rng","mt","state","parseThinkEntries","entry","idx","think","parseEntityFields","fields","parsed","name","object","inventory","entryName","entryValue","x","y","z","parseEntities","entity","parsePool","pool","parseEntitySnapshot","snapshot","parseCvars","cvar","parseConfigstrings","parseGameState","parseSaveFile","serialized","options","allowNewerVersion","raw","save","ensureObject","versionValue","SAVE_FORMAT_VERSION","version","ensureNumber","MIN_SUPPORTED_VERSION","ensureString","parseGameState","parseLevelState","parseRngState","parseEntitySnapshot","parseCvars","parseConfigstrings","TEXT_ENCODER_CTOR","cloneSave","save","parseSaveFile","estimateSizeBytes","MemorySaveAdapter","record","copy","id","IndexedDbSaveAdapter","indexedDB","dbName","storeName","resolve","reject","request","mode","operation","database","store","_SaveStorage","options","indexedDBFactory","slotId","normalized","metadata","a","b","AmmoType","AMMO_TYPE_COUNT","ZERO_VEC3","createGame","engine","options","gravity","levelClock","LevelClock","frameLoop","GameFrameLoop","entities","EntitySystem","context","deltaSeconds","velocity","origin","snapshot","frame","resetState","startTimeMs","step","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_CHECKCOUNT","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"]}
|
|
1
|
+
{"version":3,"sources":["../../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/protocol/contracts.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/shared/src/protocol/usercmd.ts","../../../../packages/client/src/prediction.ts","../../../../packages/client/src/view-effects.ts","../../../../packages/client/src/input/bindings.ts","../../../../packages/client/src/input/controller.ts","../../../../packages/client/src/input/command-buffer.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/protocol/contracts.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/shared/src/protocol/usercmd.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/pakValidation.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/assets/md3.ts","../../../../packages/engine/src/assets/animation.ts","../../../../packages/engine/src/assets/wal.ts","../../../../packages/engine/src/assets/pcx.ts","../../../../packages/engine/src/assets/texture.ts","../../../../packages/engine/src/assets/wav.ts","../../../../packages/engine/src/assets/ogg.ts","../../../../packages/engine/src/assets/audio.ts","../../../../packages/engine/src/assets/pakIndexStore.ts","../../../../packages/engine/src/assets/manager.ts","../../../../packages/engine/src/audio/constants.ts","../../../../packages/engine/src/audio/context.ts","../../../../packages/engine/src/audio/registry.ts","../../../../packages/engine/src/audio/precache.ts","../../../../packages/engine/src/audio/channels.ts","../../../../packages/engine/src/audio/spatialization.ts","../../../../packages/engine/src/audio/system.ts","../../../../packages/engine/src/audio/music.ts","../../../../packages/engine/src/audio/api.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/render/culling.ts","../../../../packages/engine/src/render/bspTraversal.ts","../../../../packages/engine/src/render/bspPipeline.ts","../../../../packages/engine/src/render/skybox.ts","../../../../packages/engine/src/render/md2Pipeline.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/protocol/contracts.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/shared/src/protocol/usercmd.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/entities/utils.ts","../../../../packages/game/src/entities/triggers.ts","../../../../packages/game/src/entities/spawn.ts","../../../../packages/game/src/loop.ts","../../../../packages/game/src/level.ts","../../../../packages/game/src/ai/constants.ts","../../../../packages/game/src/ai/movement.ts","../../../../packages/game/src/ai/perception.ts","../../../../packages/game/src/checksum.ts","../../../../packages/game/src/save/save.ts","../../../../packages/game/src/save/rerelease.ts","../../../../packages/game/src/save/storage.ts","../../../../packages/game/src/combat/damageFlags.ts","../../../../packages/game/src/combat/armor.ts","../../../../packages/game/src/combat/damage.ts","../../../../packages/game/src/combat/damageMods.ts","../../../../packages/game/src/combat/specialDamage.ts","../../../../packages/game/src/inventory/ammo.ts","../../../../packages/game/src/inventory/playerInventory.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/protocol/contracts.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/shared/src/protocol/usercmd.ts"],"sourcesContent":["import { createClient } from '@quake2ts/client';\nimport { ClientRenderer, 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 as unknown as ClientRenderer);\n runtime.start();\n\n return { engine, game, client, runtime };\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n","import {\n addVec3,\n angleMod,\n scaleVec3,\n type Vec3,\n buildAirGroundWish,\n buildWaterWish,\n clampViewAngles,\n hasPmFlag,\n PmFlag,\n PmType,\n WaterLevel,\n type PmFlags,\n type UserCommand,\n} from '@quake2ts/shared';\nimport {\n applyPmoveAccelerate,\n applyPmoveAirAccelerate,\n applyPmoveFriction,\n} from '@quake2ts/shared';\nimport type { GameFrameResult } from '@quake2ts/engine';\n\nexport interface PredictionState {\n readonly origin: Vec3;\n readonly velocity: Vec3;\n readonly viewangles: Vec3;\n readonly pmFlags: PmFlags;\n readonly pmType: PmType;\n readonly waterlevel: WaterLevel;\n readonly gravity: number;\n readonly deltaAngles?: Vec3;\n}\n\nexport interface PredictionSettings {\n readonly pmFriction: number;\n readonly pmStopSpeed: number;\n readonly pmAccelerate: number;\n readonly pmAirAccelerate: number;\n readonly pmWaterAccelerate: number;\n readonly pmWaterFriction: number;\n readonly pmMaxSpeed: number;\n readonly pmDuckSpeed: number;\n readonly pmWaterSpeed: number;\n readonly groundIsSlick: boolean;\n}\n\nconst DEFAULTS: PredictionSettings = {\n pmFriction: 6,\n pmStopSpeed: 100,\n pmAccelerate: 10,\n pmAirAccelerate: 1,\n pmWaterAccelerate: 4,\n pmWaterFriction: 1,\n pmMaxSpeed: 300,\n pmDuckSpeed: 100,\n pmWaterSpeed: 400,\n groundIsSlick: false,\n};\n\nconst DEFAULT_GRAVITY = 800;\nconst ZERO_VEC3: Vec3 = { x: 0, y: 0, z: 0 };\nconst MSEC_MAX = 250;\n\nexport function defaultPredictionState(): PredictionState {\n return {\n origin: ZERO_VEC3,\n velocity: ZERO_VEC3,\n viewangles: ZERO_VEC3,\n pmFlags: PmFlag.OnGround,\n pmType: PmType.Normal,\n waterlevel: WaterLevel.None,\n gravity: DEFAULT_GRAVITY,\n deltaAngles: ZERO_VEC3,\n } satisfies PredictionState;\n}\n\nfunction normalizeState(state: PredictionState | undefined): PredictionState {\n if (!state) return defaultPredictionState();\n\n return {\n ...defaultPredictionState(),\n ...state,\n origin: { ...state.origin },\n velocity: { ...state.velocity },\n viewangles: { ...state.viewangles },\n deltaAngles: state.deltaAngles ? { ...state.deltaAngles } : ZERO_VEC3,\n } satisfies PredictionState;\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpAngle(a: number, b: number, t: number): number {\n let delta = angleMod(b - a);\n if (delta > 180) {\n delta -= 360;\n }\n return angleMod(a + delta * t);\n}\n\nexport function interpolatePredictionState(\n previous: PredictionState,\n latest: PredictionState,\n alpha: number,\n): PredictionState {\n const clamped = Math.max(0, Math.min(alpha, 1));\n return {\n origin: {\n x: lerp(previous.origin.x, latest.origin.x, clamped),\n y: lerp(previous.origin.y, latest.origin.y, clamped),\n z: lerp(previous.origin.z, latest.origin.z, clamped),\n },\n velocity: {\n x: lerp(previous.velocity.x, latest.velocity.x, clamped),\n y: lerp(previous.velocity.y, latest.velocity.y, clamped),\n z: lerp(previous.velocity.z, latest.velocity.z, clamped),\n },\n viewangles: {\n x: lerpAngle(previous.viewangles.x, latest.viewangles.x, clamped),\n y: lerpAngle(previous.viewangles.y, latest.viewangles.y, clamped),\n z: lerpAngle(previous.viewangles.z, latest.viewangles.z, clamped),\n },\n pmFlags: latest.pmFlags,\n pmType: latest.pmType,\n waterlevel: latest.waterlevel,\n gravity: latest.gravity,\n deltaAngles: latest.deltaAngles,\n } satisfies PredictionState;\n}\n\nfunction simulateCommand(\n state: PredictionState,\n cmd: UserCommand,\n settings: PredictionSettings,\n): PredictionState {\n const frametime = Math.min(Math.max(cmd.msec, 0), MSEC_MAX) / 1000;\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n const onLadder = hasPmFlag(state.pmFlags, PmFlag.OnLadder);\n\n let velocity = applyPmoveFriction({\n velocity: state.velocity,\n frametime,\n onGround,\n groundIsSlick: settings.groundIsSlick,\n onLadder,\n waterlevel: state.waterlevel,\n pmFriction: settings.pmFriction,\n pmStopSpeed: settings.pmStopSpeed,\n pmWaterFriction: settings.pmWaterFriction,\n });\n\n const { viewangles, forward, right } = clampViewAngles({\n pmFlags: state.pmFlags,\n cmdAngles: cmd.angles,\n deltaAngles: state.deltaAngles ?? ZERO_VEC3,\n });\n\n const wish =\n state.waterlevel > WaterLevel.None\n ? buildWaterWish({ forward, right, cmd, maxSpeed: settings.pmWaterSpeed })\n : buildAirGroundWish({ forward, right, cmd, maxSpeed: settings.pmMaxSpeed });\n\n if (state.waterlevel > WaterLevel.None) {\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmWaterAccelerate,\n frametime,\n });\n } else if (onGround || onLadder) {\n const maxSpeed = hasPmFlag(state.pmFlags, PmFlag.Ducked) ? settings.pmDuckSpeed : settings.pmMaxSpeed;\n const clampedWish =\n wish.wishspeed > maxSpeed\n ? {\n wishdir: wish.wishdir,\n wishspeed: maxSpeed,\n }\n : wish;\n\n velocity = applyPmoveAccelerate({\n velocity,\n wishdir: clampedWish.wishdir,\n wishspeed: clampedWish.wishspeed,\n accel: settings.pmAccelerate,\n frametime,\n });\n } else {\n velocity = applyPmoveAirAccelerate({\n velocity,\n wishdir: wish.wishdir,\n wishspeed: wish.wishspeed,\n accel: settings.pmAirAccelerate,\n frametime,\n });\n velocity = { ...velocity, z: velocity.z - state.gravity * frametime };\n }\n\n const originDelta = scaleVec3(velocity, frametime);\n const origin = addVec3(state.origin, originDelta);\n\n return {\n ...state,\n origin,\n velocity,\n viewangles,\n } satisfies PredictionState;\n}\n\nexport class ClientPrediction {\n private readonly settings: PredictionSettings;\n private baseFrame: GameFrameResult<PredictionState> = {\n frame: 0,\n timeMs: 0,\n state: defaultPredictionState(),\n } satisfies GameFrameResult<PredictionState>;\n private commands: UserCommand[] = [];\n private predicted: PredictionState = defaultPredictionState();\n\n constructor(settings: Partial<PredictionSettings> = {}) {\n this.settings = { ...DEFAULTS, ...settings } satisfies PredictionSettings;\n this.predicted = this.baseFrame.state ?? defaultPredictionState();\n }\n\n setAuthoritative(frame: GameFrameResult<PredictionState>): PredictionState {\n const normalized = normalizeState(frame.state);\n this.baseFrame = { ...frame, state: normalized };\n this.commands = this.commands.filter((cmd) => (cmd.serverFrame ?? Number.MAX_SAFE_INTEGER) > frame.frame);\n return this.recompute();\n }\n\n enqueueCommand(cmd: UserCommand): PredictionState {\n this.commands.push(cmd);\n return this.recompute();\n }\n\n getPredictedState(): PredictionState {\n return this.predicted;\n }\n\n private recompute(): PredictionState {\n let state = normalizeState(this.baseFrame.state);\n\n for (const cmd of this.commands) {\n state = simulateCommand(state, cmd, this.settings);\n }\n\n this.predicted = state;\n return state;\n }\n}\n","import { ZERO_VEC3, angleVectors, clampViewAngles, dotVec3, hasPmFlag, PmFlag, type PmFlags, type Vec3 } from '@quake2ts/shared';\nimport type { PredictionState } from './prediction.js';\n\nexport interface ViewEffectSettings {\n readonly runPitch: number;\n readonly runRoll: number;\n readonly bobUp: number;\n readonly bobPitch: number;\n readonly bobRoll: number;\n readonly maxBobHeight: number;\n readonly maxBobAngle: number;\n}\n\nconst DEFAULT_SETTINGS: ViewEffectSettings = {\n runPitch: 0.002,\n runRoll: 0.005,\n bobUp: 0.005,\n bobPitch: 0.002,\n bobRoll: 0.002,\n maxBobHeight: 6,\n maxBobAngle: 1.2,\n};\n\nexport interface ViewKick {\n readonly pitch: number;\n readonly roll: number;\n readonly durationMs: number;\n}\n\nexport interface ActiveKick extends ViewKick {\n remainingMs: number;\n}\n\nexport interface ViewSample {\n readonly angles: Vec3;\n readonly offset: Vec3;\n readonly bobCycle: number;\n readonly bobCycleRun: number;\n readonly bobFracSin: number;\n readonly xyspeed: number;\n}\n\nfunction clampViewOffset(offset: Vec3): Vec3 {\n return {\n x: Math.max(-14, Math.min(14, offset.x)),\n y: Math.max(-14, Math.min(14, offset.y)),\n z: Math.max(-22, Math.min(30, offset.z)),\n };\n}\n\nfunction computeBobMove(xyspeed: number, onGround: boolean, frameTimeMs: number): number {\n if (!onGround) return 0;\n\n if (xyspeed > 210) return frameTimeMs / 400;\n if (xyspeed > 100) return frameTimeMs / 800;\n return frameTimeMs / 1600;\n}\n\nfunction computeBobValues(\n previousBobTime: number,\n xyspeed: number,\n pmFlags: PmFlags,\n onGround: boolean,\n frameTimeMs: number,\n): { bobTime: number; bobCycle: number; bobCycleRun: number; bobFracSin: number } {\n if (xyspeed < 5) {\n return { bobTime: 0, bobCycle: 0, bobCycleRun: 0, bobFracSin: 0 };\n }\n\n const bobMove = computeBobMove(xyspeed, onGround, frameTimeMs);\n const bobTimeRun = previousBobTime + bobMove;\n const crouched = hasPmFlag(pmFlags, PmFlag.Ducked) && onGround;\n const bobTime = crouched ? bobTimeRun * 4 : bobTimeRun;\n\n return {\n bobTime: bobTimeRun,\n bobCycle: Math.floor(bobTime),\n bobCycleRun: Math.floor(bobTimeRun),\n bobFracSin: Math.abs(Math.sin(bobTime * Math.PI)),\n };\n}\n\nexport class ViewEffects {\n private readonly settings: ViewEffectSettings;\n private bobTime = 0;\n private bobCycle = 0;\n private bobCycleRun = 0;\n private bobFracSin = 0;\n private kick: ActiveKick | undefined;\n private lastSample: ViewSample | undefined;\n\n constructor(settings: Partial<ViewEffectSettings> = {}) {\n this.settings = { ...DEFAULT_SETTINGS, ...settings } satisfies ViewEffectSettings;\n }\n\n addKick(kick: ViewKick): void {\n if (kick.durationMs <= 0) return;\n this.kick = { ...kick, remainingMs: kick.durationMs } satisfies ActiveKick;\n }\n\n get last(): ViewSample | undefined {\n return this.lastSample;\n }\n\n sample(state: PredictionState, frameTimeMs: number): ViewSample {\n const { forward, right } = angleVectors(\n clampViewAngles({ pmFlags: state.pmFlags, cmdAngles: state.viewangles, deltaAngles: state.deltaAngles ?? ZERO_VEC3 }).viewangles,\n );\n\n const xyspeed = Math.sqrt(state.velocity.x * state.velocity.x + state.velocity.y * state.velocity.y);\n const onGround = hasPmFlag(state.pmFlags, PmFlag.OnGround);\n\n const bobValues = computeBobValues(this.bobTime, xyspeed, state.pmFlags, onGround, frameTimeMs);\n this.bobTime = bobValues.bobTime;\n this.bobCycle = bobValues.bobCycle;\n this.bobCycleRun = bobValues.bobCycleRun;\n this.bobFracSin = bobValues.bobFracSin;\n\n // Velocity-based tilt\n let pitchTilt = dotVec3(state.velocity, forward) * this.settings.runPitch;\n let rollTilt = dotVec3(state.velocity, right) * this.settings.runRoll;\n\n // Bob tilt\n let pitchDelta = this.bobFracSin * this.settings.bobPitch * xyspeed;\n let rollDelta = this.bobFracSin * this.settings.bobRoll * xyspeed;\n if (hasPmFlag(state.pmFlags, PmFlag.Ducked) && onGround) {\n pitchDelta *= 6;\n rollDelta *= 6;\n }\n\n pitchTilt += Math.min(pitchDelta, this.settings.maxBobAngle);\n rollDelta = Math.min(rollDelta, this.settings.maxBobAngle);\n if (this.bobCycle & 1) rollDelta = -rollDelta;\n rollTilt += rollDelta;\n\n // Bob height\n const bobHeight = Math.min(this.bobFracSin * xyspeed * this.settings.bobUp, this.settings.maxBobHeight);\n\n let kickPitch = 0;\n let kickRoll = 0;\n\n // Apply active kick\n if (this.kick && this.kick.remainingMs > 0) {\n const ratio = Math.max(0, Math.min(1, this.kick.remainingMs / this.kick.durationMs));\n kickPitch += ratio * this.kick.pitch;\n kickRoll += ratio * this.kick.roll;\n this.kick.remainingMs = Math.max(0, this.kick.remainingMs - frameTimeMs);\n if (this.kick.remainingMs === 0) this.kick = undefined;\n }\n\n const angles: Vec3 = { x: pitchTilt + kickPitch, y: 0, z: rollTilt + kickRoll };\n const offset: Vec3 = { x: 0, y: 0, z: bobHeight };\n\n const sample: ViewSample = {\n angles,\n offset: clampViewOffset(offset),\n bobCycle: this.bobCycle,\n bobCycleRun: this.bobCycleRun,\n bobFracSin: this.bobFracSin,\n xyspeed,\n } satisfies ViewSample;\n this.lastSample = sample;\n return sample;\n }\n}\n","export type InputCode = string;\n\nexport interface BindingEntry {\n readonly code: InputCode;\n readonly command: string;\n}\n\nconst DEFAULT_BINDINGS: readonly BindingEntry[] = [\n { code: 'KeyW', command: '+forward' },\n { code: 'ArrowUp', command: '+forward' },\n { code: 'KeyS', command: '+back' },\n { code: 'ArrowDown', command: '+back' },\n { code: 'KeyA', command: '+moveleft' },\n { code: 'KeyD', command: '+moveright' },\n { code: 'Space', command: '+jump' },\n { code: 'ControlLeft', command: '+crouch' },\n { code: 'ShiftLeft', command: '+speed' },\n { code: 'Mouse1', command: '+attack' },\n { code: 'Mouse2', command: '+use' },\n { code: 'Mouse3', command: '+zoom' },\n { code: 'ArrowLeft', command: '+left' },\n { code: 'ArrowRight', command: '+right' },\n { code: 'PageUp', command: '+lookup' },\n { code: 'PageDown', command: '+lookdown' },\n { code: 'Gamepad0-Button7', command: '+attack' },\n { code: 'Gamepad0-Button6', command: '+zoom' },\n { code: 'Gamepad0-Button0', command: '+jump' },\n { code: 'Gamepad0-Button1', command: '+crouch' },\n { code: 'Gamepad0-Button2', command: '+use' },\n { code: 'Gamepad0-Button4', command: 'prevweapon' },\n { code: 'Gamepad0-Button5', command: 'nextweapon' },\n { code: 'Digit1', command: 'weapon 1' },\n { code: 'Digit2', command: 'weapon 2' },\n { code: 'Digit3', command: 'weapon 3' },\n { code: 'Digit4', command: 'weapon 4' },\n { code: 'Digit5', command: 'weapon 5' },\n { code: 'Digit6', command: 'weapon 6' },\n { code: 'Digit7', command: 'weapon 7' },\n { code: 'Digit8', command: 'weapon 8' },\n { code: 'Digit9', command: 'weapon 9' },\n { code: 'Digit0', command: 'weapon 10' },\n];\n\nexport type BindingMap = ReadonlyMap<InputCode, string>;\n\nexport class InputBindings {\n private readonly bindings = new Map<InputCode, string>();\n\n constructor(entries: Iterable<BindingEntry> = DEFAULT_BINDINGS) {\n for (const entry of entries) {\n this.bind(entry.code, entry.command);\n }\n }\n\n bind(code: InputCode, command: string): void {\n this.bindings.set(code, command);\n }\n\n unbind(code: InputCode): void {\n this.bindings.delete(code);\n }\n\n getBinding(code: InputCode): string | undefined {\n return this.bindings.get(code);\n }\n\n entries(): BindingMap {\n return new Map(this.bindings.entries());\n }\n}\n\nexport function createDefaultBindings(): InputBindings {\n return new InputBindings();\n}\n\nexport function normalizeInputCode(code: string): InputCode {\n return code;\n}\n\nexport function normalizeCommand(command: string): string {\n return command.trim().toLowerCase();\n}\n\n","import {\n DEFAULT_FORWARD_SPEED,\n DEFAULT_MOUSE_SENSITIVITY,\n DEFAULT_PITCH_SPEED,\n DEFAULT_SIDE_SPEED,\n DEFAULT_UP_SPEED,\n DEFAULT_YAW_SPEED,\n PlayerButton,\n addViewAngles,\n mouseDeltaToViewDelta,\n type MouseDelta,\n type UserCommand,\n type Vec3,\n} from '@quake2ts/shared';\nimport { InputBindings, normalizeCommand, normalizeInputCode, type InputCode } from './bindings.js';\n\nconst MSEC_MAX = 250;\n\nexport interface GamepadLikeButton {\n readonly pressed: boolean;\n readonly value: number;\n}\n\nexport interface GamepadLike {\n readonly axes: readonly number[];\n readonly buttons: readonly GamepadLikeButton[];\n readonly index?: number;\n readonly connected?: boolean;\n}\n\ninterface ButtonState {\n readonly active: boolean;\n readonly wasPressed: boolean;\n readonly fraction: number;\n}\n\nexport interface TouchInputState {\n readonly move?: { readonly x: number; readonly y: number };\n readonly look?: { readonly x: number; readonly y: number };\n readonly buttons?: Partial<Record<InputAction, boolean>>;\n}\n\nclass KeyButton {\n private readonly activeCodes = new Set<InputCode>();\n private downTime = 0;\n private msec = 0;\n private pressed = false;\n\n press(code: InputCode, now: number): boolean {\n if (this.activeCodes.has(code)) return false;\n\n this.activeCodes.add(code);\n this.pressed = true;\n if (this.activeCodes.size === 1) {\n this.downTime = now;\n return true;\n }\n\n return false;\n }\n\n release(code: InputCode, now: number): boolean {\n if (!this.activeCodes.delete(code)) return false;\n\n if (this.activeCodes.size === 0) {\n this.msec += now - this.downTime;\n this.downTime = 0;\n return true;\n }\n\n return false;\n }\n\n sample(frameMsec: number, now: number): ButtonState {\n if (frameMsec <= 0) {\n return { active: this.activeCodes.size > 0, wasPressed: this.pressed, fraction: 0 };\n }\n\n let total = this.msec;\n\n if (this.activeCodes.size > 0) {\n total += now - this.downTime;\n this.downTime = now;\n }\n\n this.msec = 0;\n\n const fraction = Math.min(total / frameMsec, 1);\n const wasPressed = this.pressed;\n this.pressed = false;\n\n return { active: this.activeCodes.size > 0, wasPressed, fraction };\n }\n}\n\nexport interface InputControllerOptions {\n readonly forwardSpeed?: number;\n readonly sideSpeed?: number;\n readonly upSpeed?: number;\n readonly yawSpeed?: number;\n readonly pitchSpeed?: number;\n readonly sensitivity?: number;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n readonly invertMouseY?: boolean;\n readonly runByDefault?: boolean;\n readonly requirePointerLock?: boolean;\n readonly jumpAddsUpMove?: boolean;\n readonly crouchAddsDownMove?: boolean;\n readonly mouseFilter?: boolean;\n readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n readonly gamepadDeadZone?: number;\n readonly gamepadLookScale?: number;\n readonly invertGamepadY?: boolean;\n}\n\nexport enum InputAction {\n Forward = '+forward',\n Back = '+back',\n MoveLeft = '+moveleft',\n MoveRight = '+moveright',\n MoveUp = '+moveup',\n MoveDown = '+movedown',\n Jump = '+jump',\n Crouch = '+crouch',\n Attack = '+attack',\n Use = '+use',\n Holster = '+holster',\n TurnLeft = '+left',\n TurnRight = '+right',\n LookUp = '+lookup',\n LookDown = '+lookdown',\n SpeedModifier = '+speed',\n Zoom = '+zoom',\n}\n\nconst BUTTON_ACTIONS: Partial<Record<InputAction, PlayerButton>> = {\n [InputAction.Attack]: PlayerButton.Attack,\n [InputAction.Use]: PlayerButton.Use,\n [InputAction.Holster]: PlayerButton.Holster,\n [InputAction.Jump]: PlayerButton.Jump,\n [InputAction.Crouch]: PlayerButton.Crouch,\n};\n\nconst ACTION_LOOKUP = new Map<string, InputAction>(\n Object.values(InputAction).map((action) => [normalizeCommand(action), action]),\n);\n\nfunction commandToAction(command: string): InputAction | undefined {\n return ACTION_LOOKUP.get(normalizeCommand(command));\n}\n\nfunction nowMs(): number {\n if (typeof performance !== 'undefined' && typeof performance.now === 'function') {\n return performance.now();\n }\n\n return Date.now();\n}\n\nexport class InputController {\n private readonly bindings: InputBindings;\n private readonly buttons = new Map<InputAction, KeyButton>();\n private viewAngles: Vec3 = { x: 0, y: 0, z: 0 };\n private pointerLocked = false;\n private mouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private previousMouseDelta: MouseDelta = { deltaX: 0, deltaY: 0 };\n private anyPressed = false;\n private commandQueue: string[] = [];\n private pendingGamepads: readonly (GamepadLike | null | undefined)[] | undefined;\n private readonly gamepadButtons = new Map<string, boolean>();\n private gamepadMove = { x: 0, y: 0 };\n private gamepadLook = { x: 0, y: 0 };\n private pendingTouchState: TouchInputState | undefined;\n private readonly touchButtons = new Map<InputAction, boolean>();\n private touchMove = { x: 0, y: 0 };\n private touchLook = { x: 0, y: 0 };\n\n private readonly forwardSpeed: number;\n private readonly sideSpeed: number;\n private readonly upSpeed: number;\n private readonly yawSpeed: number;\n private readonly pitchSpeed: number;\n private readonly sensitivity: number;\n private readonly sensitivityX?: number;\n private readonly sensitivityY?: number;\n private readonly invertMouseY: boolean;\n private readonly runByDefault: boolean;\n private readonly requirePointerLock: boolean;\n private readonly jumpAddsUpMove: boolean;\n private readonly crouchAddsDownMove: boolean;\n private readonly mouseFilter: boolean;\n private readonly getGamepads?: () => readonly (GamepadLike | null | undefined)[];\n private readonly gamepadDeadZone: number;\n private readonly gamepadLookScale: number;\n private readonly invertGamepadY: boolean;\n\n constructor(options: InputControllerOptions = {}, bindings = new InputBindings()) {\n this.bindings = bindings;\n this.forwardSpeed = options.forwardSpeed ?? DEFAULT_FORWARD_SPEED;\n this.sideSpeed = options.sideSpeed ?? DEFAULT_SIDE_SPEED;\n this.upSpeed = options.upSpeed ?? DEFAULT_UP_SPEED;\n this.yawSpeed = options.yawSpeed ?? DEFAULT_YAW_SPEED;\n this.pitchSpeed = options.pitchSpeed ?? DEFAULT_PITCH_SPEED;\n this.sensitivity = options.sensitivity ?? DEFAULT_MOUSE_SENSITIVITY;\n this.sensitivityX = options.sensitivityX;\n this.sensitivityY = options.sensitivityY;\n this.invertMouseY = options.invertMouseY ?? false;\n this.runByDefault = options.runByDefault ?? true;\n this.requirePointerLock = options.requirePointerLock ?? true;\n this.jumpAddsUpMove = options.jumpAddsUpMove ?? true;\n this.crouchAddsDownMove = options.crouchAddsDownMove ?? true;\n this.mouseFilter = options.mouseFilter ?? false;\n this.getGamepads = options.getGamepads;\n this.gamepadDeadZone = options.gamepadDeadZone ?? 0.15;\n this.gamepadLookScale = options.gamepadLookScale ?? 1;\n this.invertGamepadY = options.invertGamepadY ?? this.invertMouseY;\n }\n\n handleKeyDown(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, true, normalized, eventTimeMs);\n }\n\n handleKeyUp(code: string, eventTimeMs: number = nowMs()): void {\n const normalized = normalizeInputCode(code);\n const binding = this.bindings.getBinding(normalized);\n if (!binding) return;\n\n this.applyCommand(binding, false, normalized, eventTimeMs);\n }\n\n handleMouseButtonDown(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), true, code, eventTimeMs);\n }\n\n handleMouseButtonUp(button: number, eventTimeMs: number = nowMs()): void {\n const code = this.mouseButtonToCode(button);\n this.applyCommand(this.mouseButtonToCommand(code), false, code, eventTimeMs);\n }\n\n handleMouseMove(deltaX: number, deltaY: number): void {\n if (this.requirePointerLock && !this.pointerLocked) return;\n\n this.mouseDelta = {\n deltaX: this.mouseDelta.deltaX + deltaX,\n deltaY: this.mouseDelta.deltaY + deltaY,\n };\n }\n\n setPointerLocked(locked: boolean): void {\n this.pointerLocked = locked;\n }\n\n setGamepadState(gamepads: readonly (GamepadLike | null | undefined)[]): void {\n this.pendingGamepads = gamepads;\n }\n\n setTouchState(state: TouchInputState): void {\n this.pendingTouchState = state;\n }\n\n buildCommand(frameMsec: number, now: number = nowMs(), serverFrame?: number): UserCommand {\n this.pollGamepads(now);\n this.applyTouchState(now);\n\n const yawStep = (this.yawSpeed * frameMsec) / 1000;\n const pitchStep = (this.pitchSpeed * frameMsec) / 1000;\n\n const turnLeft = this.sample(InputAction.TurnLeft, frameMsec, now);\n const turnRight = this.sample(InputAction.TurnRight, frameMsec, now);\n const lookUp = this.sample(InputAction.LookUp, frameMsec, now);\n const lookDown = this.sample(InputAction.LookDown, frameMsec, now);\n\n let viewDelta: Vec3 = {\n x: (lookDown.fraction - lookUp.fraction) * pitchStep,\n y: (turnRight.fraction - turnLeft.fraction) * yawStep,\n z: 0,\n };\n\n if (this.gamepadLook.x !== 0 || this.gamepadLook.y !== 0) {\n const pitch = this.gamepadLook.y * (this.invertGamepadY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep * this.gamepadLookScale,\n y: viewDelta.y + this.gamepadLook.x * yawStep * this.gamepadLookScale,\n z: 0,\n };\n }\n\n if (this.touchLook.x !== 0 || this.touchLook.y !== 0) {\n const pitch = this.touchLook.y * (this.invertMouseY ? -1 : 1);\n viewDelta = {\n x: viewDelta.x + pitch * pitchStep,\n y: viewDelta.y + this.touchLook.x * yawStep,\n z: 0,\n };\n }\n\n if (this.pointerLocked || !this.requirePointerLock) {\n const sampledDelta = this.sampleMouseDelta();\n const mouseDelta = mouseDeltaToViewDelta(sampledDelta, {\n sensitivity: this.sensitivity,\n sensitivityX: this.sensitivityX,\n sensitivityY: this.sensitivityY,\n invertY: this.invertMouseY,\n });\n viewDelta = {\n x: viewDelta.x + mouseDelta.x,\n y: viewDelta.y + mouseDelta.y,\n z: 0,\n };\n }\n\n const angles = addViewAngles(this.viewAngles, viewDelta);\n this.viewAngles = angles;\n\n const forward = this.sample(InputAction.Forward, frameMsec, now);\n const back = this.sample(InputAction.Back, frameMsec, now);\n const moveLeft = this.sample(InputAction.MoveLeft, frameMsec, now);\n const moveRight = this.sample(InputAction.MoveRight, frameMsec, now);\n const moveUp = this.sample(InputAction.MoveUp, frameMsec, now);\n const moveDown = this.sample(InputAction.MoveDown, frameMsec, now);\n const speed = this.sample(InputAction.SpeedModifier, frameMsec, now);\n const jump = this.sample(InputAction.Jump, frameMsec, now);\n const crouch = this.sample(InputAction.Crouch, frameMsec, now);\n\n const speedScale = this.runByDefault\n ? speed.active\n ? 0.5\n : 1\n : speed.active\n ? 1\n : 0.5;\n\n let forwardmove = this.forwardSpeed * (forward.fraction - back.fraction) * speedScale;\n let sidemove = this.sideSpeed * (moveRight.fraction - moveLeft.fraction) * speedScale;\n let upmove = this.upSpeed * (moveUp.fraction - moveDown.fraction);\n\n if (this.gamepadMove.x !== 0 || this.gamepadMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.gamepadMove.y * speedScale;\n sidemove += this.sideSpeed * this.gamepadMove.x * speedScale;\n }\n\n if (this.touchMove.x !== 0 || this.touchMove.y !== 0) {\n forwardmove += this.forwardSpeed * this.touchMove.y * speedScale;\n sidemove += this.sideSpeed * this.touchMove.x * speedScale;\n }\n\n if (this.jumpAddsUpMove && jump.fraction > 0) {\n upmove += this.upSpeed * jump.fraction;\n }\n\n if (this.crouchAddsDownMove && crouch.fraction > 0) {\n upmove -= this.upSpeed * crouch.fraction;\n }\n\n forwardmove = this.clampMove(forwardmove, this.forwardSpeed);\n sidemove = this.clampMove(sidemove, this.sideSpeed);\n upmove = this.clampMove(upmove, this.upSpeed);\n\n let buttons = this.collectButtonBits(frameMsec, now);\n\n const msec = Math.min(Math.max(Math.round(frameMsec), 1), MSEC_MAX);\n\n if (this.anyPressed || buttons !== PlayerButton.None) {\n buttons |= PlayerButton.Any;\n }\n\n this.anyPressed = false;\n\n return {\n msec,\n buttons,\n angles: { ...this.viewAngles },\n forwardmove,\n sidemove,\n upmove,\n serverFrame,\n } satisfies UserCommand;\n }\n\n consumeConsoleCommands(): readonly string[] {\n const commands = this.commandQueue;\n this.commandQueue = [];\n return commands;\n }\n\n private pollGamepads(now: number): void {\n const gamepads = this.getGamepads?.() ?? this.pendingGamepads ?? [];\n this.pendingGamepads = undefined;\n\n this.gamepadMove = { x: 0, y: 0 };\n this.gamepadLook = { x: 0, y: 0 };\n\n const pressedThisFrame = new Set<InputCode>();\n\n for (const pad of gamepads) {\n if (!pad || pad.connected === false) continue;\n\n const index = pad.index ?? 0;\n const axes = pad.axes ?? [];\n\n this.gamepadMove = {\n x: this.mergeAnalog(this.gamepadMove.x, this.applyDeadZone(axes[0] ?? 0)),\n y: this.mergeAnalog(this.gamepadMove.y, -this.applyDeadZone(axes[1] ?? 0)),\n };\n\n this.gamepadLook = {\n x: this.mergeAnalog(this.gamepadLook.x, this.applyDeadZone(axes[2] ?? 0)),\n y: this.mergeAnalog(this.gamepadLook.y, this.applyDeadZone(axes[3] ?? 0)),\n };\n\n const buttons = pad.buttons ?? [];\n for (let i = 0; i < buttons.length; i++) {\n const button = buttons[i];\n if (!button) continue;\n\n const pressed = button.pressed || button.value > this.gamepadDeadZone;\n const code = this.gamepadButtonCode(index, i);\n if (pressed) pressedThisFrame.add(code);\n\n const wasPressed = this.gamepadButtons.get(code) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(this.bindings.getBinding(code), pressed, code, now);\n this.gamepadButtons.set(code, pressed);\n }\n }\n }\n\n for (const [code, wasPressed] of this.gamepadButtons.entries()) {\n if (wasPressed && !pressedThisFrame.has(code)) {\n this.applyCommand(this.bindings.getBinding(code), false, code, now);\n this.gamepadButtons.set(code, false);\n }\n }\n }\n\n private applyTouchState(now: number): void {\n const state = this.pendingTouchState;\n if (!state) return;\n\n this.pendingTouchState = undefined;\n\n if (state.move) {\n this.touchMove = {\n x: this.clampAnalog(state.move.x),\n y: this.clampAnalog(state.move.y),\n };\n }\n\n if (state.look) {\n this.touchLook = {\n x: this.clampAnalog(state.look.x),\n y: this.clampAnalog(state.look.y),\n };\n }\n\n if (state.buttons) {\n for (const [action, pressed] of Object.entries(state.buttons) as Array<\n [InputAction, boolean | undefined]\n >) {\n if (pressed === undefined) continue;\n\n const wasPressed = this.touchButtons.get(action) ?? false;\n if (pressed !== wasPressed) {\n this.applyCommand(action, pressed, this.touchButtonCode(action), now);\n this.touchButtons.set(action, pressed);\n }\n }\n }\n }\n\n private applyCommand(\n command: string | undefined,\n isDown: boolean,\n code: InputCode,\n eventTimeMs: number,\n ): void {\n if (!command) return;\n\n const action = commandToAction(command);\n if (action) {\n const button = this.lookupButton(action);\n if (isDown) {\n if (button.press(code, eventTimeMs)) {\n this.commandQueue.push(action);\n }\n this.anyPressed = true;\n } else if (button.release(code, eventTimeMs)) {\n this.commandQueue.push(action.replace('+', '-'));\n }\n } else if (isDown) {\n this.commandQueue.push(command);\n }\n }\n\n private sampleMouseDelta(): MouseDelta {\n const delta = this.mouseDelta;\n this.mouseDelta = { deltaX: 0, deltaY: 0 };\n\n if (!this.mouseFilter) {\n this.previousMouseDelta = delta;\n return delta;\n }\n\n const filtered = {\n deltaX: (delta.deltaX + this.previousMouseDelta.deltaX) * 0.5,\n deltaY: (delta.deltaY + this.previousMouseDelta.deltaY) * 0.5,\n } satisfies MouseDelta;\n\n this.previousMouseDelta = delta;\n return filtered;\n }\n\n private collectButtonBits(frameMsec: number, now: number): PlayerButton {\n let buttons = PlayerButton.None;\n\n for (const [action, bit] of Object.entries(BUTTON_ACTIONS) as Array<\n [InputAction, PlayerButton]\n >) {\n const sample = this.sample(action, frameMsec, now);\n if (sample.fraction > 0 || sample.active || sample.wasPressed) {\n buttons |= bit;\n }\n }\n\n return buttons;\n }\n\n private lookupButton(action: InputAction): KeyButton {\n let button = this.buttons.get(action);\n if (!button) {\n button = new KeyButton();\n this.buttons.set(action, button);\n }\n return button;\n }\n\n private mouseButtonToCode(button: number): InputCode {\n if (button === 0) return 'Mouse1';\n if (button === 1) return 'Mouse3';\n if (button === 2) return 'Mouse2';\n return `Mouse${button + 1}`;\n }\n\n private mouseButtonToCommand(code: InputCode): string | undefined {\n return this.bindings.getBinding(code);\n }\n\n private sample(action: InputAction, frameMsec: number, now: number): ButtonState {\n const button = this.lookupButton(action);\n return button.sample(frameMsec, now);\n }\n\n private gamepadButtonCode(index: number, button: number): InputCode {\n return `Gamepad${index}-Button${button}`;\n }\n\n private touchButtonCode(action: InputAction): InputCode {\n return `Touch-${action}`;\n }\n\n private clampAnalog(value: number): number {\n return Math.max(-1, Math.min(1, value));\n }\n\n private applyDeadZone(value: number): number {\n return Math.abs(value) < this.gamepadDeadZone ? 0 : value;\n }\n\n private mergeAnalog(current: number, incoming: number): number {\n return Math.abs(incoming) > Math.abs(current) ? incoming : current;\n }\n\n private clampMove(value: number, max: number): number {\n return Math.max(-max, Math.min(max, value));\n }\n}\n\n","import type { UserCommand } from '@quake2ts/shared';\nimport { InputController, type InputControllerOptions } from './controller.js';\n\nexport interface QueuedFrameCommands {\n readonly command: UserCommand;\n readonly console: readonly string[];\n}\n\nexport class InputCommandBuffer {\n private readonly controller: InputController;\n private readonly queued: QueuedFrameCommands[] = [];\n\n constructor(options?: InputControllerOptions, controller = new InputController(options)) {\n this.controller = controller;\n }\n\n captureFrame(frameMsec: number, now?: number, serverFrame?: number): QueuedFrameCommands {\n const command = this.controller.buildCommand(frameMsec, now, serverFrame);\n const console = this.controller.consumeConsoleCommands();\n const entry: QueuedFrameCommands = { command, console };\n this.queued.push(entry);\n return entry;\n }\n\n consumeQueued(): readonly QueuedFrameCommands[] {\n const queued = [...this.queued];\n this.queued.length = 0;\n return queued;\n }\n\n getController(): InputController {\n return this.controller;\n }\n}\n","import type {\n ClientRenderer,\n EngineImports,\n GameFrameResult,\n GameRenderSample,\n} from '@quake2ts/engine';\nimport type { UserCommand } from '@quake2ts/shared';\nimport { ClientPrediction, interpolatePredictionState } from './prediction.js';\nimport type { PredictionState } from './prediction.js';\nimport { ViewEffects, type ViewSample } from './view-effects.js';\nexport { createDefaultBindings, InputBindings, normalizeCommand, normalizeInputCode } from './input/bindings.js';\nexport {\n GamepadLike,\n GamepadLikeButton,\n InputAction,\n InputController,\n TouchInputState,\n type InputControllerOptions,\n} from './input/controller.js';\nexport {\n InputCommandBuffer,\n type QueuedFrameCommands,\n} from './input/command-buffer.js';\nexport {\n ClientPrediction,\n defaultPredictionState,\n interpolatePredictionState,\n type PredictionSettings,\n type PredictionState,\n} from './prediction.js';\nexport { ViewEffects, type ViewEffectSettings, type ViewKick, type ViewSample } from './view-effects.js';\n\nexport interface ClientImports {\n readonly engine: EngineImports;\n}\n\nexport interface ClientExports extends ClientRenderer<PredictionState> {\n predict(command: UserCommand): PredictionState;\n readonly prediction: ClientPrediction;\n readonly lastRendered?: PredictionState;\n readonly view: ViewEffects;\n readonly lastView?: ViewSample;\n}\n\nexport function createClient(imports: ClientImports): ClientExports {\n const prediction = new ClientPrediction();\n const view = new ViewEffects();\n let latestFrame: GameFrameResult<PredictionState> | undefined;\n let lastRendered: PredictionState | undefined;\n let lastView: ViewSample | undefined;\n\n return {\n init(initial) {\n latestFrame = initial;\n if (initial?.state) {\n prediction.setAuthoritative(initial);\n }\n void imports.engine.trace({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 });\n },\n predict(command: UserCommand): PredictionState {\n return prediction.enqueueCommand(command);\n },\n render(sample: GameRenderSample<PredictionState>): void {\n if (sample.latest?.state) {\n prediction.setAuthoritative(sample.latest);\n latestFrame = sample.latest;\n }\n\n if (sample.previous?.state && sample.latest?.state) {\n lastRendered = interpolatePredictionState(sample.previous.state, sample.latest.state, sample.alpha);\n } else {\n lastRendered = sample.latest?.state ?? sample.previous?.state ?? prediction.getPredictedState();\n }\n\n const frameTimeMs = sample.latest && sample.previous ? Math.max(0, sample.latest.timeMs - sample.previous.timeMs) : 0;\n lastView = view.sample(lastRendered, frameTimeMs);\n\n void imports;\n void sample;\n },\n shutdown() {\n latestFrame = undefined;\n lastRendered = undefined;\n },\n get prediction(): ClientPrediction {\n return prediction;\n },\n get lastRendered(): PredictionState | undefined {\n return lastRendered;\n },\n get view(): ViewEffects {\n return view;\n },\n get lastView(): ViewSample | undefined {\n return lastView;\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\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 findSoundIndex(path: string): number | undefined {\n for (let i = ConfigStringIndex.Sounds; i < ConfigStringIndex.Sounds + MAX_SOUNDS; i += 1) {\n if (this.values.get(i) === path) {\n return i;\n }\n }\n return undefined;\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, normalizePath, type PakValidationResult } from './pak.js';\n\nexport interface KnownPakChecksum {\n readonly name: string;\n readonly checksum: number;\n readonly size?: number;\n readonly description?: string;\n}\n\nexport interface PakValidationOutcome {\n readonly name: string;\n readonly checksum: number;\n readonly expectedChecksum?: number;\n readonly size?: number;\n readonly status: 'valid' | 'mismatch' | 'unknown';\n readonly description?: string;\n}\n\nexport const RERELEASE_KNOWN_PAKS: readonly KnownPakChecksum[] = Object.freeze([\n // Base campaign\n { name: 'pak0.pak', checksum: 0x8dbe2e6d, description: 'Base game assets' },\n { name: 'pak0.pak@baseq2', checksum: 0x8dbe2e6d, description: 'Base game assets (baseq2)' },\n // Mission packs bundled with the rerelease\n { name: 'pak0.pak@rogue', checksum: 0xc90f1e6d, description: 'Ground Zero (rogue) mission pack' },\n { name: 'pak0.pak@xatrix', checksum: 0x50f58d80, description: 'The Reckoning (xatrix) mission pack' },\n]);\n\nexport class PakValidationError extends Error {\n constructor(readonly result: PakValidationOutcome) {\n super(\n result.status === 'unknown'\n ? `Unknown PAK not allowed: ${result.name}`\n : `PAK checksum mismatch for ${result.name}`,\n );\n this.name = 'PakValidationError';\n }\n}\n\nexport class PakValidator {\n private readonly known = new Map<string, KnownPakChecksum>();\n\n constructor(knownPaks: readonly KnownPakChecksum[] = RERELEASE_KNOWN_PAKS) {\n knownPaks.forEach((pak) => this.known.set(this.normalizePakName(pak.name), pak));\n }\n\n validateArchive(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const pakName = this.normalizePakName(nameOverride ?? ('name' in archive ? archive.name : 'unknown'));\n const checksum = archive.checksum;\n const size = 'size' in archive ? archive.size : undefined;\n\n const known = this.known.get(pakName);\n if (!known) {\n return { name: pakName, checksum, status: 'unknown', size };\n }\n\n if (known.checksum !== checksum) {\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'mismatch',\n size,\n description: known.description,\n };\n }\n\n return {\n name: pakName,\n checksum,\n expectedChecksum: known.checksum,\n status: 'valid',\n size,\n description: known.description,\n };\n }\n\n assertValid(archive: PakArchive | PakValidationResult, nameOverride?: string): PakValidationOutcome {\n const outcome = this.validateArchive(archive, nameOverride);\n if (outcome.status === 'mismatch') {\n throw new PakValidationError(outcome);\n }\n return outcome;\n }\n\n private normalizePakName(name: string): string {\n const normalized = normalizePath(name);\n const parts = normalized.split('/');\n const filename = parts.pop() ?? normalized;\n const directory = parts.pop();\n return directory ? `${filename}@${directory}` : filename;\n }\n}\n","import { PakArchive } from './pak.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { PakIndexStore } from './pakIndexStore.js';\nimport { PakValidationError, PakValidator, type PakValidationOutcome } from './pakValidation.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 readonly validation?: PakValidationOutcome;\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 * Optional persistence target for PAK directory indexes. When provided, each successfully\n * parsed archive will be stored in IndexedDB so the browser can rebuild listings without\n * reparsing the binary payload.\n */\n readonly pakIndexStore?: PakIndexStore;\n /**\n * Whether to persist parsed PAK indexes. Defaults to true when a pakIndexStore is provided.\n */\n readonly persistIndexes?: boolean;\n /**\n * Optional checksum validator. When provided, PAKs whose checksums do not match the known list will\n * raise a PakValidationError unless `enforceValidation` is explicitly set to false.\n */\n readonly validator?: PakValidator;\n /**\n * Whether checksum mismatches should prevent mounting the archive. Defaults to true when a validator\n * is supplied.\n */\n readonly enforceValidation?: boolean;\n /**\n * Whether unknown PAKs (not present in the validator list) are allowed. Defaults to true.\n */\n readonly allowUnknownPaks?: boolean;\n /**\n * Callback invoked with the validation outcome when a validator is provided.\n */\n readonly onValidationResult?: (outcome: PakValidationOutcome) => void;\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 shouldPersist = options.persistIndexes ?? Boolean(options.pakIndexStore);\n const enforceValidation = options.enforceValidation ?? Boolean(options.validator);\n const allowUnknownPaks = options.allowUnknownPaks ?? true;\n const stopOnError = options.stopOnError ?? false;\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 const validation = options.validator?.validateArchive(archive);\n if (validation) {\n options.onValidationResult?.(validation);\n const isMismatch = validation.status === 'mismatch';\n const isUnknown = validation.status === 'unknown';\n if ((isMismatch && enforceValidation) || (isUnknown && !allowUnknownPaks)) {\n const validationError = new PakValidationError(validation);\n options.onError?.(source.name, validationError);\n if (stopOnError) {\n throw new PakIngestionError(source.name, validationError);\n }\n results.push({ archive, mounted: false, validation });\n continue;\n }\n }\n vfs.mountPak(archive);\n if (shouldPersist && options.pakIndexStore) {\n try {\n await options.pakIndexStore.persist(archive);\n } catch (error) {\n options.onError?.(source.name, error);\n if (stopOnError) {\n throw new PakIngestionError(source.name, error);\n }\n }\n }\n options.onProgress?.({ file: source.name, loadedBytes: buffer.byteLength, totalBytes: buffer.byteLength, state: 'parsed' });\n results.push({ archive, mounted: true, validation });\n } catch (error) {\n options.onProgress?.({ file: source.name, loadedBytes: 0, totalBytes: 0, state: 'error' });\n options.onError?.(source.name, error);\n\n if (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","import { Vec3 } from '@quake2ts/shared';\nimport { VirtualFileSystem } from './vfs.js';\n\nconst MD3_IDENT = 860898377; // 'IDP3'\nconst MD3_VERSION = 15;\n\nexport interface Md3Header {\n readonly ident: number;\n readonly version: number;\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly numTags: number;\n readonly numSurfaces: number;\n readonly numSkins: number;\n readonly ofsFrames: number;\n readonly ofsTags: number;\n readonly ofsSurfaces: number;\n readonly ofsEnd: number;\n}\n\nexport interface Md3Frame {\n readonly minBounds: Vec3;\n readonly maxBounds: Vec3;\n readonly localOrigin: Vec3;\n readonly radius: number;\n readonly name: string;\n}\n\nexport interface Md3Tag {\n readonly name: string;\n readonly origin: Vec3;\n readonly axis: readonly [Vec3, Vec3, Vec3];\n}\n\nexport interface Md3Triangle {\n readonly indices: readonly [number, number, number];\n}\n\nexport interface Md3Shader {\n readonly name: string;\n readonly shaderIndex: number;\n}\n\nexport interface Md3TexCoord {\n readonly s: number;\n readonly t: number;\n}\n\nexport interface Md3Vertex {\n readonly position: Vec3;\n readonly normal: Vec3;\n readonly latLng: number;\n}\n\nexport interface Md3Surface {\n readonly name: string;\n readonly flags: number;\n readonly numFrames: number;\n readonly shaders: readonly Md3Shader[];\n readonly triangles: readonly Md3Triangle[];\n readonly texCoords: readonly Md3TexCoord[];\n readonly vertices: readonly (readonly Md3Vertex[])[];\n}\n\nexport interface Md3Model {\n readonly header: Md3Header;\n readonly frames: readonly Md3Frame[];\n readonly tags: readonly Md3Tag[][];\n readonly surfaces: readonly Md3Surface[];\n}\n\nexport class Md3ParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Md3ParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n const bytes = new Uint8Array(view.buffer, view.byteOffset + offset, length);\n const decoded = new TextDecoder('utf-8').decode(bytes);\n return decoded.replace(/\\0.*$/, '').trim();\n}\n\nfunction decodeLatLngNormal(latLng: number): Vec3 {\n const lat = ((latLng >> 8) & 0xff) * (2 * Math.PI / 255);\n const lng = (latLng & 0xff) * (2 * Math.PI / 255);\n const sinLng = Math.sin(lng);\n return {\n x: Math.cos(lat) * sinLng,\n y: Math.sin(lat) * sinLng,\n z: Math.cos(lng),\n };\n}\n\nfunction validateOffset(name: string, offset: number, size: number, bufferLength: number): void {\n if (offset < 0 || offset + size > bufferLength) {\n throw new Md3ParseError(`${name} exceeds buffer bounds`);\n }\n}\n\nfunction parseHeader(view: DataView): Md3Header {\n const ident = view.getInt32(0, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid MD3 ident: ${ident}`);\n }\n const version = view.getInt32(4, true);\n if (version !== MD3_VERSION) {\n throw new Md3ParseError(`Unsupported MD3 version: ${version}`);\n }\n\n const name = readString(view, 8, 64);\n const flags = view.getInt32(72, true);\n const numFrames = view.getInt32(76, true);\n const numTags = view.getInt32(80, true);\n const numSurfaces = view.getInt32(84, true);\n const numSkins = view.getInt32(88, true);\n const ofsFrames = view.getInt32(92, true);\n const ofsTags = view.getInt32(96, true);\n const ofsSurfaces = view.getInt32(100, true);\n const ofsEnd = view.getInt32(104, true);\n\n if (numFrames <= 0 || numSurfaces < 0 || numTags < 0) {\n throw new Md3ParseError('Invalid MD3 counts');\n }\n\n return {\n ident,\n version,\n name,\n flags,\n numFrames,\n numTags,\n numSurfaces,\n numSkins,\n ofsFrames,\n ofsTags,\n ofsSurfaces,\n ofsEnd,\n };\n}\n\nfunction parseFrames(view: DataView, header: Md3Header): Md3Frame[] {\n const frames: Md3Frame[] = [];\n const frameSize = 56;\n validateOffset('Frames', header.ofsFrames, header.numFrames * frameSize, view.byteLength);\n\n for (let i = 0; i < header.numFrames; i += 1) {\n const base = header.ofsFrames + i * frameSize;\n frames.push({\n minBounds: {\n x: view.getFloat32(base, true),\n y: view.getFloat32(base + 4, true),\n z: view.getFloat32(base + 8, true),\n },\n maxBounds: {\n x: view.getFloat32(base + 12, true),\n y: view.getFloat32(base + 16, true),\n z: view.getFloat32(base + 20, true),\n },\n localOrigin: {\n x: view.getFloat32(base + 24, true),\n y: view.getFloat32(base + 28, true),\n z: view.getFloat32(base + 32, true),\n },\n radius: view.getFloat32(base + 36, true),\n name: readString(view, base + 40, 16),\n });\n }\n\n return frames;\n}\n\nfunction parseTags(view: DataView, header: Md3Header): Md3Tag[][] {\n const tags: Md3Tag[][] = [];\n const tagSize = 112;\n const totalSize = header.numFrames * header.numTags * tagSize;\n validateOffset('Tags', header.ofsTags, totalSize, view.byteLength);\n\n for (let frame = 0; frame < header.numFrames; frame += 1) {\n const frameTags: Md3Tag[] = [];\n for (let tagIndex = 0; tagIndex < header.numTags; tagIndex += 1) {\n const base = header.ofsTags + (frame * header.numTags + tagIndex) * tagSize;\n const originOffset = base + 64;\n const axisOffset = originOffset + 12;\n frameTags.push({\n name: readString(view, base, 64),\n origin: {\n x: view.getFloat32(originOffset, true),\n y: view.getFloat32(originOffset + 4, true),\n z: view.getFloat32(originOffset + 8, true),\n },\n axis: [\n {\n x: view.getFloat32(axisOffset, true),\n y: view.getFloat32(axisOffset + 4, true),\n z: view.getFloat32(axisOffset + 8, true),\n },\n {\n x: view.getFloat32(axisOffset + 12, true),\n y: view.getFloat32(axisOffset + 16, true),\n z: view.getFloat32(axisOffset + 20, true),\n },\n {\n x: view.getFloat32(axisOffset + 24, true),\n y: view.getFloat32(axisOffset + 28, true),\n z: view.getFloat32(axisOffset + 32, true),\n },\n ],\n });\n }\n tags.push(frameTags);\n }\n\n return tags;\n}\n\nfunction parseSurface(view: DataView, offset: number): { surface: Md3Surface; nextOffset: number } {\n const ident = view.getInt32(offset, true);\n if (ident !== MD3_IDENT) {\n throw new Md3ParseError(`Invalid surface ident at ${offset}: ${ident}`);\n }\n\n const name = readString(view, offset + 4, 64);\n const flags = view.getInt32(offset + 68, true);\n const numFrames = view.getInt32(offset + 72, true);\n const numShaders = view.getInt32(offset + 76, true);\n const numVerts = view.getInt32(offset + 80, true);\n const numTriangles = view.getInt32(offset + 84, true);\n const ofsTriangles = view.getInt32(offset + 88, true);\n const ofsShaders = view.getInt32(offset + 92, true);\n const ofsSt = view.getInt32(offset + 96, true);\n const ofsXyzNormals = view.getInt32(offset + 100, true);\n const ofsEnd = view.getInt32(offset + 104, true);\n\n if (numFrames <= 0 || numVerts <= 0 || numTriangles <= 0) {\n throw new Md3ParseError(`Invalid surface counts for ${name}`);\n }\n\n const surfaceSize = ofsEnd;\n validateOffset(`Surface ${name}`, offset, surfaceSize, view.byteLength);\n\n const triangles: Md3Triangle[] = [];\n const triangleStart = offset + ofsTriangles;\n for (let i = 0; i < numTriangles; i += 1) {\n const base = triangleStart + i * 12;\n triangles.push({\n indices: [view.getInt32(base, true), view.getInt32(base + 4, true), view.getInt32(base + 8, true)],\n });\n }\n\n const shaders: Md3Shader[] = [];\n const shaderStart = offset + ofsShaders;\n for (let i = 0; i < numShaders; i += 1) {\n const base = shaderStart + i * 68;\n shaders.push({ name: readString(view, base, 64), shaderIndex: view.getInt32(base + 64, true) });\n }\n\n const texCoords: Md3TexCoord[] = [];\n const stStart = offset + ofsSt;\n for (let i = 0; i < numVerts; i += 1) {\n const base = stStart + i * 8;\n texCoords.push({ s: view.getFloat32(base, true), t: view.getFloat32(base + 4, true) });\n }\n\n const vertices: Md3Vertex[][] = [];\n const xyzStart = offset + ofsXyzNormals;\n for (let frame = 0; frame < numFrames; frame += 1) {\n const frameVertices: Md3Vertex[] = [];\n for (let i = 0; i < numVerts; i += 1) {\n const base = xyzStart + (frame * numVerts + i) * 8;\n const x = view.getInt16(base, true) / 64;\n const y = view.getInt16(base + 2, true) / 64;\n const z = view.getInt16(base + 4, true) / 64;\n const latLng = view.getUint16(base + 6, true);\n frameVertices.push({ position: { x, y, z }, latLng, normal: decodeLatLngNormal(latLng) });\n }\n vertices.push(frameVertices);\n }\n\n return {\n surface: { name, flags, numFrames, shaders, triangles, texCoords, vertices },\n nextOffset: offset + ofsEnd,\n };\n}\n\nexport function parseMd3(buffer: ArrayBufferLike): Md3Model {\n if (buffer.byteLength < 108) {\n throw new Md3ParseError('MD3 buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const header = parseHeader(view);\n validateOffset('MD3 end', header.ofsEnd, 0, buffer.byteLength);\n\n const frames = parseFrames(view, header);\n const tags = parseTags(view, header);\n\n const surfaces: Md3Surface[] = [];\n let surfaceOffset = header.ofsSurfaces;\n for (let i = 0; i < header.numSurfaces; i += 1) {\n const { surface, nextOffset } = parseSurface(view, surfaceOffset);\n surfaces.push(surface);\n surfaceOffset = nextOffset;\n }\n\n if (surfaceOffset !== header.ofsEnd) {\n throw new Md3ParseError('Surface parsing did not reach ofsEnd');\n }\n\n return { header, frames, tags, surfaces };\n}\n\nexport class Md3Loader {\n constructor(private readonly vfs: VirtualFileSystem) {}\n\n async load(path: string): Promise<Md3Model> {\n const data = await this.vfs.readFile(path);\n return parseMd3(data.slice().buffer);\n }\n}\n","export interface FrameBlend {\n readonly frame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface AnimationSequence {\n readonly name: string;\n readonly start: number;\n readonly end: number;\n readonly fps: number;\n readonly loop?: boolean;\n}\n\nexport interface AnimationState {\n readonly sequence: AnimationSequence;\n readonly time: number;\n}\n\nexport function advanceAnimation(state: AnimationState, deltaSeconds: number): AnimationState {\n const duration = (state.sequence.end - state.sequence.start + 1) / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n let time = state.time + deltaSeconds;\n\n if (loop) {\n time = ((time % duration) + duration) % duration;\n } else if (time > duration) {\n time = duration;\n }\n\n return { ...state, time: Math.max(0, Math.min(time, duration)) };\n}\n\nexport function computeFrameBlend(state: AnimationState): FrameBlend {\n const totalFrames = state.sequence.end - state.sequence.start + 1;\n const frameDuration = 1 / state.sequence.fps;\n const loop = state.sequence.loop !== false;\n const framePosition = state.time / frameDuration;\n\n if (!loop && framePosition >= totalFrames) {\n return { frame: state.sequence.end, nextFrame: state.sequence.end, lerp: 0 };\n }\n\n const normalizedPosition = loop ? framePosition % totalFrames : Math.min(framePosition, totalFrames - 1);\n const baseFrame = Math.floor(normalizedPosition);\n const frame = state.sequence.start + baseFrame;\n const nextFrame = baseFrame + 1 >= totalFrames ? (loop ? state.sequence.start : state.sequence.end) : frame + 1;\n const lerp = !loop && baseFrame >= totalFrames - 1 ? 0 : normalizedPosition - baseFrame;\n return { frame, nextFrame, lerp };\n}\n\nexport function createAnimationState(sequence: AnimationSequence): AnimationState {\n return { sequence, time: 0 };\n}\n\nexport function interpolateVec3(\n a: { x: number; y: number; z: number },\n b: { x: number; y: number; z: number },\n t: number,\n): { x: number; y: number; z: number } {\n return {\n x: a.x + (b.x - a.x) * t,\n y: a.y + (b.y - a.y) * t,\n z: a.z + (b.z - a.z) * t,\n };\n}\n","export interface WalTexture {\n readonly name: string;\n readonly width: number;\n readonly height: number;\n readonly mipmaps: readonly WalMipmap[];\n readonly animName: string;\n readonly flags: number;\n readonly contents: number;\n readonly value: number;\n}\n\nexport interface WalMipmap {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly data: Uint8Array;\n}\n\nexport class WalParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WalParseError';\n }\n}\n\nexport function parseWal(buffer: ArrayBuffer): WalTexture {\n if (buffer.byteLength < 100) {\n throw new WalParseError('WAL buffer too small');\n }\n\n const view = new DataView(buffer);\n const nameBytes = new Uint8Array(buffer, 0, 32);\n const name = new TextDecoder('utf-8').decode(nameBytes).replace(/\\0.*$/, '').trim();\n const width = view.getInt32(32, true);\n const height = view.getInt32(36, true);\n const offsets = [view.getInt32(40, true), view.getInt32(44, true), view.getInt32(48, true), view.getInt32(52, true)];\n const animNameBytes = new Uint8Array(buffer, 56, 32);\n const animName = new TextDecoder('utf-8').decode(animNameBytes).replace(/\\0.*$/, '').trim();\n const flags = view.getInt32(88, true);\n const contents = view.getInt32(92, true);\n const value = view.getInt32(96, true);\n\n if (width <= 0 || height <= 0) {\n throw new WalParseError('Invalid WAL dimensions');\n }\n\n const mipmaps: WalMipmap[] = [];\n let currentWidth = width;\n let currentHeight = height;\n\n for (let level = 0; level < offsets.length; level += 1) {\n const offset = offsets[level];\n const expectedSize = Math.max(1, (currentWidth * currentHeight) | 0);\n if (offset <= 0 || offset + expectedSize > buffer.byteLength) {\n throw new WalParseError(`Invalid WAL mip offset for level ${level}`);\n }\n const data = new Uint8Array(buffer, offset, expectedSize);\n mipmaps.push({ level, width: currentWidth, height: currentHeight, data });\n currentWidth = Math.max(1, currentWidth >> 1);\n currentHeight = Math.max(1, currentHeight >> 1);\n }\n\n return { name, width, height, mipmaps, animName, flags, contents, value };\n}\n","export interface PcxImage {\n readonly width: number;\n readonly height: number;\n readonly bitsPerPixel: number;\n readonly pixels: Uint8Array;\n readonly palette: Uint8Array;\n}\n\nexport class PcxParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'PcxParseError';\n }\n}\n\nexport function parsePcx(buffer: ArrayBuffer): PcxImage {\n if (buffer.byteLength < 128) {\n throw new PcxParseError('PCX buffer too small for header');\n }\n\n const view = new DataView(buffer);\n const manufacturer = view.getUint8(0);\n const encoding = view.getUint8(2);\n const bitsPerPixel = view.getUint8(3);\n const xMin = view.getUint16(4, true);\n const yMin = view.getUint16(6, true);\n const xMax = view.getUint16(8, true);\n const yMax = view.getUint16(10, true);\n\n if (manufacturer !== 0x0a || encoding !== 1) {\n throw new PcxParseError('Unsupported PCX encoding');\n }\n if (bitsPerPixel !== 8) {\n throw new PcxParseError('Only 8bpp PCX files are supported');\n }\n\n const width = xMax - xMin + 1;\n const height = yMax - yMin + 1;\n const bytesPerLine = view.getUint16(66, true);\n\n const paletteMarkerOffset = buffer.byteLength - 769;\n if (paletteMarkerOffset < 128 || new DataView(buffer, paletteMarkerOffset, 1).getUint8(0) !== 0x0c) {\n throw new PcxParseError('Missing PCX palette');\n }\n\n const palette = new Uint8Array(buffer, paletteMarkerOffset + 1, 768);\n const encoded = new Uint8Array(buffer, 128, paletteMarkerOffset - 128);\n const pixels = new Uint8Array(width * height);\n\n let srcIndex = 0;\n let dstIndex = 0;\n\n for (let y = 0; y < height; y += 1) {\n let written = 0;\n while (written < bytesPerLine && srcIndex < encoded.length) {\n let count = 1;\n let value = encoded[srcIndex++]!;\n\n if ((value & 0xc0) === 0xc0) {\n count = value & 0x3f;\n if (srcIndex >= encoded.length) {\n throw new PcxParseError('Unexpected end of PCX RLE data');\n }\n value = encoded[srcIndex++]!;\n }\n\n for (let i = 0; i < count && written < bytesPerLine; i += 1) {\n if (written < width) {\n pixels[dstIndex++] = value;\n }\n written += 1;\n }\n }\n }\n\n return { width, height, bitsPerPixel, pixels, palette };\n}\n\nexport function pcxToRgba(image: PcxImage): Uint8Array {\n const rgba = new Uint8Array(image.width * image.height * 4);\n for (let i = 0; i < image.pixels.length; i += 1) {\n const colorIndex = image.pixels[i]!;\n const paletteIndex = colorIndex * 3;\n const rgbaIndex = i * 4;\n rgba[rgbaIndex] = image.palette[paletteIndex]!;\n rgba[rgbaIndex + 1] = image.palette[paletteIndex + 1]!;\n rgba[rgbaIndex + 2] = image.palette[paletteIndex + 2]!;\n rgba[rgbaIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n return rgba;\n}\n","import { LruCache } from './cache.js';\nimport { pcxToRgba, type PcxImage } from './pcx.js';\nimport { parseWal, type WalTexture } from './wal.js';\n\nexport interface PreparedTexture {\n readonly width: number;\n readonly height: number;\n readonly levels: readonly TextureLevel[];\n readonly source: 'pcx' | 'wal';\n}\n\nexport interface TextureLevel {\n readonly level: number;\n readonly width: number;\n readonly height: number;\n readonly rgba: Uint8Array;\n}\n\nexport interface TextureCacheOptions {\n readonly capacity?: number;\n}\n\nexport class TextureCache {\n private readonly cache: LruCache<PreparedTexture>;\n\n constructor(options: TextureCacheOptions = {}) {\n this.cache = new LruCache<PreparedTexture>(options.capacity ?? 128);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n get(key: string): PreparedTexture | undefined {\n return this.cache.get(key.toLowerCase());\n }\n\n set(key: string, texture: PreparedTexture): void {\n this.cache.set(key.toLowerCase(), texture);\n }\n\n clear(): void {\n this.cache.clear();\n }\n}\n\nexport function walToRgba(wal: WalTexture, palette: Uint8Array): PreparedTexture {\n const levels: TextureLevel[] = [];\n for (const mip of wal.mipmaps) {\n const rgba = new Uint8Array(mip.width * mip.height * 4);\n for (let i = 0; i < mip.data.length; i += 1) {\n const colorIndex = mip.data[i]!;\n const paletteIndex = colorIndex * 3;\n const outIndex = i * 4;\n rgba[outIndex] = palette[paletteIndex]!;\n rgba[outIndex + 1] = palette[paletteIndex + 1]!;\n rgba[outIndex + 2] = palette[paletteIndex + 2]!;\n rgba[outIndex + 3] = colorIndex === 255 ? 0 : 255;\n }\n levels.push({ level: mip.level, width: mip.width, height: mip.height, rgba });\n }\n\n return { width: wal.width, height: wal.height, levels, source: 'wal' };\n}\n\nexport function preparePcxTexture(pcx: PcxImage): PreparedTexture {\n const rgba = pcxToRgba(pcx);\n const level: TextureLevel = { level: 0, width: pcx.width, height: pcx.height, rgba };\n return { width: pcx.width, height: pcx.height, levels: [level], source: 'pcx' };\n}\n\nexport function parseWalTexture(buffer: ArrayBuffer, palette: Uint8Array): PreparedTexture {\n return walToRgba(parseWal(buffer), palette);\n}\n","export interface WavData {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitsPerSample: number;\n readonly samples: Float32Array;\n}\n\nexport class WavParseError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'WavParseError';\n }\n}\n\nfunction readString(view: DataView, offset: number, length: number): string {\n return new TextDecoder('ascii').decode(new Uint8Array(view.buffer, view.byteOffset + offset, length));\n}\n\nexport function parseWav(buffer: ArrayBuffer): WavData {\n if (buffer.byteLength < 44) {\n throw new WavParseError('WAV buffer too small');\n }\n\n const view = new DataView(buffer);\n if (readString(view, 0, 4) !== 'RIFF' || readString(view, 8, 4) !== 'WAVE') {\n throw new WavParseError('Invalid WAV header');\n }\n\n let offset = 12;\n let fmtOffset = -1;\n let dataOffset = -1;\n let fmtSize = 0;\n let dataSize = 0;\n\n while (offset + 8 <= buffer.byteLength) {\n const chunkId = readString(view, offset, 4);\n const chunkSize = view.getUint32(offset + 4, true);\n const chunkDataOffset = offset + 8;\n\n if (chunkId === 'fmt ') {\n fmtOffset = chunkDataOffset;\n fmtSize = chunkSize;\n } else if (chunkId === 'data') {\n dataOffset = chunkDataOffset;\n dataSize = chunkSize;\n }\n\n offset = chunkDataOffset + chunkSize;\n }\n\n if (fmtOffset === -1 || dataOffset === -1) {\n throw new WavParseError('Missing fmt or data chunk');\n }\n\n const audioFormat = view.getUint16(fmtOffset, true);\n const channels = view.getUint16(fmtOffset + 2, true);\n const sampleRate = view.getUint32(fmtOffset + 4, true);\n const bitsPerSample = view.getUint16(fmtOffset + 14, true);\n\n if (audioFormat !== 1) {\n throw new WavParseError('Only PCM WAV is supported');\n }\n\n const bytesPerSample = bitsPerSample / 8;\n const frameCount = dataSize / (bytesPerSample * channels);\n const samples = new Float32Array(frameCount * channels);\n\n for (let frame = 0; frame < frameCount; frame += 1) {\n for (let ch = 0; ch < channels; ch += 1) {\n const sampleIndex = frame * channels + ch;\n const byteOffset = dataOffset + sampleIndex * bytesPerSample;\n let value = 0;\n if (bitsPerSample === 8) {\n value = view.getUint8(byteOffset);\n samples[sampleIndex] = (value - 128) / 128;\n } else if (bitsPerSample === 16) {\n value = view.getInt16(byteOffset, true);\n samples[sampleIndex] = value / 32768;\n } else if (bitsPerSample === 24) {\n const b0 = view.getUint8(byteOffset);\n const b1 = view.getUint8(byteOffset + 1);\n const b2 = view.getInt8(byteOffset + 2);\n value = b0 | (b1 << 8) | (b2 << 16);\n samples[sampleIndex] = value / 8388608;\n } else {\n throw new WavParseError(`Unsupported bitsPerSample: ${bitsPerSample}`);\n }\n }\n }\n\n return { sampleRate, channels, bitsPerSample, samples };\n}\n","import { OggVorbisDecoder } from '@wasm-audio-decoders/ogg-vorbis';\n\nexport interface OggAudio {\n readonly sampleRate: number;\n readonly channels: number;\n readonly bitDepth: number;\n readonly channelData: readonly Float32Array[];\n}\n\nexport class OggDecodeError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OggDecodeError';\n }\n}\n\nexport async function decodeOgg(buffer: ArrayBuffer, decoder: OggVorbisDecoder = new OggVorbisDecoder()): Promise<OggAudio> {\n await decoder.ready;\n const result = await decoder.decode(new Uint8Array(buffer));\n\n const errors = (result as { errors?: { message: string }[] }).errors;\n if (errors && errors.length > 0) {\n throw new OggDecodeError(errors.map((err) => err.message).join('; '));\n }\n\n return {\n sampleRate: result.sampleRate,\n channels: result.channelData.length,\n bitDepth: result.bitDepth,\n channelData: result.channelData,\n };\n}\n","import { decodeOgg, type OggAudio } from './ogg.js';\nimport { parseWav } from './wav.js';\nimport { VirtualFileSystem } from './vfs.js';\nimport { LruCache } from './cache.js';\n\nexport type DecodedAudio = OggAudio;\n\nexport class AudioRegistryError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AudioRegistryError';\n }\n}\n\nexport interface AudioRegistryOptions {\n readonly cacheSize?: number;\n}\n\nexport class AudioRegistry {\n private readonly cache: LruCache<DecodedAudio>;\n private readonly refCounts = new Map<string, number>();\n\n constructor(private readonly vfs: VirtualFileSystem, options: AudioRegistryOptions = {}) {\n this.cache = new LruCache<DecodedAudio>(options.cacheSize ?? 64);\n }\n\n get size(): number {\n return this.cache.size;\n }\n\n async load(path: string): Promise<DecodedAudio> {\n const normalized = path.toLowerCase();\n const cached = this.cache.get(normalized);\n if (cached) {\n this.refCounts.set(normalized, (this.refCounts.get(normalized) ?? 0) + 1);\n return cached;\n }\n\n const data = await this.vfs.readFile(path);\n const arrayBuffer = data.slice().buffer;\n const audio = await this.decodeByExtension(path, arrayBuffer);\n this.cache.set(normalized, audio);\n this.refCounts.set(normalized, 1);\n return audio;\n }\n\n release(path: string): void {\n const normalized = path.toLowerCase();\n const count = this.refCounts.get(normalized) ?? 0;\n if (count <= 1) {\n this.cache.delete(normalized);\n this.refCounts.delete(normalized);\n } else {\n this.refCounts.set(normalized, count - 1);\n }\n }\n\n clearAll(): void {\n this.cache.clear();\n this.refCounts.clear();\n }\n\n private async decodeByExtension(path: string, buffer: ArrayBuffer): Promise<DecodedAudio> {\n const lower = path.toLowerCase();\n if (lower.endsWith('.wav')) {\n const wav = parseWav(buffer);\n const channels = wav.channels;\n const channelData: Float32Array[] = Array.from({ length: channels }, () => new Float32Array(wav.samples.length / channels));\n for (let i = 0; i < wav.samples.length; i += 1) {\n channelData[i % channels]![Math.floor(i / channels)] = wav.samples[i]!;\n }\n return { sampleRate: wav.sampleRate, channels, bitDepth: wav.bitsPerSample, channelData } satisfies OggAudio;\n }\n if (lower.endsWith('.ogg') || lower.endsWith('.oga')) {\n return decodeOgg(buffer);\n }\n throw new AudioRegistryError(`Unsupported audio format: ${path}`);\n }\n}\n","import { PakArchive, type PakDirectoryEntry, type PakValidationResult, normalizePath } from './pak.js';\n\nconst DEFAULT_DB_NAME = 'quake2ts-pak-indexes';\nconst DEFAULT_STORE_NAME = 'pak-indexes';\n\nexport interface StoredPakIndex extends PakValidationResult {\n readonly key: string;\n readonly name: string;\n readonly size: number;\n readonly persistedAt: number;\n}\n\nfunction getIndexedDb(): IDBFactory | undefined {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof window !== 'undefined' && 'indexedDB' in window) {\n return window.indexedDB;\n }\n if (typeof globalThis !== 'undefined' && 'indexedDB' in globalThis) {\n return (globalThis as unknown as { indexedDB?: IDBFactory }).indexedDB;\n }\n return undefined;\n}\n\nfunction openDatabase(dbName: string, storeName: string): Promise<IDBDatabase> {\n const idb = getIndexedDb();\n if (!idb) {\n return Promise.reject(new Error('IndexedDB is not available in this environment'));\n }\n\n return new Promise<IDBDatabase>((resolve, reject) => {\n const request = idb.open(dbName, 1);\n\n request.onupgradeneeded = () => {\n const { result } = request;\n if (!result.objectStoreNames.contains(storeName)) {\n result.createObjectStore(storeName, { keyPath: 'key' });\n }\n };\n\n request.onerror = () => reject(request.error ?? new Error('Unknown IndexedDB error'));\n request.onsuccess = () => resolve(request.result);\n });\n}\n\nfunction runTransaction<T>(\n db: IDBDatabase,\n storeName: string,\n mode: IDBTransactionMode,\n runner: (store: IDBObjectStore) => IDBRequest<T>,\n): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n const transaction = db.transaction(storeName, mode);\n const store = transaction.objectStore(storeName);\n const request = runner(store);\n\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB transaction error'));\n });\n}\n\nfunction buildKey(name: string, checksum: number): string {\n return `${normalizePath(name)}:${checksum.toString(16)}`;\n}\n\nfunction cloneEntries(entries: readonly PakDirectoryEntry[]): PakDirectoryEntry[] {\n return entries.map((entry) => ({ ...entry }));\n}\n\nexport class PakIndexStore {\n constructor(\n private readonly dbName = DEFAULT_DB_NAME,\n private readonly storeName = DEFAULT_STORE_NAME,\n ) {}\n\n get isSupported(): boolean {\n return Boolean(getIndexedDb());\n }\n\n async persist(archive: PakArchive): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n\n const validation = archive.validate();\n const record: StoredPakIndex = {\n ...validation,\n key: buildKey(archive.name, validation.checksum),\n name: archive.name,\n size: archive.size,\n persistedAt: Date.now(),\n entries: cloneEntries(validation.entries),\n };\n\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.put(record));\n db.close();\n return record;\n }\n\n async find(name: string, checksum?: number): Promise<StoredPakIndex | undefined> {\n if (!this.isSupported) {\n return undefined;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n\n const record = await runTransaction(db, this.storeName, 'readonly', (store) => {\n if (key) {\n return store.get(key);\n }\n return store.getAll();\n });\n\n db.close();\n\n if (!record) {\n return undefined;\n }\n\n if (Array.isArray(record)) {\n const normalized = normalizePath(name);\n const matches = record.filter((candidate: StoredPakIndex) => normalizePath(candidate.name) === normalized);\n if (matches.length === 0) {\n return undefined;\n }\n return matches.sort((a, b) => b.persistedAt - a.persistedAt)[0];\n }\n\n return record as StoredPakIndex;\n }\n\n async remove(name: string, checksum?: number): Promise<boolean> {\n if (!this.isSupported) {\n return false;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const key = checksum !== undefined ? buildKey(name, checksum) : undefined;\n const result = await runTransaction(db, this.storeName, 'readwrite', (store) => {\n if (key) {\n return store.delete(key);\n }\n const prefix = `${normalizePath(name)}:`;\n return store.delete(IDBKeyRange.bound(prefix, `${prefix}`, false, true));\n });\n db.close();\n return typeof result === 'number' ? result > 0 : true;\n }\n\n async clear(): Promise<void> {\n if (!this.isSupported) {\n return;\n }\n const db = await openDatabase(this.dbName, this.storeName);\n await runTransaction(db, this.storeName, 'readwrite', (store) => store.clear());\n db.close();\n }\n\n async list(): Promise<StoredPakIndex[]> {\n if (!this.isSupported) {\n return [];\n }\n const db = await openDatabase(this.dbName, this.storeName);\n const result = await runTransaction(db, this.storeName, 'readonly', (store) => store.getAll());\n db.close();\n return (result as StoredPakIndex[]).sort((a, b) => b.persistedAt - a.persistedAt);\n }\n}\n","import { normalizePath } from './pak.js';\nimport { TextureCache, type PreparedTexture } from './texture.js';\nimport { AudioRegistry, type DecodedAudio } from './audio.js';\nimport { Md2Loader, type Md2Model } from './md2.js';\nimport { Md3Loader, type Md3Model } from './md3.js';\nimport { VirtualFileSystem } from './vfs.js';\n\ntype AssetType = 'texture' | 'model' | 'sound';\n\ninterface DependencyNode {\n readonly dependencies: Set<string>;\n loaded: boolean;\n}\n\nexport class AssetDependencyError extends Error {\n constructor(readonly missing: readonly string[], message?: string) {\n super(message ?? `Missing dependencies: ${missing.join(', ')}`);\n this.name = 'AssetDependencyError';\n }\n}\n\nexport class AssetDependencyTracker {\n private readonly nodes = new Map<string, DependencyNode>();\n\n register(assetKey: string, dependencies: readonly string[] = []): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n dependencies.forEach((dependency) => node.dependencies.add(dependency));\n this.nodes.set(assetKey, node);\n dependencies.forEach((dependency) => {\n if (!this.nodes.has(dependency)) {\n this.nodes.set(dependency, { dependencies: new Set<string>(), loaded: false });\n }\n });\n }\n\n markLoaded(assetKey: string): void {\n const node = this.nodes.get(assetKey) ?? { dependencies: new Set<string>(), loaded: false };\n const missing = this.getMissingDependencies(assetKey, node);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${assetKey} is missing dependencies: ${missing.join(', ')}`);\n }\n node.loaded = true;\n this.nodes.set(assetKey, node);\n }\n\n markUnloaded(assetKey: string): void {\n const node = this.nodes.get(assetKey);\n if (node) {\n node.loaded = false;\n }\n }\n\n isLoaded(assetKey: string): boolean {\n return this.nodes.get(assetKey)?.loaded ?? false;\n }\n\n missingDependencies(assetKey: string): string[] {\n const node = this.nodes.get(assetKey);\n if (!node) {\n return [];\n }\n return this.getMissingDependencies(assetKey, node);\n }\n\n reset(): void {\n this.nodes.clear();\n }\n\n private getMissingDependencies(assetKey: string, node: DependencyNode): string[] {\n const missing: string[] = [];\n for (const dependency of node.dependencies) {\n if (!this.nodes.get(dependency)?.loaded) {\n missing.push(dependency);\n }\n }\n return missing;\n }\n}\n\nexport interface AssetManagerOptions {\n readonly textureCacheCapacity?: number;\n readonly audioCacheSize?: number;\n readonly dependencyTracker?: AssetDependencyTracker;\n}\n\nexport class AssetManager {\n readonly textures: TextureCache;\n readonly audio: AudioRegistry;\n readonly dependencyTracker: AssetDependencyTracker;\n private readonly md2: Md2Loader;\n private readonly md3: Md3Loader;\n\n constructor(private readonly vfs: VirtualFileSystem, options: AssetManagerOptions = {}) {\n this.textures = new TextureCache({ capacity: options.textureCacheCapacity ?? 128 });\n this.audio = new AudioRegistry(vfs, { cacheSize: options.audioCacheSize ?? 64 });\n this.dependencyTracker = options.dependencyTracker ?? new AssetDependencyTracker();\n this.md2 = new Md2Loader(vfs);\n this.md3 = new Md3Loader(vfs);\n }\n\n isAssetLoaded(type: AssetType, path: string): boolean {\n return this.dependencyTracker.isLoaded(this.makeKey(type, path));\n }\n\n registerTexture(path: string, texture: PreparedTexture): void {\n this.textures.set(path, texture);\n const key = this.makeKey('texture', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n }\n\n async loadSound(path: string): Promise<DecodedAudio> {\n const audio = await this.audio.load(path);\n const key = this.makeKey('sound', path);\n this.dependencyTracker.register(key);\n this.dependencyTracker.markLoaded(key);\n return audio;\n }\n\n async loadMd2Model(path: string, textureDependencies: readonly string[] = []): Promise<Md2Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md2.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n async loadMd3Model(path: string, textureDependencies: readonly string[] = []): Promise<Md3Model> {\n const modelKey = this.makeKey('model', path);\n const dependencyKeys = textureDependencies.map((dep) => this.makeKey('texture', dep));\n this.dependencyTracker.register(modelKey, dependencyKeys);\n const missing = this.dependencyTracker.missingDependencies(modelKey);\n if (missing.length > 0) {\n throw new AssetDependencyError(missing, `Asset ${modelKey} is missing dependencies: ${missing.join(', ')}`);\n }\n const model = await this.md3.load(path);\n this.dependencyTracker.markLoaded(modelKey);\n return model;\n }\n\n resetForLevelChange(): void {\n this.textures.clear();\n this.audio.clearAll();\n this.dependencyTracker.reset();\n }\n\n private makeKey(type: AssetType, path: string): string {\n return `${type}:${normalizePath(path)}`;\n }\n}\n","export const MAX_SOUND_CHANNELS = 32;\n\n// Sound channel identifiers and flags from the rerelease game headers.\nexport enum SoundChannel {\n Auto = 0,\n Weapon = 1,\n Voice = 2,\n Item = 3,\n Body = 4,\n Aux = 5,\n Footstep = 6,\n Aux3 = 7,\n\n NoPhsAdd = 1 << 3,\n Reliable = 1 << 4,\n ForcePos = 1 << 5,\n}\n\nexport const ATTN_LOOP_NONE = -1;\nexport const ATTN_NONE = 0;\nexport const ATTN_NORM = 1;\nexport const ATTN_IDLE = 2;\nexport const ATTN_STATIC = 3;\n\nexport const SOUND_FULLVOLUME = 80;\nexport const SOUND_LOOP_ATTENUATE = 0.003;\n\nexport function attenuationToDistanceMultiplier(attenuation: number): number {\n return attenuation === ATTN_STATIC ? attenuation * 0.001 : attenuation * 0.0005;\n}\n\nexport function calculateMaxAudibleDistance(attenuation: number): number {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n return distMult <= 0 ? Number.POSITIVE_INFINITY : SOUND_FULLVOLUME + 1 / distMult;\n}\n","export interface AudioParamLike {\n value: number;\n}\n\nexport interface AudioNodeLike {\n connect(destination: AudioNodeLike): void;\n}\n\nexport interface BiquadFilterNodeLike extends AudioNodeLike {\n frequency: AudioParamLike;\n Q: AudioParamLike;\n type: string;\n}\n\nexport interface GainNodeLike extends AudioNodeLike {\n gain: AudioParamLike;\n}\n\nexport interface DynamicsCompressorNodeLike extends AudioNodeLike {}\n\nexport interface AudioBufferLike {\n readonly duration: number;\n}\n\nexport interface AudioBufferSourceNodeLike extends AudioNodeLike {\n buffer: AudioBufferLike | null;\n loop: boolean;\n onended: (() => void) | null;\n start(when?: number, offset?: number, duration?: number): void;\n stop(when?: number): void;\n}\n\nexport interface PannerNodeLike extends AudioNodeLike {\n positionX: AudioParamLike;\n positionY: AudioParamLike;\n positionZ: AudioParamLike;\n refDistance?: number;\n maxDistance?: number;\n rolloffFactor?: number;\n distanceModel?: string;\n}\n\nexport interface AudioDestinationNodeLike extends AudioNodeLike {}\n\nexport interface AudioContextLike {\n readonly destination: AudioDestinationNodeLike;\n readonly currentTime: number;\n state: 'suspended' | 'running' | 'closed';\n resume(): Promise<void>;\n suspend(): Promise<void>;\n createGain(): GainNodeLike;\n createDynamicsCompressor(): DynamicsCompressorNodeLike;\n createBufferSource(): AudioBufferSourceNodeLike;\n createPanner?(): PannerNodeLike;\n createBiquadFilter?(): BiquadFilterNodeLike;\n decodeAudioData?(data: ArrayBuffer): Promise<AudioBufferLike>;\n}\n\nexport type AudioContextFactory = () => AudioContextLike;\n\nexport interface AudioGraph {\n context: AudioContextLike;\n master: GainNodeLike;\n compressor: DynamicsCompressorNodeLike;\n filter?: BiquadFilterNodeLike;\n}\n\nexport class AudioContextController {\n private context?: AudioContextLike;\n\n constructor(private readonly factory: AudioContextFactory) {}\n\n getContext(): AudioContextLike {\n if (!this.context) {\n this.context = this.factory();\n }\n return this.context;\n }\n\n async resume(): Promise<void> {\n const ctx = this.getContext();\n if (ctx.state === 'suspended') {\n await ctx.resume();\n }\n }\n\n getState(): AudioContextLike['state'] {\n return this.context?.state ?? 'suspended';\n }\n}\n\nexport function createAudioGraph(controller: AudioContextController): AudioGraph {\n const context = controller.getContext();\n const master = context.createGain();\n master.gain.value = 1;\n const compressor = context.createDynamicsCompressor();\n const filter = context.createBiquadFilter?.();\n if (filter) {\n filter.type = 'lowpass';\n filter.frequency.value = 20000;\n filter.Q.value = 0.707;\n master.connect(filter);\n filter.connect(compressor);\n } else {\n master.connect(compressor);\n }\n compressor.connect(context.destination);\n return { context, master, compressor, filter };\n}\n","import { ConfigStringRegistry } from '../configstrings.js';\nimport type { AudioBufferLike } from './context.js';\n\nexport class SoundRegistry {\n private readonly buffers = new Map<number, AudioBufferLike>();\n\n constructor(private readonly configStrings = new ConfigStringRegistry()) {}\n\n registerName(name: string): number {\n return this.configStrings.soundIndex(name);\n }\n\n register(name: string, buffer: AudioBufferLike): number {\n const index = this.registerName(name);\n this.buffers.set(index, buffer);\n return index;\n }\n\n find(name: string): number | undefined {\n return this.configStrings.findSoundIndex(name);\n }\n\n get(index: number): AudioBufferLike | undefined {\n return this.buffers.get(index);\n }\n\n has(index: number): boolean {\n return this.buffers.has(index);\n }\n}\n","import { normalizePath } from '../assets/pak.js';\nimport type { VirtualFileSystem } from '../assets/vfs.js';\nimport type { AudioBufferLike, AudioContextLike } from './context.js';\nimport { AudioContextController } from './context.js';\nimport { SoundRegistry } from './registry.js';\n\nexport interface SoundPrecacheOptions {\n vfs: Pick<VirtualFileSystem, 'readFile' | 'stat'>;\n registry: SoundRegistry;\n context: AudioContextController;\n decodeAudio?: (context: AudioContextLike, data: ArrayBuffer) => Promise<AudioBufferLike>;\n soundRoot?: string;\n}\n\nexport interface SoundPrecacheReport {\n loaded: string[];\n skipped: string[];\n missing: string[];\n errors: Record<string, Error>;\n}\n\nexport class SoundPrecache {\n private readonly vfs: SoundPrecacheOptions['vfs'];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly decodeAudio: NonNullable<SoundPrecacheOptions['decodeAudio']>;\n private readonly soundRoot: string;\n\n constructor(options: SoundPrecacheOptions) {\n this.vfs = options.vfs;\n this.registry = options.registry;\n this.contextController = options.context;\n this.soundRoot = options.soundRoot ?? 'sound/';\n this.decodeAudio =\n options.decodeAudio ??\n ((context: AudioContextLike, data: ArrayBuffer) => {\n if (!context.decodeAudioData) {\n throw new Error('decodeAudioData is not available on the provided audio context');\n }\n return context.decodeAudioData(data);\n });\n }\n\n async precache(paths: string[]): Promise<SoundPrecacheReport> {\n const unique = [...new Set(paths.map((p) => this.normalize(p)))];\n const report: SoundPrecacheReport = { loaded: [], skipped: [], missing: [], errors: {} };\n const context = this.contextController.getContext();\n\n for (const path of unique) {\n try {\n const existingIndex = this.registry.find(path);\n if (existingIndex !== undefined && this.registry.has(existingIndex)) {\n report.skipped.push(path);\n continue;\n }\n\n const stat = this.vfs.stat(path);\n if (!stat) {\n report.missing.push(path);\n continue;\n }\n\n const bytes = await this.vfs.readFile(path);\n const copy = bytes.slice().buffer;\n const buffer = await this.decodeAudio(context, copy);\n this.registry.register(path, buffer);\n report.loaded.push(path);\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n report.errors[path] = err;\n }\n }\n\n return report;\n }\n\n private normalize(path: string): string {\n const normalized = normalizePath(path.replace(/^\\//, ''));\n if (normalized.startsWith(this.soundRoot)) {\n return normalized;\n }\n return normalizePath(`${this.soundRoot}${normalized}`);\n }\n}\n","import { MAX_SOUND_CHANNELS, SoundChannel } from './constants.js';\n\nconst CHANNEL_MASK = 0x07;\n\nexport const baseChannel = (entchannel: number): number => entchannel & CHANNEL_MASK;\n\nexport interface ChannelState {\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n isPlayer: boolean;\n active: boolean;\n}\n\nexport interface ChannelPickContext {\n readonly nowMs: number;\n readonly playerEntity?: number;\n}\n\nexport function createInitialChannels(playerEntity?: number): ChannelState[] {\n return Array.from({ length: MAX_SOUND_CHANNELS }, () => ({\n entnum: 0,\n entchannel: SoundChannel.Auto,\n endTimeMs: 0,\n isPlayer: false,\n active: false,\n } satisfies ChannelState)).map((channel) => ({ ...channel, isPlayer: channel.entnum === playerEntity }));\n}\n\nexport function pickChannel(\n channels: ChannelState[],\n entnum: number,\n entchannel: number,\n context: ChannelPickContext,\n): number | undefined {\n if (entchannel < 0) {\n throw new Error('pickChannel: entchannel must be non-negative');\n }\n\n const normalizedEntchannel = baseChannel(entchannel);\n let firstToDie = -1;\n let lifeLeft = Number.POSITIVE_INFINITY;\n\n for (let i = 0; i < channels.length; i += 1) {\n const channel = channels[i];\n const channelBase = baseChannel(channel.entchannel);\n\n if (\n normalizedEntchannel !== SoundChannel.Auto &&\n channel.entnum === entnum &&\n channelBase === normalizedEntchannel\n ) {\n firstToDie = i;\n break;\n }\n\n if (channel.active && channel.entnum === context.playerEntity && entnum !== context.playerEntity) {\n continue;\n }\n\n const remainingLife = channel.endTimeMs - context.nowMs;\n if (firstToDie === -1 || remainingLife < lifeLeft) {\n lifeLeft = remainingLife;\n firstToDie = i;\n }\n }\n\n return firstToDie === -1 ? undefined : firstToDie;\n}\n","import { Vec3, dotVec3, lengthVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { SOUND_FULLVOLUME, attenuationToDistanceMultiplier } from './constants.js';\n\nexport interface ListenerState {\n origin: Vec3;\n right: Vec3;\n mono?: boolean;\n playerEntity?: number;\n}\n\nexport interface SpatializationResult {\n left: number;\n right: number;\n distanceComponent: number;\n}\n\nexport function spatializeOrigin(\n origin: Vec3,\n listener: ListenerState,\n masterVolume: number,\n attenuation: number,\n isListenerSound: boolean,\n): SpatializationResult {\n if (isListenerSound) {\n return { left: masterVolume, right: masterVolume, distanceComponent: 0 };\n }\n\n const sourceVec = subtractVec3(origin, listener.origin);\n const distance = lengthVec3(sourceVec);\n const normalized = normalizeVec3(sourceVec);\n let dist = distance - SOUND_FULLVOLUME;\n if (dist < 0) dist = 0;\n dist *= attenuationToDistanceMultiplier(attenuation);\n\n const dot = dotVec3(listener.right, normalized);\n const mono = listener.mono ?? false;\n const rscale = mono || attenuation === 0 ? 1 : 0.5 * (1 + dot);\n const lscale = mono || attenuation === 0 ? 1 : 0.5 * (1 - dot);\n\n const right = Math.max(0, Math.floor(masterVolume * (1 - dist) * rscale));\n const left = Math.max(0, Math.floor(masterVolume * (1 - dist) * lscale));\n\n return { left, right, distanceComponent: dist };\n}\n","import { ZERO_VEC3, type Vec3 } from '@quake2ts/shared';\nimport {\n ATTN_NONE,\n SOUND_FULLVOLUME,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n SoundChannel,\n} from './constants.js';\nimport {\n AudioContextController,\n createAudioGraph,\n type AudioContextLike,\n type AudioBufferSourceNodeLike,\n type AudioGraph,\n type BiquadFilterNodeLike,\n type GainNodeLike,\n type PannerNodeLike,\n} from './context.js';\nimport { SoundRegistry } from './registry.js';\nimport { baseChannel, createInitialChannels, pickChannel, type ChannelState } from './channels.js';\nimport { spatializeOrigin, type ListenerState } from './spatialization.js';\n\nexport interface SoundRequest {\n entity: number;\n channel: number;\n soundIndex: number;\n volume: number;\n attenuation: number;\n origin?: Vec3;\n timeOffsetMs?: number;\n looping?: boolean;\n}\n\nexport interface AudioSystemOptions {\n context: AudioContextController;\n registry: SoundRegistry;\n playerEntity?: number;\n listener?: ListenerState;\n sfxVolume?: number;\n masterVolume?: number;\n resolveOcclusion?: OcclusionResolver;\n}\n\ninterface ActiveSound {\n channelIndex: number;\n entnum: number;\n entchannel: number;\n endTimeMs: number;\n source: AudioBufferSourceNodeLike;\n panner: PannerNodeLike;\n gain: GainNodeLike;\n baseGain: number;\n origin: Vec3;\n attenuation: number;\n occlusion?: OcclusionState;\n}\n\ninterface OcclusionState {\n scale: number;\n lowpassHz?: number;\n filter?: BiquadFilterNodeLike;\n}\n\nexport interface OcclusionResult {\n gainScale?: number;\n lowpassHz?: number;\n}\n\nexport type OcclusionResolver = (\n listener: ListenerState,\n source: Vec3,\n attenuation: number,\n) => OcclusionResult | undefined;\n\nexport interface AudioDiagnostics {\n activeChannels: number;\n masterVolume: number;\n sfxVolume: number;\n channels: ChannelState[];\n activeSounds: Array<{\n entnum: number;\n entchannel: number;\n channelIndex: number;\n origin: Vec3;\n gain: number;\n baseGain: number;\n attenuation: number;\n maxDistance?: number;\n distanceModel?: string;\n occlusion?: { scale: number; lowpassHz?: number };\n }>;\n}\n\nexport class AudioSystem {\n private readonly channels: ChannelState[];\n private readonly registry: SoundRegistry;\n private readonly contextController: AudioContextController;\n private readonly graph: AudioGraph;\n private readonly playerEntity?: number;\n private readonly activeSources = new Map<number, ActiveSound>();\n private readonly resolveOcclusion?: OcclusionResolver;\n private listener: ListenerState;\n private sfxVolume: number;\n private masterVolume: number;\n\n constructor(options: AudioSystemOptions) {\n this.contextController = options.context;\n this.registry = options.registry;\n this.playerEntity = options.playerEntity;\n this.channels = createInitialChannels(options.playerEntity);\n this.listener = options.listener ?? { origin: ZERO_VEC3, right: { x: 1, y: 0, z: 0 } };\n this.sfxVolume = options.sfxVolume ?? 1;\n this.masterVolume = options.masterVolume ?? 1;\n this.resolveOcclusion = options.resolveOcclusion;\n this.graph = createAudioGraph(this.contextController);\n this.graph.master.gain.value = this.masterVolume;\n }\n\n setListener(listener: ListenerState): void {\n this.listener = listener;\n }\n\n setMasterVolume(volume: number): void {\n this.masterVolume = volume;\n this.graph.master.gain.value = volume;\n }\n\n setSfxVolume(volume: number): void {\n this.sfxVolume = volume;\n }\n\n async ensureRunning(): Promise<void> {\n await this.contextController.resume();\n }\n\n play(request: SoundRequest): ActiveSound | undefined {\n const buffer = this.registry.get(request.soundIndex);\n if (!buffer) return undefined;\n\n const ctx = this.graph.context;\n const nowMs = ctx.currentTime * 1000;\n const channelIndex = pickChannel(this.channels, request.entity, request.channel, {\n nowMs,\n playerEntity: this.playerEntity,\n });\n\n if (channelIndex === undefined) return undefined;\n\n const existing = this.activeSources.get(channelIndex);\n if (existing) {\n existing.source.onended = null;\n existing.source.stop();\n this.activeSources.delete(channelIndex);\n }\n\n const source = ctx.createBufferSource();\n source.buffer = buffer;\n source.loop = request.looping ?? false;\n\n const origin = request.origin ?? this.listener.origin;\n const gain = ctx.createGain();\n const panner = this.createPanner(ctx, request.attenuation);\n const occlusion = this.resolveOcclusion?.(this.listener, origin, request.attenuation);\n const occlusionScale = clamp01(occlusion?.gainScale ?? 1);\n const occlusionFilter = this.resolveOcclusion\n ? this.createOcclusionFilter(ctx, occlusion?.lowpassHz ?? 20000)\n : undefined;\n this.applyOriginToPanner(panner, origin);\n const isListenerSound = request.entity === this.playerEntity;\n const spatial = spatializeOrigin(origin, this.listener, request.volume, request.attenuation, isListenerSound);\n\n const attenuationScale = request.volume === 0 ? 0 : Math.max(spatial.left, spatial.right) / Math.max(1, request.volume);\n const gainValue = attenuationScale * (request.volume / 255) * this.masterVolume * this.sfxVolume;\n gain.gain.value = gainValue * occlusionScale;\n\n const startTimeSec = ctx.currentTime + (request.timeOffsetMs ?? 0) / 1000;\n const endTimeMs = (request.looping ? Number.POSITIVE_INFINITY : buffer.duration * 1000) + startTimeSec * 1000;\n\n source.connect(panner);\n if (occlusionFilter) {\n panner.connect(occlusionFilter);\n occlusionFilter.connect(gain);\n } else {\n panner.connect(gain);\n }\n gain.connect(this.graph.master);\n\n source.start(startTimeSec);\n source.onended = () => {\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n };\n\n const active: ActiveSound = {\n channelIndex,\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n source,\n panner,\n gain,\n baseGain: gainValue,\n origin,\n attenuation: request.attenuation,\n occlusion: occlusionFilter\n ? { scale: occlusionScale, lowpassHz: occlusion?.lowpassHz, filter: occlusionFilter }\n : occlusion\n ? { scale: occlusionScale, lowpassHz: occlusion.lowpassHz }\n : undefined,\n };\n\n this.channels[channelIndex] = {\n entnum: request.entity,\n entchannel: baseChannel(request.channel),\n endTimeMs,\n isPlayer: request.entity === this.playerEntity,\n active: true,\n };\n\n this.activeSources.set(channelIndex, active);\n return active;\n }\n\n stop(channelIndex: number): void {\n const active = this.activeSources.get(channelIndex);\n if (!active) return;\n active.source.stop();\n this.channels[channelIndex].active = false;\n this.activeSources.delete(channelIndex);\n }\n\n stopEntitySounds(entnum: number): void {\n for (const [index, active] of [...this.activeSources.entries()]) {\n if (active.entnum !== entnum) continue;\n active.source.stop();\n this.channels[index].active = false;\n this.activeSources.delete(index);\n }\n }\n\n updateEntityPosition(entnum: number, origin: Vec3): void {\n for (const active of this.activeSources.values()) {\n if (active.entnum !== entnum) continue;\n this.applyOriginToPanner(active.panner, origin);\n active.origin = origin;\n if (this.resolveOcclusion) {\n const occlusion = this.resolveOcclusion(this.listener, origin, active.attenuation);\n this.applyOcclusion(active, occlusion);\n }\n }\n }\n\n positionedSound(origin: Vec3, soundIndex: number, volume: number, attenuation: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation,\n origin,\n });\n }\n\n ambientSound(origin: Vec3, soundIndex: number, volume: number): ActiveSound | undefined {\n return this.play({\n entity: 0,\n channel: SoundChannel.Auto,\n soundIndex,\n volume,\n attenuation: ATTN_NONE,\n origin,\n looping: true,\n });\n }\n\n getChannelState(index: number): ChannelState | undefined {\n return this.channels[index];\n }\n\n getDiagnostics(): AudioDiagnostics {\n return {\n activeChannels: this.activeSources.size,\n masterVolume: this.masterVolume,\n sfxVolume: this.sfxVolume,\n channels: [...this.channels],\n activeSounds: [...this.activeSources.values()].map((sound) => ({\n entnum: sound.entnum,\n entchannel: sound.entchannel,\n channelIndex: sound.channelIndex,\n origin: sound.origin,\n gain: sound.gain.gain.value,\n baseGain: sound.baseGain,\n attenuation: sound.attenuation,\n maxDistance: sound.panner.maxDistance,\n distanceModel: sound.panner.distanceModel,\n occlusion: sound.occlusion ? { scale: sound.occlusion.scale, lowpassHz: sound.occlusion.lowpassHz } : undefined,\n })),\n };\n }\n\n setUnderwater(enabled: boolean, cutoffHz = 400): void {\n const filter = this.graph.filter;\n if (!filter) return;\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = enabled ? cutoffHz : 20000;\n }\n\n private createPanner(context: AudioContextLike, attenuation: number): PannerNodeLike {\n const panner = context.createPanner\n ? context.createPanner()\n : Object.assign(context.createGain(), {\n positionX: { value: this.listener.origin.x },\n positionY: { value: this.listener.origin.y },\n positionZ: { value: this.listener.origin.z },\n } satisfies Partial<PannerNodeLike>);\n\n return this.configurePanner(panner, attenuation);\n }\n\n private configurePanner(panner: PannerNodeLike, attenuation: number): PannerNodeLike {\n const distMult = attenuationToDistanceMultiplier(attenuation);\n panner.refDistance = SOUND_FULLVOLUME;\n panner.maxDistance = calculateMaxAudibleDistance(attenuation);\n panner.rolloffFactor = distMult;\n panner.distanceModel = attenuation === 0 ? 'linear' : 'inverse';\n panner.positionX.value = this.listener.origin.x;\n panner.positionY.value = this.listener.origin.y;\n panner.positionZ.value = this.listener.origin.z;\n return panner;\n }\n\n private applyOriginToPanner(panner: PannerNodeLike, origin: Vec3): void {\n panner.positionX.value = origin.x;\n panner.positionY.value = origin.y;\n panner.positionZ.value = origin.z;\n }\n\n private createOcclusionFilter(context: AudioContextLike, cutoffHz: number): BiquadFilterNodeLike | undefined {\n if (!context.createBiquadFilter) return undefined;\n const filter = context.createBiquadFilter();\n filter.type = 'lowpass';\n filter.Q.value = 0.707;\n filter.frequency.value = clamp(cutoffHz, 10, 20000);\n return filter;\n }\n\n private applyOcclusion(active: ActiveSound, occlusion?: OcclusionResult): void {\n const scale = clamp01(occlusion?.gainScale ?? 1);\n active.gain.gain.value = active.baseGain * scale;\n if (active.occlusion?.filter) {\n const cutoff = occlusion?.lowpassHz ?? 20000;\n active.occlusion.filter.frequency.value = clamp(cutoff, 10, 20000);\n }\n if (active.occlusion) {\n active.occlusion.scale = scale;\n active.occlusion.lowpassHz = occlusion?.lowpassHz;\n } else if (occlusion) {\n active.occlusion = { scale, lowpassHz: occlusion.lowpassHz };\n }\n }\n}\n\nconst clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));\nconst clamp01 = (value: number): number => clamp(value, 0, 1);\n\n","export interface AudioElementLike {\n src: string;\n loop: boolean;\n volume: number;\n currentTime: number;\n paused: boolean;\n ended: boolean;\n play(): Promise<void>;\n pause(): void;\n load(): void;\n}\n\nexport type AudioElementFactory = () => AudioElementLike;\nexport type MusicSourceResolver = (path: string) => Promise<string>;\n\nexport interface MusicSystemOptions {\n createElement: AudioElementFactory;\n resolveSource?: MusicSourceResolver;\n volume?: number;\n}\n\nexport interface MusicState {\n readonly track?: string;\n readonly paused: boolean;\n readonly playing: boolean;\n readonly volume: number;\n}\n\nexport class MusicSystem {\n private readonly createElement: AudioElementFactory;\n private readonly resolveSource: MusicSourceResolver;\n private element?: AudioElementLike;\n private track?: string;\n private volume: number;\n\n constructor(options: MusicSystemOptions) {\n this.createElement = options.createElement;\n this.resolveSource = options.resolveSource ?? (async (path) => path);\n this.volume = options.volume ?? 1;\n }\n\n async play(track: string, { loop = true, restart = false }: { loop?: boolean; restart?: boolean } = {}): Promise<void> {\n if (this.track === track && this.element) {\n this.element.loop = loop;\n this.element.volume = this.volume;\n if (restart) {\n this.element.currentTime = 0;\n }\n if (this.element.paused || restart) {\n await this.element.play();\n }\n return;\n }\n\n const src = await this.resolveSource(track);\n const element = this.createElement();\n element.src = src;\n element.loop = loop;\n element.volume = this.volume;\n element.currentTime = 0;\n element.load();\n await element.play();\n\n this.element = element;\n this.track = track;\n }\n\n pause(): void {\n if (!this.element || this.element.paused) return;\n this.element.pause();\n }\n\n async resume(): Promise<void> {\n if (!this.element || !this.element.paused) return;\n await this.element.play();\n }\n\n stop(): void {\n if (!this.element) return;\n this.element.pause();\n this.element.currentTime = 0;\n this.element = undefined;\n this.track = undefined;\n }\n\n setVolume(volume: number): void {\n this.volume = volume;\n if (this.element) {\n this.element.volume = volume;\n }\n }\n\n getState(): MusicState {\n const playing = Boolean(this.element && !this.element.paused && !this.element.ended);\n const paused = Boolean(this.element?.paused);\n return { track: this.track, paused, playing, volume: this.volume };\n }\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport { MusicSystem } from './music.js';\nimport { SoundRegistry } from './registry.js';\nimport { AudioSystem, type SoundRequest } from './system.js';\n\nexport interface AudioApiOptions {\n registry: SoundRegistry;\n system: AudioSystem;\n music?: MusicSystem;\n}\n\nexport class AudioApi {\n private readonly registry: SoundRegistry;\n private readonly system: AudioSystem;\n private readonly music?: MusicSystem;\n\n constructor(options: AudioApiOptions) {\n this.registry = options.registry;\n this.system = options.system;\n this.music = options.music;\n }\n\n soundindex(name: string): number {\n return this.registry.registerName(name);\n }\n\n sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number, timeofs: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n timeOffsetMs: timeofs,\n });\n }\n\n positioned_sound(origin: Vec3, soundindex: number, volume: number, attenuation: number): void {\n this.system.positionedSound(origin, soundindex, volume, attenuation);\n }\n\n loop_sound(entity: number, channel: number, soundindex: number, volume: number, attenuation: number): void {\n this.system.play({\n entity,\n channel,\n soundIndex: soundindex,\n volume,\n attenuation,\n looping: true,\n });\n }\n\n stop_entity_sounds(entnum: number): void {\n this.system.stopEntitySounds(entnum);\n }\n\n set_listener(listener: Parameters<AudioSystem['setListener']>[0]): void {\n this.system.setListener(listener);\n }\n\n play_music(track: string, loop = true): Promise<void> {\n if (!this.music) {\n return Promise.resolve();\n }\n return this.music.play(track, { loop });\n }\n\n pause_music(): void {\n this.music?.pause();\n }\n\n resume_music(): Promise<void> {\n return this.music?.resume() ?? Promise.resolve();\n }\n\n stop_music(): void {\n this.music?.stop();\n }\n\n set_music_volume(volume: number): void {\n this.music?.setVolume(volume);\n }\n\n play_ambient(origin: Vec3, soundindex: number, volume: number): void {\n this.system.ambientSound(origin, soundindex, volume);\n }\n\n play_channel(request: Omit<SoundRequest, 'looping'>): void {\n this.system.play({ ...request });\n }\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 TextureCubeMap {\n readonly gl: WebGL2RenderingContext;\n readonly texture: WebGLTexture;\n readonly target: GLenum;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.target = gl.TEXTURE_CUBE_MAP;\n const texture = gl.createTexture();\n if (!texture) {\n throw new Error('Failed to allocate cubemap 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 uploadFace(\n faceTarget: GLenum,\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(faceTarget, 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 { type Vec3 } from '@quake2ts/shared';\n\nexport interface FrustumPlane {\n readonly normal: Vec3;\n readonly distance: number;\n}\n\nfunction normalizePlane(plane: FrustumPlane): FrustumPlane {\n const { normal, distance } = plane;\n const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z);\n if (length === 0) {\n return plane;\n }\n const inv = 1 / length;\n return {\n normal: { x: normal.x * inv, y: normal.y * inv, z: normal.z * inv },\n distance: distance * inv,\n };\n}\n\nexport function extractFrustumPlanes(matrix: readonly number[]): readonly FrustumPlane[] {\n if (matrix.length !== 16) {\n throw new Error('View-projection matrix must contain 16 elements');\n }\n\n const m00 = matrix[0];\n const m01 = matrix[4];\n const m02 = matrix[8];\n const m03 = matrix[12];\n const m10 = matrix[1];\n const m11 = matrix[5];\n const m12 = matrix[9];\n const m13 = matrix[13];\n const m20 = matrix[2];\n const m21 = matrix[6];\n const m22 = matrix[10];\n const m23 = matrix[14];\n const m30 = matrix[3];\n const m31 = matrix[7];\n const m32 = matrix[11];\n const m33 = matrix[15];\n\n const planes: FrustumPlane[] = [\n // Left\n normalizePlane({ normal: { x: m30 + m00, y: m31 + m01, z: m32 + m02 }, distance: m33 + m03 }),\n // Right\n normalizePlane({ normal: { x: m30 - m00, y: m31 - m01, z: m32 - m02 }, distance: m33 - m03 }),\n // Bottom\n normalizePlane({ normal: { x: m30 + m10, y: m31 + m11, z: m32 + m12 }, distance: m33 + m13 }),\n // Top\n normalizePlane({ normal: { x: m30 - m10, y: m31 - m11, z: m32 - m12 }, distance: m33 - m13 }),\n // Near\n normalizePlane({ normal: { x: m30 + m20, y: m31 + m21, z: m32 + m22 }, distance: m33 + m23 }),\n // Far\n normalizePlane({ normal: { x: m30 - m20, y: m31 - m21, z: m32 - m22 }, distance: m33 - m23 }),\n ];\n\n return planes;\n}\n\nfunction planeDistance(plane: FrustumPlane, point: Vec3): number {\n return plane.normal.x * point.x + plane.normal.y * point.y + plane.normal.z * point.z + plane.distance;\n}\n\nexport function boxIntersectsFrustum(mins: Vec3, maxs: Vec3, planes: readonly FrustumPlane[]): boolean {\n for (const plane of planes) {\n // Choose the corner most likely to be outside based on the plane normal.\n const x = plane.normal.x >= 0 ? maxs.x : mins.x;\n const y = plane.normal.y >= 0 ? maxs.y : mins.y;\n const z = plane.normal.z >= 0 ? maxs.z : mins.z;\n if (planeDistance(plane, { x, y, z }) < 0) {\n return false;\n }\n }\n return true;\n}\n","import { type Vec3 } from '@quake2ts/shared';\nimport type {\n BspLeaf,\n BspMap,\n BspNode,\n BspPlane,\n BspVisibility,\n} from '../assets/bsp.js';\nimport { boxIntersectsFrustum, type FrustumPlane } from './culling.js';\n\nexport interface VisibleFace {\n readonly faceIndex: number;\n readonly leafIndex: number;\n readonly sortKey: number;\n}\n\nfunction childIsLeaf(index: number): boolean {\n return index < 0;\n}\n\nfunction childLeafIndex(index: number): number {\n return -index - 1;\n}\n\nfunction distanceToPlane(plane: BspPlane, point: Vec3): number {\n return plane.normal[0] * point.x + plane.normal[1] * point.y + plane.normal[2] * point.z - plane.dist;\n}\n\nfunction isClusterVisible(visibility: BspVisibility | undefined, fromCluster: number, testCluster: number): boolean {\n if (!visibility) {\n return true;\n }\n if (fromCluster < 0 || testCluster < 0) {\n return true;\n }\n const rowBytes = Math.ceil(visibility.numClusters / 8);\n const row = visibility.clusters[fromCluster].pvs;\n const byteIndex = Math.floor(testCluster / 8);\n const bit = 1 << (testCluster % 8);\n if (byteIndex < 0 || byteIndex >= rowBytes) {\n return false;\n }\n return (row[byteIndex] & bit) !== 0;\n}\n\nfunction leafIntersectsFrustum(leaf: BspLeaf, planes: readonly FrustumPlane[]): boolean {\n const mins = { x: leaf.mins[0], y: leaf.mins[1], z: leaf.mins[2] };\n const maxs = { x: leaf.maxs[0], y: leaf.maxs[1], z: leaf.maxs[2] };\n return boxIntersectsFrustum(mins, maxs, planes);\n}\n\nexport function findLeafForPoint(map: BspMap, point: Vec3): number {\n let nodeIndex = 0;\n while (nodeIndex >= 0) {\n const node: BspNode = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, point);\n const side = dist >= 0 ? 0 : 1;\n const child = node.children[side];\n if (childIsLeaf(child)) {\n return childLeafIndex(child);\n }\n nodeIndex = child;\n }\n return -1;\n}\n\nfunction collectFacesFromLeaf(map: BspMap, leafIndex: number): number[] {\n const leaf = map.leafs[leafIndex];\n const faces: number[] = [];\n for (let i = 0; i < leaf.numLeafFaces; i += 1) {\n faces.push(map.leafLists.leafFaces[leafIndex][i]);\n }\n return faces;\n}\n\nfunction traverse(\n map: BspMap,\n nodeIndex: number,\n camera: Vec3,\n frustum: readonly FrustumPlane[],\n viewCluster: number,\n visibleFaces: VisibleFace[],\n visitedFaces: Set<number>\n): void {\n if (childIsLeaf(nodeIndex)) {\n const leafIndex = childLeafIndex(nodeIndex);\n const leaf = map.leafs[leafIndex];\n if (!isClusterVisible(map.visibility, viewCluster, leaf.cluster)) {\n return;\n }\n if (!leafIntersectsFrustum(leaf, frustum)) {\n return;\n }\n const center = {\n x: (leaf.mins[0] + leaf.maxs[0]) * 0.5,\n y: (leaf.mins[1] + leaf.maxs[1]) * 0.5,\n z: (leaf.mins[2] + leaf.maxs[2]) * 0.5,\n };\n const dx = center.x - camera.x;\n const dy = center.y - camera.y;\n const dz = center.z - camera.z;\n const leafSortKey = -(dx * dx + dy * dy + dz * dz);\n for (const faceIndex of collectFacesFromLeaf(map, leafIndex)) {\n if (visitedFaces.has(faceIndex)) {\n continue;\n }\n visitedFaces.add(faceIndex);\n visibleFaces.push({ faceIndex, leafIndex, sortKey: leafSortKey });\n }\n return;\n }\n\n const node = map.nodes[nodeIndex];\n const plane = map.planes[node.planeIndex];\n const dist = distanceToPlane(plane, camera);\n const nearChild = dist >= 0 ? node.children[0] : node.children[1];\n const farChild = dist >= 0 ? node.children[1] : node.children[0];\n\n if (boxIntersectsFrustum(\n { x: node.mins[0], y: node.mins[1], z: node.mins[2] },\n { x: node.maxs[0], y: node.maxs[1], z: node.maxs[2] },\n frustum,\n )) {\n traverse(map, nearChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n traverse(map, farChild, camera, frustum, viewCluster, visibleFaces, visitedFaces);\n }\n}\n\nexport function gatherVisibleFaces(\n map: BspMap,\n cameraPosition: Vec3,\n frustum: readonly FrustumPlane[],\n): VisibleFace[] {\n const viewLeaf = findLeafForPoint(map, cameraPosition);\n const viewCluster = viewLeaf >= 0 ? map.leafs[viewLeaf].cluster : -1;\n const visibleFaces: VisibleFace[] = [];\n const visitedFaces = new Set<number>();\n traverse(map, 0, cameraPosition, frustum, viewCluster, visibleFaces, visitedFaces);\n return visibleFaces;\n}\n","import {\n SURF_FLOWING,\n SURF_NONE,\n SURF_SKY,\n SURF_TRANS33,\n SURF_TRANS66,\n SURF_WARP,\n type SurfaceFlag,\n} from '@quake2ts/shared';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface SurfaceRenderState {\n readonly alpha: number;\n readonly blend: boolean;\n readonly depthWrite: boolean;\n readonly warp: boolean;\n readonly flowOffset: readonly [number, number];\n readonly sky: boolean;\n}\n\nexport interface BspSurfaceBindOptions {\n readonly modelViewProjection: Float32List;\n readonly styleIndices?: readonly number[];\n readonly styleValues?: ReadonlyArray<number>;\n readonly diffuseSampler?: number;\n readonly lightmapSampler?: number;\n readonly surfaceFlags?: SurfaceFlag;\n readonly timeSeconds?: number;\n}\n\nexport const BSP_SURFACE_VERTEX_SOURCE = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec2 a_lightmapCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec2 u_texScroll;\nuniform vec2 u_lightmapScroll;\n\nout vec2 v_texCoord;\nout vec2 v_lightmapCoord;\n\nvec2 applyScroll(vec2 uv, vec2 scroll) {\n return uv + scroll;\n}\n\nvoid main() {\n v_texCoord = applyScroll(a_texCoord, u_texScroll);\n v_lightmapCoord = applyScroll(a_lightmapCoord, u_lightmapScroll);\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const BSP_SURFACE_FRAGMENT_SOURCE = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin vec2 v_lightmapCoord;\n\nuniform sampler2D u_diffuseMap;\nuniform sampler2D u_lightmapAtlas;\nuniform vec4 u_lightStyleFactors;\nuniform float u_alpha;\nuniform bool u_applyLightmap;\nuniform bool u_warp;\nuniform float u_time;\n\nout vec4 o_color;\n\nvec2 warpCoords(vec2 uv) {\n // Quake II warp applies a subtle sinusoidal offset; we mirror the rerelease scale.\n if (!u_warp) {\n return uv;\n }\n float s = uv.x + sin(uv.y * 0.125 + u_time) * 0.125;\n float t = uv.y + sin(uv.x * 0.125 + u_time) * 0.125;\n return vec2(s, t);\n}\n\nvoid main() {\n vec2 warpedTex = warpCoords(v_texCoord);\n vec4 base = texture(u_diffuseMap, warpedTex);\n\n if (u_applyLightmap) {\n vec3 light = texture(u_lightmapAtlas, warpCoords(v_lightmapCoord)).rgb;\n float styleScale = dot(u_lightStyleFactors, vec4(1.0));\n base.rgb *= light * styleScale;\n }\n\n o_color = vec4(base.rgb, base.a * u_alpha);\n}`;\n\nconst DEFAULT_STYLE_INDICES: readonly number[] = [0, 255, 255, 255];\n\nexport function resolveLightStyles(\n styleIndices: readonly number[] = DEFAULT_STYLE_INDICES,\n styleValues: ReadonlyArray<number> = []\n): Float32Array {\n const factors = new Float32Array(4);\n for (let i = 0; i < 4; i += 1) {\n const styleIndex = styleIndices[i] ?? 255;\n if (styleIndex === 255) {\n factors[i] = 0;\n continue;\n }\n const value = styleValues[styleIndex];\n factors[i] = value !== undefined ? value : 1;\n }\n return factors;\n}\n\nfunction computeFlowOffset(timeSeconds: number): readonly [number, number] {\n const cycle = (timeSeconds * 0.25) % 1;\n // Match Quake II's negative scroll direction for flowing water/conveyors.\n return [-cycle, 0];\n}\n\nexport function deriveSurfaceRenderState(\n surfaceFlags: SurfaceFlag = SURF_NONE,\n timeSeconds = 0\n): SurfaceRenderState {\n const flowing = (surfaceFlags & SURF_FLOWING) !== 0;\n const warp = (surfaceFlags & SURF_WARP) !== 0;\n const sky = (surfaceFlags & SURF_SKY) !== 0;\n const trans33 = (surfaceFlags & SURF_TRANS33) !== 0;\n const trans66 = (surfaceFlags & SURF_TRANS66) !== 0;\n\n const alpha = trans33 ? 0.33 : trans66 ? 0.66 : 1;\n const blend = trans33 || trans66;\n const depthWrite = !blend && !sky;\n const flowOffset: readonly [number, number] = flowing ? computeFlowOffset(timeSeconds) : [0, 0];\n\n return {\n alpha,\n blend,\n depthWrite,\n warp,\n flowOffset,\n sky,\n };\n}\n\nexport class BspSurfacePipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformTexScroll: WebGLUniformLocation | null;\n private readonly uniformLmScroll: WebGLUniformLocation | null;\n private readonly uniformLightStyles: WebGLUniformLocation | null;\n private readonly uniformAlpha: WebGLUniformLocation | null;\n private readonly uniformApplyLightmap: WebGLUniformLocation | null;\n private readonly uniformWarp: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n private readonly uniformLightmap: WebGLUniformLocation | null;\n private readonly uniformTime: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: BSP_SURFACE_VERTEX_SOURCE, fragment: BSP_SURFACE_FRAGMENT_SOURCE },\n { a_position: 0, a_texCoord: 1, a_lightmapCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformTexScroll = this.program.getUniformLocation('u_texScroll');\n this.uniformLmScroll = this.program.getUniformLocation('u_lightmapScroll');\n this.uniformLightStyles = this.program.getUniformLocation('u_lightStyleFactors');\n this.uniformAlpha = this.program.getUniformLocation('u_alpha');\n this.uniformApplyLightmap = this.program.getUniformLocation('u_applyLightmap');\n this.uniformWarp = this.program.getUniformLocation('u_warp');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n this.uniformLightmap = this.program.getUniformLocation('u_lightmapAtlas');\n this.uniformTime = this.program.getUniformLocation('u_time');\n }\n\n bind(options: BspSurfaceBindOptions): SurfaceRenderState {\n const {\n modelViewProjection,\n styleIndices = DEFAULT_STYLE_INDICES,\n styleValues = [],\n diffuseSampler = 0,\n lightmapSampler = 1,\n surfaceFlags = SURF_NONE,\n timeSeconds = 0,\n } = options;\n\n const state = deriveSurfaceRenderState(surfaceFlags, timeSeconds);\n const styles = resolveLightStyles(styleIndices, styleValues);\n\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform2f(this.uniformTexScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform2f(this.uniformLmScroll, state.flowOffset[0], state.flowOffset[1]);\n this.gl.uniform4fv(this.uniformLightStyles, styles);\n this.gl.uniform1f(this.uniformAlpha, state.alpha);\n this.gl.uniform1i(this.uniformApplyLightmap, state.sky ? 0 : 1);\n this.gl.uniform1i(this.uniformWarp, state.warp ? 1 : 0);\n this.gl.uniform1f(this.uniformTime, timeSeconds);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n this.gl.uniform1i(this.uniformLightmap, lightmapSampler);\n\n return state;\n }\n\n dispose(): void {\n this.program.dispose();\n }\n}\n\nexport function applySurfaceState(gl: WebGL2RenderingContext, state: SurfaceRenderState): void {\n gl.depthMask(state.depthWrite);\n if (state.blend) {\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);\n } else {\n gl.disable(gl.BLEND);\n }\n}\n","import { ShaderProgram } from './shaderProgram.js';\nimport { TextureCubeMap, VertexArray, VertexBuffer, type VertexAttributeLayout } from './resources.js';\n\nconst SKYBOX_POSITIONS = new Float32Array([\n // Front\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n -1, -1, 1,\n 1, 1, 1,\n -1, 1, 1,\n // Back\n -1, -1, -1,\n -1, 1, -1,\n 1, 1, -1,\n -1, -1, -1,\n 1, 1, -1,\n 1, -1, -1,\n // Left\n -1, -1, -1,\n -1, -1, 1,\n -1, 1, 1,\n -1, -1, -1,\n -1, 1, 1,\n -1, 1, -1,\n // Right\n 1, -1, -1,\n 1, 1, -1,\n 1, 1, 1,\n 1, -1, -1,\n 1, 1, 1,\n 1, -1, 1,\n // Top\n -1, 1, -1,\n -1, 1, 1,\n 1, 1, 1,\n -1, 1, -1,\n 1, 1, 1,\n 1, 1, -1,\n // Bottom\n -1, -1, -1,\n 1, -1, -1,\n 1, -1, 1,\n -1, -1, -1,\n 1, -1, 1,\n -1, -1, 1,\n]);\n\nexport const SKYBOX_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\n\nuniform mat4 u_viewProjectionNoTranslation;\nuniform vec2 u_scroll;\n\nout vec3 v_direction;\n\nvoid main() {\n vec3 dir = normalize(a_position);\n dir.xy += u_scroll;\n v_direction = dir;\n gl_Position = u_viewProjectionNoTranslation * vec4(a_position, 1.0);\n}`;\n\nexport const SKYBOX_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec3 v_direction;\nuniform samplerCube u_skybox;\n\nout vec4 o_color;\n\nvoid main() {\n o_color = texture(u_skybox, v_direction);\n}`;\n\nexport interface SkyboxBindOptions {\n readonly viewProjection: Float32List;\n readonly scroll: readonly [number, number];\n readonly textureUnit?: number;\n}\n\nexport class SkyboxPipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n readonly vao: VertexArray;\n readonly vbo: VertexBuffer;\n readonly cubemap: TextureCubeMap;\n\n private readonly uniformViewProj: WebGLUniformLocation | null;\n private readonly uniformScroll: WebGLUniformLocation | null;\n private readonly uniformSampler: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: SKYBOX_VERTEX_SHADER, fragment: SKYBOX_FRAGMENT_SHADER },\n { a_position: 0 }\n );\n\n this.vao = new VertexArray(gl);\n this.vbo = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.vbo.upload(SKYBOX_POSITIONS, gl.STATIC_DRAW);\n\n const layout: VertexAttributeLayout[] = [{ index: 0, size: 3, type: gl.FLOAT, stride: 12, offset: 0 }];\n this.vao.configureAttributes(layout, this.vbo);\n\n this.uniformViewProj = this.program.getUniformLocation('u_viewProjectionNoTranslation');\n this.uniformScroll = this.program.getUniformLocation('u_scroll');\n this.uniformSampler = this.program.getUniformLocation('u_skybox');\n\n this.cubemap = new TextureCubeMap(gl);\n this.cubemap.setParameters({\n minFilter: gl.LINEAR,\n magFilter: gl.LINEAR,\n wrapS: gl.CLAMP_TO_EDGE,\n wrapT: gl.CLAMP_TO_EDGE,\n });\n }\n\n bind(options: SkyboxBindOptions): void {\n const { viewProjection, scroll, textureUnit = 0 } = options;\n this.program.use();\n this.gl.depthMask(false);\n this.gl.uniformMatrix4fv(this.uniformViewProj, false, viewProjection);\n this.gl.uniform2f(this.uniformScroll, scroll[0], scroll[1]);\n this.gl.uniform1i(this.uniformSampler, textureUnit);\n this.cubemap.bind(textureUnit);\n this.vao.bind();\n }\n\n draw(): void {\n this.gl.drawArrays(this.gl.TRIANGLES, 0, SKYBOX_POSITIONS.length / 3);\n }\n\n dispose(): void {\n this.vbo.dispose();\n this.vao.dispose();\n this.cubemap.dispose();\n this.program.dispose();\n }\n}\n\nexport function removeViewTranslation(viewMatrix: Float32Array): Float32Array {\n const noTranslation = viewMatrix.slice();\n noTranslation[12] = 0;\n noTranslation[13] = 0;\n noTranslation[14] = 0;\n return noTranslation;\n}\n\nexport function computeSkyScroll(timeSeconds: number, scrollSpeeds: readonly [number, number] = [0.01, 0.02]): [number, number] {\n const [sx, sy] = scrollSpeeds;\n return [sx * timeSeconds, sy * timeSeconds];\n}\n","import { Vec3 } from '@quake2ts/shared';\nimport { Md2Model } from '../assets/md2.js';\nimport { IndexBuffer, VertexArray, VertexBuffer } from './resources.js';\nimport { ShaderProgram } from './shaderProgram.js';\n\nexport interface Md2DrawVertex {\n readonly vertexIndex: number;\n readonly texCoord: readonly [number, number];\n}\n\nexport interface Md2Geometry {\n readonly vertices: readonly Md2DrawVertex[];\n readonly indices: Uint16Array;\n}\n\nexport interface Md2FrameBlend {\n readonly currentFrame: number;\n readonly nextFrame: number;\n readonly lerp: number;\n}\n\nexport interface Md2BindOptions {\n readonly modelViewProjection: Float32List;\n readonly lightDirection?: readonly [number, number, number];\n readonly tint?: readonly [number, number, number, number];\n readonly diffuseSampler?: number;\n}\n\nexport const MD2_VERTEX_SHADER = `#version 300 es\nprecision highp float;\n\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\n\nuniform mat4 u_modelViewProjection;\nuniform vec3 u_lightDir;\n\nout vec2 v_texCoord;\nout float v_light;\n\nvoid main() {\n vec3 normal = normalize(a_normal);\n v_light = max(dot(normal, normalize(u_lightDir)), 0.0);\n v_texCoord = a_texCoord;\n gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n}`;\n\nexport const MD2_FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nin vec2 v_texCoord;\nin float v_light;\n\nuniform sampler2D u_diffuseMap;\nuniform vec4 u_tint;\n\nout vec4 o_color;\n\nvoid main() {\n vec4 albedo = texture(u_diffuseMap, v_texCoord) * u_tint;\n o_color = vec4(albedo.rgb * v_light, albedo.a);\n}`;\n\nfunction normalizeVec3(v: Vec3): Vec3 {\n const lengthSq = v.x * v.x + v.y * v.y + v.z * v.z;\n if (lengthSq <= 0) {\n return { x: 0, y: 0, z: 1 };\n }\n const inv = 1 / Math.sqrt(lengthSq);\n return { x: v.x * inv, y: v.y * inv, z: v.z * inv };\n}\n\nfunction lerp(a: number, b: number, t: number): number {\n return a + (b - a) * t;\n}\n\nfunction lerpVec3(a: Vec3, b: Vec3, t: number): Vec3 {\n return {\n x: lerp(a.x, b.x, t),\n y: lerp(a.y, b.y, t),\n z: lerp(a.z, b.z, t),\n };\n}\n\nfunction normalizeUv(s: number, t: number, header: Md2Model['header']): readonly [number, number] {\n return [s / header.skinWidth, 1 - t / header.skinHeight];\n}\n\nexport function buildMd2Geometry(model: Md2Model): Md2Geometry {\n if (model.glCommands.length === 0) {\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n model.triangles.forEach((triangle) => {\n const baseIndex = vertices.length;\n for (let i = 0; i < 3; i += 1) {\n const vertexIndex = triangle.vertexIndices[i];\n const texCoordIndex = triangle.texCoordIndices[i];\n const texCoord = model.texCoords[texCoordIndex];\n vertices.push({\n vertexIndex,\n texCoord: normalizeUv(texCoord.s, texCoord.t, model.header),\n });\n }\n indices.push(baseIndex, baseIndex + 1, baseIndex + 2);\n });\n\n return { vertices, indices: new Uint16Array(indices) };\n }\n\n const vertices: Md2DrawVertex[] = [];\n const indices: number[] = [];\n\n for (const command of model.glCommands) {\n const start = vertices.length;\n vertices.push(\n ...command.vertices.map((vertex) => ({\n vertexIndex: vertex.vertexIndex,\n texCoord: [vertex.s, 1 - vertex.t] as const,\n }))\n );\n\n if (command.mode === 'strip') {\n for (let i = 0; i < command.vertices.length - 2; i += 1) {\n const even = i % 2 === 0;\n const a = start + i + (even ? 0 : 1);\n const b = start + i + (even ? 1 : 0);\n const c = start + i + 2;\n indices.push(a, b, c);\n }\n } else {\n for (let i = 1; i < command.vertices.length - 1; i += 1) {\n indices.push(start, start + i, start + i + 1);\n }\n }\n }\n\n return { vertices, indices: new Uint16Array(indices) };\n}\n\nexport function buildMd2VertexData(\n model: Md2Model,\n geometry: Md2Geometry,\n blend: Md2FrameBlend\n): Float32Array {\n const { currentFrame, nextFrame, lerp } = blend;\n const frameA = model.frames[currentFrame];\n const frameB = model.frames[nextFrame];\n\n if (!frameA || !frameB) {\n throw new Error('Requested MD2 frames are out of range');\n }\n\n const data = new Float32Array(geometry.vertices.length * 8);\n geometry.vertices.forEach((vertex, index) => {\n const vA = frameA.vertices[vertex.vertexIndex];\n const vB = frameB.vertices[vertex.vertexIndex];\n if (!vA || !vB) {\n throw new Error('MD2 vertex index out of range for frame');\n }\n\n const position = lerpVec3(vA.position, vB.position, lerp);\n const normal = normalizeVec3(lerpVec3(vA.normal, vB.normal, lerp));\n\n const base = index * 8;\n data[base] = position.x;\n data[base + 1] = position.y;\n data[base + 2] = position.z;\n data[base + 3] = normal.x;\n data[base + 4] = normal.y;\n data[base + 5] = normal.z;\n data[base + 6] = vertex.texCoord[0];\n data[base + 7] = vertex.texCoord[1];\n });\n\n return data;\n}\n\nexport class Md2MeshBuffers {\n readonly gl: WebGL2RenderingContext;\n readonly geometry: Md2Geometry;\n readonly vertexBuffer: VertexBuffer;\n readonly indexBuffer: IndexBuffer;\n readonly vertexArray: VertexArray;\n readonly indexCount: number;\n\n constructor(gl: WebGL2RenderingContext, model: Md2Model, blend: Md2FrameBlend) {\n this.gl = gl;\n this.geometry = buildMd2Geometry(model);\n this.vertexBuffer = new VertexBuffer(gl, gl.STATIC_DRAW);\n this.indexBuffer = new IndexBuffer(gl, gl.STATIC_DRAW);\n this.vertexArray = new VertexArray(gl);\n this.indexCount = this.geometry.indices.length;\n\n this.vertexArray.configureAttributes(\n [\n { index: 0, size: 3, type: gl.FLOAT, stride: 32, offset: 0 },\n { index: 1, size: 3, type: gl.FLOAT, stride: 32, offset: 12 },\n { index: 2, size: 2, type: gl.FLOAT, stride: 32, offset: 24 },\n ],\n this.vertexBuffer\n );\n\n this.vertexArray.bind();\n this.indexBuffer.bind();\n this.indexBuffer.upload(this.geometry.indices as unknown as BufferSource, gl.STATIC_DRAW);\n this.update(model, blend);\n }\n\n update(model: Md2Model, blend: Md2FrameBlend): void {\n const data = buildMd2VertexData(model, this.geometry, blend);\n this.vertexBuffer.upload(data as unknown as BufferSource, this.gl.STATIC_DRAW);\n }\n\n bind(): void {\n this.vertexArray.bind();\n this.indexBuffer.bind();\n }\n\n dispose(): void {\n this.vertexBuffer.dispose();\n this.indexBuffer.dispose();\n this.vertexArray.dispose();\n }\n}\n\nexport class Md2Pipeline {\n readonly gl: WebGL2RenderingContext;\n readonly program: ShaderProgram;\n\n private readonly uniformMvp: WebGLUniformLocation | null;\n private readonly uniformLightDir: WebGLUniformLocation | null;\n private readonly uniformTint: WebGLUniformLocation | null;\n private readonly uniformDiffuse: WebGLUniformLocation | null;\n\n constructor(gl: WebGL2RenderingContext) {\n this.gl = gl;\n this.program = ShaderProgram.create(\n gl,\n { vertex: MD2_VERTEX_SHADER, fragment: MD2_FRAGMENT_SHADER },\n { a_position: 0, a_normal: 1, a_texCoord: 2 }\n );\n\n this.uniformMvp = this.program.getUniformLocation('u_modelViewProjection');\n this.uniformLightDir = this.program.getUniformLocation('u_lightDir');\n this.uniformTint = this.program.getUniformLocation('u_tint');\n this.uniformDiffuse = this.program.getUniformLocation('u_diffuseMap');\n }\n\n bind(options: Md2BindOptions): void {\n const { modelViewProjection, lightDirection = [0, 0, 1], tint = [1, 1, 1, 1], diffuseSampler = 0 } = options;\n const lightVec = new Float32Array(lightDirection);\n const tintVec = new Float32Array(tint);\n this.program.use();\n this.gl.uniformMatrix4fv(this.uniformMvp, false, modelViewProjection);\n this.gl.uniform3fv(this.uniformLightDir, lightVec);\n this.gl.uniform4fv(this.uniformTint, tintVec);\n this.gl.uniform1i(this.uniformDiffuse, diffuseSampler);\n }\n\n draw(mesh: Md2MeshBuffers): void {\n mesh.bind();\n this.gl.drawElements(this.gl.TRIANGLES, mesh.indexCount, this.gl.UNSIGNED_SHORT, 0);\n }\n\n dispose(): void {\n this.program.dispose();\n }\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 Md3Loader,\n Md3ParseError,\n parseMd3,\n type Md3Frame,\n type Md3Model,\n type Md3Surface,\n} from './assets/md3.js';\nexport {\n advanceAnimation,\n computeFrameBlend,\n createAnimationState,\n interpolateVec3,\n type AnimationSequence,\n type AnimationState,\n type FrameBlend,\n} from './assets/animation.js';\nexport { parseWal, type WalTexture } from './assets/wal.js';\nexport { parsePcx, pcxToRgba, type PcxImage } from './assets/pcx.js';\nexport {\n parseWalTexture,\n preparePcxTexture,\n TextureCache,\n walToRgba,\n type PreparedTexture,\n type TextureLevel,\n} from './assets/texture.js';\nexport { parseWav, type WavData } from './assets/wav.js';\nexport { decodeOgg, type OggAudio } from './assets/ogg.js';\nexport { AudioRegistry, AudioRegistryError, type DecodedAudio } from './assets/audio.js';\nexport { PakIndexStore, type StoredPakIndex } from './assets/pakIndexStore.js';\nexport {\n PakValidationError,\n PakValidator,\n RERELEASE_KNOWN_PAKS,\n type KnownPakChecksum,\n type PakValidationOutcome,\n} from './assets/pakValidation.js';\nexport {\n AssetDependencyError,\n AssetDependencyTracker,\n AssetManager,\n type AssetManagerOptions,\n} from './assets/manager.js';\nexport {\n ATTN_IDLE,\n ATTN_LOOP_NONE,\n ATTN_NONE,\n ATTN_NORM,\n ATTN_STATIC,\n MAX_SOUND_CHANNELS,\n SOUND_FULLVOLUME,\n SOUND_LOOP_ATTENUATE,\n SoundChannel,\n attenuationToDistanceMultiplier,\n calculateMaxAudibleDistance,\n} from './audio/constants.js';\nexport {\n AudioContextController,\n createAudioGraph,\n type AudioBufferLike,\n type AudioContextLike,\n type AudioGraph,\n type AudioNodeLike,\n type GainNodeLike,\n type BiquadFilterNodeLike,\n type PannerNodeLike,\n} from './audio/context.js';\nexport { SoundRegistry } from './audio/registry.js';\nexport { SoundPrecache, type SoundPrecacheOptions, type SoundPrecacheReport } from './audio/precache.js';\nexport { AudioSystem, type AudioSystemOptions, type SoundRequest } from './audio/system.js';\nexport { spatializeOrigin, type ListenerState, type SpatializationResult } from './audio/spatialization.js';\nexport { createInitialChannels, pickChannel, type ChannelState } from './audio/channels.js';\nexport { MusicSystem, type MusicSystemOptions, type MusicState, type AudioElementLike } from './audio/music.js';\nexport { AudioApi, type AudioApiOptions } from './audio/api.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 TextureCubeMap,\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';\nexport { extractFrustumPlanes, boxIntersectsFrustum, type FrustumPlane } from './render/culling.js';\nexport { findLeafForPoint, gatherVisibleFaces, type VisibleFace } from './render/bspTraversal.js';\nexport {\n applySurfaceState,\n BspSurfacePipeline,\n BSP_SURFACE_FRAGMENT_SOURCE,\n BSP_SURFACE_VERTEX_SOURCE,\n deriveSurfaceRenderState,\n resolveLightStyles,\n type BspSurfaceBindOptions,\n type SurfaceRenderState,\n} from './render/bspPipeline.js';\nexport {\n SKYBOX_FRAGMENT_SHADER,\n SKYBOX_VERTEX_SHADER,\n SkyboxPipeline,\n computeSkyScroll,\n removeViewTranslation,\n} from './render/skybox.js';\nexport {\n MD2_FRAGMENT_SHADER,\n MD2_VERTEX_SHADER,\n Md2MeshBuffers,\n Md2Pipeline,\n buildMd2Geometry,\n buildMd2VertexData,\n type Md2BindOptions,\n type Md2FrameBlend,\n type Md2Geometry,\n type Md2DrawVertex,\n} from './render/md2Pipeline.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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\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 ServerFlags {\n None = 0,\n NoClient = 1 << 0,\n DeadMonster = 1 << 1,\n Monster = 1 << 2,\n Player = 1 << 3,\n Bot = 1 << 4,\n NoBots = 1 << 5,\n Respawning = 1 << 6,\n Projectile = 1 << 7,\n Instanced = 1 << 8,\n Door = 1 << 9,\n NoCull = 1 << 10,\n Hull = 1 << 11,\n}\n\nexport enum EntityFlags {\n Fly = 1 << 0,\n Swim = 1 << 1,\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, activator?: 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 | 'inventory'\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 interface MonsterInfo {\n aiflags: number;\n}\n\nconst DEFAULT_MONSTER_INFO: MonsterInfo = Object.freeze({ aiflags: 0 });\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 killtarget?: string;\n team?: string;\n message?: string;\n pathtarget?: string;\n model?: string;\n item?: string;\n\n inventory: Record<string, number> = {};\n\n origin: Vec3 = copyVec3();\n old_origin: Vec3 = copyVec3();\n velocity: Vec3 = copyVec3();\n avelocity: Vec3 = copyVec3();\n angles: Vec3 = copyVec3();\n\n viewheight = 0;\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 movedir: Vec3 = copyVec3();\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 speed = 0;\n deadflag: DeadFlag = DeadFlag.Alive;\n count = 0;\n wait = 0;\n delay = 0;\n timestamp = 0;\n sounds = 0;\n noise_index = 0;\n fly_sound_debounce_time = 0;\n\n enemy: Entity | null = null;\n movetarget: Entity | null = null;\n target_ent: Entity | null = null;\n goalentity: Entity | null = null;\n ideal_yaw = 0;\n yaw_speed = 0;\n search_time = 0;\n attack_finished_time = 0;\n pain_finished_time = 0;\n trail_time = 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 activator: Entity | null = null;\n\n solid: Solid = Solid.Not;\n flags = 0;\n svflags = 0;\n\n monsterinfo: MonsterInfo = { ...DEFAULT_MONSTER_INFO };\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.killtarget = undefined;\n this.team = undefined;\n this.message = undefined;\n this.pathtarget = undefined;\n this.model = undefined;\n this.item = undefined;\n\n this.inventory = {};\n\n this.origin = copyVec3();\n this.old_origin = copyVec3();\n this.velocity = copyVec3();\n this.avelocity = copyVec3();\n this.angles = copyVec3();\n this.viewheight = 0;\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 this.movedir = copyVec3();\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.speed = 0;\n this.deadflag = DeadFlag.Alive;\n this.count = 0;\n this.wait = 0;\n this.delay = 0;\n this.timestamp = 0;\n this.sounds = 0;\n this.noise_index = 0;\n this.fly_sound_debounce_time = 0;\n\n this.enemy = null;\n this.movetarget = null;\n this.target_ent = null;\n this.goalentity = null;\n this.ideal_yaw = 0;\n this.yaw_speed = 0;\n this.search_time = 0;\n this.attack_finished_time = 0;\n this.pain_finished_time = 0;\n this.trail_time = 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 this.activator = null;\n\n this.solid = Solid.Not;\n this.flags = 0;\n this.svflags = 0;\n\n this.monsterinfo = { ...DEFAULT_MONSTER_INFO };\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: 'killtarget', type: 'string', save: true },\n { name: 'team', type: 'string', save: true },\n { name: 'message', type: 'string', save: true },\n { name: 'pathtarget', type: 'string', save: true },\n { name: 'model', type: 'string', save: true },\n { name: 'item', type: 'string', save: true },\n { name: 'inventory', type: 'inventory', 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: 'viewheight', type: 'int', 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: 'movedir', type: 'vec3', 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: 'speed', type: 'float', save: true },\n { name: 'deadflag', type: 'int', save: true },\n { name: 'count', type: 'int', save: true },\n { name: 'wait', type: 'float', save: true },\n { name: 'delay', type: 'float', save: true },\n { name: 'timestamp', type: 'float', save: true },\n { name: 'sounds', type: 'int', save: true },\n { name: 'noise_index', type: 'int', save: true },\n { name: 'fly_sound_debounce_time', type: 'float', save: true },\n { name: 'enemy', type: 'entity', save: true },\n { name: 'movetarget', type: 'entity', save: true },\n { name: 'target_ent', 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: 'search_time', type: 'float', save: true },\n { name: 'attack_finished_time', type: 'float', save: true },\n { name: 'pain_finished_time', type: 'float', save: true },\n { name: 'trail_time', 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 interface EntityPoolSnapshot {\n readonly capacity: number;\n readonly activeOrder: readonly number[];\n readonly freeList: readonly number[];\n readonly pendingFree: readonly number[];\n}\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 freeImmediate(entity: Entity): void {\n if (entity.index === WORLD_INDEX) {\n throw new Error('Cannot free world entity');\n }\n\n if (!entity.inUse) {\n return;\n }\n\n this.unlink(entity);\n entity.reset();\n this.freeList.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 createSnapshot(): EntityPoolSnapshot {\n const activeOrder = Array.from(this, (entity) => entity.index);\n return {\n capacity: this.entities.length,\n activeOrder,\n freeList: [...this.freeList],\n pendingFree: [...this.pendingFree],\n };\n }\n\n restore(snapshot: EntityPoolSnapshot): void {\n if (snapshot.capacity !== this.entities.length) {\n throw new Error(`Snapshot capacity ${snapshot.capacity} does not match pool capacity ${this.entities.length}`);\n }\n\n const seen = new Set<number>();\n const noteIndex = (index: number, label: string) => {\n if (index < 0 || index >= this.entities.length) {\n throw new Error(`Invalid entity index ${index} in ${label}`);\n }\n if (seen.has(index)) {\n throw new Error(`Duplicate entity index ${index} in snapshot`);\n }\n seen.add(index);\n };\n\n for (const index of snapshot.activeOrder) {\n noteIndex(index, 'activeOrder');\n }\n for (const index of snapshot.freeList) {\n noteIndex(index, 'freeList');\n }\n for (const index of snapshot.pendingFree) {\n noteIndex(index, 'pendingFree');\n }\n\n this.activeHead = null;\n this.freeList.length = 0;\n this.pendingFree.length = 0;\n\n for (const entity of this.entities) {\n entity.reset();\n }\n\n for (let i = snapshot.activeOrder.length - 1; i >= 0; i -= 1) {\n const entity = this.entities[snapshot.activeOrder[i]];\n entity.inUse = true;\n this.link(entity);\n }\n\n for (const index of snapshot.pendingFree) {\n const entity = this.entities[index];\n entity.inUse = false;\n entity.freePending = true;\n entity.linkNext = null;\n entity.linkPrevious = null;\n this.pendingFree.push(index);\n }\n\n for (const index of snapshot.freeList) {\n const entity = this.entities[index];\n entity.inUse = false;\n entity.freePending = false;\n entity.linkNext = null;\n entity.linkPrevious = null;\n this.freeList.push(index);\n }\n\n if (!snapshot.activeOrder.includes(WORLD_INDEX)) {\n throw new Error('Snapshot must include the world entity as active');\n }\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 interface ThinkScheduleEntry {\n readonly time: number;\n readonly entityIndex: number;\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 snapshot(): ThinkScheduleEntry[] {\n return this.queue.map(({ time, entity }) => ({ time, entityIndex: entity.index }));\n }\n\n restore(entries: ThinkScheduleEntry[], resolver: (index: number) => Entity | undefined): void {\n this.queue.length = 0;\n for (const entry of entries) {\n const entity = resolver(entry.entityIndex);\n if (!entity) {\n continue;\n }\n this.schedule(entity, entry.time);\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 { createRandomGenerator } from '@quake2ts/shared';\nimport {\n DeadFlag,\n ENTITY_FIELD_METADATA,\n Entity,\n ServerFlags,\n type EntityFieldDescriptor,\n Solid,\n} from './entity.js';\nimport { EntityPool, type EntityPoolSnapshot } from './pool.js';\nimport { ThinkScheduler, type ThinkScheduleEntry } 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\ntype SerializableVec3 = readonly [number, number, number];\n\ntype SerializableInventory = Record<string, number>;\n\ntype SerializableEntityFieldValue =\n | number\n | string\n | boolean\n | null\n | SerializableVec3\n | SerializableInventory;\n\ntype SerializableFieldName = Exclude<\n (typeof ENTITY_FIELD_METADATA)[number]['name'],\n 'think' | 'touch' | 'use' | 'pain' | 'die' | 'index'\n>;\ntype SerializableFieldDescriptor = EntityFieldDescriptor<SerializableFieldName>;\n\nconst SERIALIZABLE_FIELDS = ENTITY_FIELD_METADATA.filter(\n (field) => field.save,\n) as SerializableFieldDescriptor[];\nconst DESCRIPTORS = new Map(SERIALIZABLE_FIELDS.map((descriptor) => [descriptor.name, descriptor]));\n\nexport interface SerializedEntityState {\n readonly index: number;\n readonly fields: Partial<Record<SerializableFieldName, SerializableEntityFieldValue>>;\n}\n\nexport interface EntitySystemSnapshot {\n readonly timeSeconds: number;\n readonly pool: EntityPoolSnapshot;\n readonly entities: SerializedEntityState[];\n readonly thinks: ThinkScheduleEntry[];\n}\n\n\nfunction serializeVec3(vec: Vec3): SerializableVec3 {\n return [vec.x, vec.y, vec.z];\n}\n\nfunction deserializeVec3(value: SerializableEntityFieldValue): Vec3 {\n const vec = value as SerializableVec3;\n if (!Array.isArray(vec) || vec.length !== 3) {\n throw new Error('Invalid vec3 serialization');\n }\n const [x, y, z] = vec;\n return { x, y, z };\n}\n\nfunction assignField(entity: Entity, name: SerializableFieldName, value: Entity[SerializableFieldName]): void {\n (entity as Record<SerializableFieldName, Entity[SerializableFieldName]>)[name] = value;\n}\n\nfunction serializeInventory(inventory: Record<string, number>): SerializableInventory {\n return { ...inventory };\n}\n\nfunction deserializeInventory(value: SerializableEntityFieldValue): Record<string, number> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error('Invalid inventory serialization');\n }\n\n const parsed: Record<string, number> = {};\n for (const [key, entry] of Object.entries(value)) {\n parsed[key] = Number(entry);\n }\n return parsed;\n}\n\nexport class EntitySystem {\n private readonly pool: EntityPool;\n private readonly thinkScheduler: ThinkScheduler;\n private readonly targetNameIndex = new Map<string, Set<Entity>>();\n private readonly random = createRandomGenerator();\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.unregisterTarget(entity);\n this.thinkScheduler.cancel(entity);\n this.pool.deferFree(entity);\n }\n\n freeImmediate(entity: Entity): void {\n this.unregisterTarget(entity);\n this.thinkScheduler.cancel(entity);\n this.pool.freeImmediate(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 finalizeSpawn(entity: Entity): void {\n if (!entity.inUse || entity.freePending) {\n return;\n }\n this.registerTarget(entity);\n }\n\n findByClassname(classname: string): Entity[] {\n const matches: Entity[] = [];\n for (const entity of this.pool) {\n if (entity.classname === classname && entity.inUse && !entity.freePending) {\n matches.push(entity);\n }\n }\n return matches;\n }\n\n findByTargetName(targetname: string): Entity[] {\n const matches = this.targetNameIndex.get(targetname);\n if (!matches) {\n return [];\n }\n return Array.from(matches).filter((entity) => entity.inUse && !entity.freePending);\n }\n\n pickTarget(targetname: string | undefined): Entity | null {\n if (!targetname) {\n return null;\n }\n const matches = this.findByTargetName(targetname);\n if (matches.length === 0) {\n return null;\n }\n const choice = this.random.randomIndex(matches);\n return matches[choice] ?? null;\n }\n\n killBox(entity: Entity): void {\n const targetBounds = computeBounds(entity);\n for (const other of this.pool) {\n if (other === entity || other === this.pool.world) {\n continue;\n }\n if (!other.inUse || other.freePending || other.solid === Solid.Not) {\n continue;\n }\n if (other.svflags & ServerFlags.DeadMonster) {\n continue;\n }\n if (!boundsIntersect(targetBounds, computeBounds(other))) {\n continue;\n }\n other.health = 0;\n other.deadflag = DeadFlag.Dead;\n this.free(other);\n }\n }\n\n useTargets(entity: Entity, activator: Entity | null = null): void {\n if (entity.delay > 0) {\n const delayed = this.spawn();\n delayed.classname = 'DelayedUse';\n delayed.target = entity.target;\n delayed.killtarget = entity.killtarget;\n delayed.message = entity.message;\n delayed.think = (self) => {\n this.useTargetsImmediate(self, activator ?? entity);\n this.free(self);\n };\n this.scheduleThink(delayed, this.currentTimeSeconds + entity.delay);\n return;\n }\n\n this.useTargetsImmediate(entity, activator ?? entity);\n }\n\n runFrame(): void {\n this.thinkScheduler.runDueThinks(this.currentTimeSeconds);\n this.runTouches();\n this.pool.flushFreeList();\n }\n\n createSnapshot(): EntitySystemSnapshot {\n const entities: SerializedEntityState[] = [];\n for (const entity of this.pool) {\n const fields: Partial<Record<SerializableFieldName, SerializableEntityFieldValue>> = {};\n for (const descriptor of SERIALIZABLE_FIELDS) {\n const value = entity[descriptor.name];\n switch (descriptor.type) {\n case 'vec3':\n fields[descriptor.name] = serializeVec3(value as Vec3);\n break;\n case 'entity':\n fields[descriptor.name] = (value as Entity | null)?.index ?? null;\n break;\n case 'inventory':\n fields[descriptor.name] = serializeInventory(value as Record<string, number>);\n break;\n default:\n fields[descriptor.name] = (value as SerializableEntityFieldValue) ?? null;\n break;\n }\n }\n entities.push({\n index: entity.index,\n fields,\n });\n }\n\n return {\n timeSeconds: this.currentTimeSeconds,\n pool: this.pool.createSnapshot(),\n entities,\n thinks: this.thinkScheduler.snapshot(),\n };\n }\n\n restore(snapshot: EntitySystemSnapshot): void {\n this.currentTimeSeconds = snapshot.timeSeconds;\n this.pool.restore(snapshot.pool);\n\n const indexToEntity = new Map<number, Entity>();\n for (const entity of this.pool) {\n indexToEntity.set(entity.index, entity);\n }\n\n const pendingEntityRefs: Array<{ entity: Entity; name: SerializableFieldName; targetIndex: number | null }>\n = [];\n\n for (const serialized of snapshot.entities) {\n const entity = indexToEntity.get(serialized.index);\n if (!entity) {\n continue;\n }\n\n for (const [name, value] of Object.entries(serialized.fields) as [\n SerializableFieldName,\n SerializableEntityFieldValue,\n ][]) {\n const descriptor = DESCRIPTORS.get(name);\n if (!descriptor || value === undefined) {\n continue;\n }\n\n switch (descriptor.type) {\n case 'vec3':\n assignField(entity, name, deserializeVec3(value) as Entity[typeof name]);\n break;\n case 'entity':\n pendingEntityRefs.push({\n entity,\n name: descriptor.name,\n targetIndex: value as number | null,\n });\n break;\n case 'inventory':\n assignField(entity, name, deserializeInventory(value) as Entity[typeof name]);\n break;\n case 'boolean':\n assignField(entity, name, Boolean(value) as Entity[typeof name]);\n break;\n default:\n assignField(entity, name, value as Entity[typeof name]);\n break;\n }\n }\n }\n\n for (const ref of pendingEntityRefs) {\n const target = ref.targetIndex === null ? null : indexToEntity.get(ref.targetIndex) ?? null;\n assignField(ref.entity, ref.name, target as Entity[SerializableFieldName]);\n }\n\n this.thinkScheduler.restore(snapshot.thinks, (index) => indexToEntity.get(index));\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 || entity.solid === Solid.Not) {\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 private registerTarget(entity: Entity): void {\n if (!entity.targetname) {\n return;\n }\n let bucket = this.targetNameIndex.get(entity.targetname);\n if (!bucket) {\n bucket = new Set<Entity>();\n this.targetNameIndex.set(entity.targetname, bucket);\n }\n bucket.add(entity);\n }\n\n private unregisterTarget(entity: Entity): void {\n if (!entity.targetname) {\n return;\n }\n const bucket = this.targetNameIndex.get(entity.targetname);\n if (!bucket) {\n return;\n }\n bucket.delete(entity);\n if (bucket.size === 0) {\n this.targetNameIndex.delete(entity.targetname);\n }\n }\n\n private useTargetsImmediate(entity: Entity, activator: Entity | null): void {\n if (entity.target) {\n for (const target of this.findByTargetName(entity.target)) {\n if (target === entity) {\n continue;\n }\n target.use?.(target, entity, activator);\n }\n }\n\n if (entity.killtarget) {\n for (const victim of this.findByTargetName(entity.killtarget)) {\n if (victim === entity) {\n continue;\n }\n this.free(victim);\n }\n }\n }\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { angleVectors, ZERO_VEC3 } from '@quake2ts/shared';\n\nconst VEC_UP: Vec3 = { x: 0, y: -1, z: 0 } as const;\nconst MOVEDIR_UP: Vec3 = { x: 0, y: 0, z: 1 } as const;\nconst VEC_DOWN: Vec3 = { x: 0, y: -2, z: 0 } as const;\nconst MOVEDIR_DOWN: Vec3 = { x: 0, y: 0, z: -1 } as const;\n\nfunction vecEquals(a: Vec3, b: Vec3): boolean {\n return a.x === b.x && a.y === b.y && a.z === b.z;\n}\n\nexport function isZeroVector(vector: Vec3): boolean {\n return vecEquals(vector, ZERO_VEC3 as Vec3);\n}\n\nexport function setMovedir(angles: Vec3): Vec3 {\n if (vecEquals(angles, VEC_UP)) {\n return { ...MOVEDIR_UP };\n }\n if (vecEquals(angles, VEC_DOWN)) {\n return { ...MOVEDIR_DOWN };\n }\n return { ...angleVectors(angles).forward };\n}\n","import { angleVectors } from '@quake2ts/shared';\nimport { EntityFlags, MoveType, ServerFlags, Solid, type Entity, type TouchCallback } from './entity.js';\nimport type { SpawnRegistry } from './spawn.js';\nimport { isZeroVector, setMovedir } from './utils.js';\nimport type { EntitySystem } from './system.js';\n\nconst FRAME_TIME_SECONDS = 1 / 40;\nconst THINK_INTERVAL = 0.1;\nconst HURT_INTERVAL = 0.1;\n\nconst TRIGGER_SPAWNFLAGS = {\n Monster: 1 << 0,\n NotPlayer: 1 << 1,\n Triggered: 1 << 2,\n Toggle: 1 << 3,\n Latched: 1 << 4,\n Clip: 1 << 5,\n} as const;\n\nconst RELAY_SPAWNFLAGS = {\n NoSound: 1 << 0,\n} as const;\n\nconst COUNTER_SPAWNFLAGS = {\n NoMessage: 1 << 0,\n} as const;\n\nconst PUSH_SPAWNFLAGS = {\n Once: 1 << 0,\n Plus: 1 << 1,\n Silent: 1 << 2,\n StartOff: 1 << 3,\n Clip: 1 << 4,\n} as const;\n\nconst HURT_SPAWNFLAGS = {\n StartOff: 1 << 0,\n Toggle: 1 << 1,\n Silent: 1 << 2,\n NoProtection: 1 << 3,\n Slow: 1 << 4,\n NoPlayers: 1 << 5,\n NoMonsters: 1 << 6,\n Clip: 1 << 7,\n} as const;\n\nconst TELEPORT_SPAWNFLAGS = {\n StartOn: 1 << 3,\n} as const;\n\nconst GRAVITY_SPAWNFLAGS = {\n Toggle: 1 << 0,\n StartOff: 1 << 1,\n Clip: 1 << 2,\n} as const;\n\nconst MONSTERJUMP_SPAWNFLAGS = {\n Toggle: 1 << 0,\n StartOff: 1 << 1,\n Clip: 1 << 2,\n} as const;\n\nfunction trainResume(train: Entity, entities: EntitySystem): void {\n if (!train.think) {\n train.think = (self) => {\n self.nextthink = 0;\n };\n }\n entities.scheduleThink(train, entities.timeSeconds + FRAME_TIME_SECONDS);\n}\n\nfunction initTrigger(entity: Entity): void {\n entity.movetype = MoveType.None;\n entity.solid = Solid.Trigger;\n entity.svflags |= ServerFlags.NoClient;\n entity.movedir = setMovedir(entity.angles);\n entity.angles = { x: 0, y: 0, z: 0 };\n}\n\nfunction multiWait(self: Entity): void {\n self.nextthink = 0;\n self.think = undefined;\n}\n\nfunction canActivate(trigger: Entity, other: Entity): boolean {\n if (trigger.solid === Solid.Not) {\n return false;\n }\n if (other.svflags & ServerFlags.Player) {\n if (trigger.spawnflags & TRIGGER_SPAWNFLAGS.NotPlayer) {\n return false;\n }\n } else if (other.svflags & ServerFlags.Monster) {\n if ((trigger.spawnflags & TRIGGER_SPAWNFLAGS.Monster) === 0) {\n return false;\n }\n } else {\n return false;\n }\n\n if (!isZeroVector(trigger.movedir)) {\n const forward = angleVectors(other.angles).forward;\n const dot = forward.x * trigger.movedir.x + forward.y * trigger.movedir.y + forward.z * trigger.movedir.z;\n if (dot < 0) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction multiTrigger(self: Entity, entities: EntitySystem): void {\n if (self.nextthink > entities.timeSeconds) {\n return;\n }\n\n entities.useTargets(self, self.activator);\n\n if (self.wait > 0) {\n self.think = multiWait;\n entities.scheduleThink(self, entities.timeSeconds + self.wait);\n } else {\n self.touch = undefined;\n self.think = (entity) => {\n entities.free(entity);\n };\n entities.scheduleThink(self, entities.timeSeconds + FRAME_TIME_SECONDS);\n }\n}\n\nfunction touchMulti(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n if (!canActivate(self, other)) {\n return;\n }\n\n self.activator = other;\n multiTrigger(self, entities);\n}\n\nfunction useMulti(self: Entity, _other: Entity | null, activator: Entity | null, entities: EntitySystem): void {\n if (self.spawnflags & TRIGGER_SPAWNFLAGS.Toggle) {\n self.solid = self.solid === Solid.Trigger ? Solid.Not : Solid.Trigger;\n return;\n }\n self.activator = activator;\n multiTrigger(self, entities);\n}\n\nfunction triggerEnable(self: Entity): void {\n self.solid = Solid.Trigger;\n}\n\nfunction registerTriggerMultiple(registry: SpawnRegistry): void {\n registry.register('trigger_multiple', (entity, context) => {\n initTrigger(entity);\n\n if (entity.wait === 0) {\n entity.wait = 0.2;\n }\n\n if (entity.spawnflags & TRIGGER_SPAWNFLAGS.Latched) {\n // Latched triggers rely on area queries; fall back to touch behaviour for now.\n }\n\n if (entity.spawnflags & (TRIGGER_SPAWNFLAGS.Triggered | TRIGGER_SPAWNFLAGS.Toggle)) {\n entity.solid = Solid.Not;\n entity.use = (self, other, activator) => {\n triggerEnable(self);\n useMulti(self, other, activator ?? other, context.entities);\n };\n } else {\n entity.use = (self, other, activator) => useMulti(self, other, activator ?? other, context.entities);\n }\n\n entity.touch = (self, other) => touchMulti(self, other, context.entities);\n });\n}\n\nfunction registerTriggerOnce(registry: SpawnRegistry): void {\n registry.register('trigger_once', (entity, context) => {\n entity.wait = -1;\n registry.get('trigger_multiple')?.(entity, context);\n });\n}\n\nfunction registerTriggerRelay(registry: SpawnRegistry): void {\n registry.register('trigger_relay', (entity, context) => {\n if (entity.spawnflags & RELAY_SPAWNFLAGS.NoSound) {\n entity.noise_index = -1;\n }\n\n entity.use = (self, _other, activator) => {\n context.entities.useTargets(self, activator ?? self);\n };\n });\n}\n\nfunction registerTriggerAlways(registry: SpawnRegistry): void {\n registry.register('trigger_always', (entity, context) => {\n if (entity.delay === 0) {\n entity.delay = 0.2;\n }\n\n context.entities.useTargets(entity, entity);\n });\n}\n\nfunction counterUse(self: Entity, _other: Entity | null, activator: Entity | null, entities: EntitySystem): void {\n if (self.count === 0) {\n return;\n }\n\n self.count -= 1;\n\n if (self.count > 0) {\n return;\n }\n\n self.activator = activator;\n multiTrigger(self, entities);\n}\n\nfunction registerTriggerCounter(registry: SpawnRegistry): void {\n registry.register('trigger_counter', (entity, context) => {\n entity.wait = -1;\n if (entity.count === 0) {\n entity.count = 2;\n }\n\n entity.use = (self, other, activator) => counterUse(self, other, activator ?? other, context.entities);\n if (!(entity.spawnflags & COUNTER_SPAWNFLAGS.NoMessage)) {\n entity.message = entity.message ?? 'sequence complete';\n }\n });\n}\n\nfunction triggerKeyUse(self: Entity, activator: Entity | null, entities: EntitySystem, warn: (message: string) => void): void {\n if (!self.item || !activator) {\n return;\n }\n\n const available = activator.inventory[self.item] ?? 0;\n if (available <= 0) {\n if (self.timestamp > entities.timeSeconds) {\n return;\n }\n self.timestamp = entities.timeSeconds + 5;\n warn(`Missing required key item: ${self.item}`);\n return;\n }\n\n activator.inventory[self.item] = available - 1;\n if (activator.inventory[self.item] <= 0) {\n delete activator.inventory[self.item];\n }\n\n entities.useTargets(self, activator);\n self.use = undefined;\n}\n\nfunction registerTriggerKey(registry: SpawnRegistry): void {\n registry.register('trigger_key', (entity, context) => {\n const requiredItem = context.keyValues.item;\n if (!requiredItem) {\n context.warn('trigger_key requires an item');\n context.free(entity);\n return;\n }\n\n entity.item = requiredItem;\n entity.use = (self, other, activator) => triggerKeyUse(self, activator ?? other, context.entities, context.warn);\n });\n}\n\nfunction triggerPushTouch(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n\n\n if (other.classname === 'grenade' || other.health > 0) {\n const scale = (self.speed || 1000) * 10;\n other.velocity = {\n x: self.movedir.x * scale,\n y: self.movedir.y * scale,\n z: self.movedir.z * scale,\n };\n }\n\n if (self.spawnflags & PUSH_SPAWNFLAGS.Once) {\n entities.free(self);\n }\n}\n\nfunction toggleSolid(self: Entity): void {\n self.solid = self.solid === Solid.Not ? Solid.Trigger : Solid.Not;\n}\n\nfunction triggerPushInactive(self: Entity, entities: EntitySystem, touchHandler: TouchCallback): void {\n if (self.delay > entities.timeSeconds) {\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n return;\n }\n\n self.touch = touchHandler;\n self.think = (entity) => triggerPushActive(entity, entities, touchHandler);\n self.delay = entities.timeSeconds + self.wait;\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n}\n\nfunction triggerPushActive(self: Entity, entities: EntitySystem, touchHandler: TouchCallback): void {\n if (self.delay > entities.timeSeconds) {\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n return;\n }\n\n self.touch = undefined;\n self.think = (entity) => triggerPushInactive(entity, entities, touchHandler);\n self.delay = entities.timeSeconds + self.wait;\n entities.scheduleThink(self, entities.timeSeconds + THINK_INTERVAL);\n}\n\nfunction registerTriggerPush(registry: SpawnRegistry): void {\n registry.register('trigger_push', (entity, context) => {\n initTrigger(entity);\n\n const touchHandler: TouchCallback = (self, other) => triggerPushTouch(self, other, context.entities);\n entity.touch = touchHandler;\n\n if (!entity.speed) {\n entity.speed = 1000;\n }\n\n if (entity.spawnflags & PUSH_SPAWNFLAGS.Plus) {\n if (!entity.wait) {\n entity.wait = 10;\n }\n entity.delay = context.entities.timeSeconds + entity.wait;\n entity.think = (self) => triggerPushActive(self, context.entities, touchHandler);\n context.entities.scheduleThink(entity, context.entities.timeSeconds + THINK_INTERVAL);\n }\n\n if (entity.targetname) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n if (entity.spawnflags & PUSH_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n } else if (entity.spawnflags & PUSH_SPAWNFLAGS.StartOff) {\n context.warn('trigger_push is START_OFF but not targeted.');\n entity.touch = undefined;\n entity.solid = Solid.Bsp;\n entity.movetype = MoveType.Push;\n }\n });\n}\n\nfunction hurtTouch(self: Entity, other: Entity | null, entities: EntitySystem): void {\n if (!other) {\n return;\n }\n if (!other.takedamage && other.classname !== 'grenade') {\n return;\n }\n if (self.spawnflags & HURT_SPAWNFLAGS.NoMonsters && (other.svflags & ServerFlags.Monster)) {\n return;\n }\n if (self.spawnflags & HURT_SPAWNFLAGS.NoPlayers && (other.svflags & ServerFlags.Player)) {\n return;\n }\n if (self.timestamp > entities.timeSeconds) {\n return;\n }\n\n self.timestamp = entities.timeSeconds + (self.spawnflags & HURT_SPAWNFLAGS.Slow ? 1 : HURT_INTERVAL);\n\n const damage = self.dmg || 5;\n other.health -= damage;\n}\n\nfunction registerTriggerHurt(registry: SpawnRegistry): void {\n registry.register('trigger_hurt', (entity, context) => {\n initTrigger(entity);\n\n entity.dmg = entity.dmg || 5;\n const touchHandler: TouchCallback = (self, other) => hurtTouch(self, other, context.entities);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & HURT_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & HURT_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nfunction teleportTouch(\n self: Entity,\n other: Entity | null,\n entities: EntitySystem,\n warn: (message: string) => void,\n): void {\n if (!other) {\n return;\n }\n if (self.delay > 0) {\n return;\n }\n\n const destination = entities.pickTarget(self.target);\n if (!destination) {\n warn('trigger_teleport target not found');\n return;\n }\n\n const destOrigin = {\n x: destination.origin.x,\n y: destination.origin.y,\n z: destination.origin.z + 10,\n } as const;\n\n other.origin = { ...destOrigin };\n other.old_origin = { ...destOrigin };\n other.velocity = { x: 0, y: 0, z: 0 };\n other.groundentity = null;\n other.angles = { ...destination.angles };\n\n entities.killBox(other);\n}\n\nfunction registerTriggerTeleport(registry: SpawnRegistry): void {\n registry.register('trigger_teleport', (entity, context) => {\n if (!entity.wait) {\n entity.wait = 0.2;\n }\n\n initTrigger(entity);\n\n if (entity.targetname) {\n entity.use = (self) => {\n self.delay = self.delay > 0 ? 0 : 1;\n };\n if ((entity.spawnflags & TELEPORT_SPAWNFLAGS.StartOn) === 0) {\n entity.delay = 1;\n }\n }\n\n entity.touch = (self, other) => teleportTouch(self, other, context.entities, context.warn);\n });\n}\n\nfunction gravityTouch(self: Entity, other: Entity | null): void {\n if (!other) {\n return;\n }\n\n if (self.spawnflags & GRAVITY_SPAWNFLAGS.Clip) {\n // Clipping requires a trace against world geometry, which is not yet available.\n // Fall back to bounding-box overlap behaviour.\n }\n\n other.gravity = self.gravity;\n}\n\nfunction registerTriggerGravity(registry: SpawnRegistry): void {\n registry.register('trigger_gravity', (entity, context) => {\n const gravityText = context.keyValues.gravity;\n if (!gravityText) {\n context.warn('trigger_gravity requires a gravity value');\n context.free(entity);\n return;\n }\n\n initTrigger(entity);\n entity.gravity = Number.parseFloat(gravityText) || 0;\n\n const touchHandler: TouchCallback = (self, other) => gravityTouch(self, other);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & GRAVITY_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & GRAVITY_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nfunction monsterJumpTouch(self: Entity, other: Entity | null): void {\n if (!other) {\n return;\n }\n\n if ((other.flags & (EntityFlags.Fly | EntityFlags.Swim)) !== 0) {\n return;\n }\n if (other.svflags & ServerFlags.DeadMonster) {\n return;\n }\n if ((other.svflags & ServerFlags.Monster) === 0) {\n return;\n }\n\n other.velocity = {\n x: self.movedir.x * self.speed,\n y: self.movedir.y * self.speed,\n z: other.velocity.z,\n };\n\n if (!other.groundentity) {\n return;\n }\n\n other.groundentity = null;\n other.velocity = { x: other.velocity.x, y: other.velocity.y, z: self.movedir.z };\n}\n\nfunction triggerElevatorUse(\n self: Entity,\n other: Entity | null,\n entities: EntitySystem,\n warn: (message: string) => void,\n): void {\n if (!self.movetarget) {\n return;\n }\n if (self.movetarget.nextthink > 0) {\n return;\n }\n\n if (!other?.pathtarget) {\n warn('trigger_elevator used with no pathtarget');\n return;\n }\n\n const target = entities.pickTarget(other.pathtarget);\n if (!target) {\n warn(`trigger_elevator used with bad pathtarget: ${other.pathtarget}`);\n return;\n }\n\n self.movetarget.target_ent = target;\n trainResume(self.movetarget, entities);\n}\n\nfunction triggerElevatorInit(self: Entity, entities: EntitySystem, warn: (message: string) => void): void {\n if (!self.target) {\n warn('trigger_elevator has no target');\n return;\n }\n\n const target = entities.pickTarget(self.target);\n if (!target) {\n warn(`trigger_elevator unable to find target ${self.target}`);\n return;\n }\n\n self.movetarget = target;\n if (target.classname !== 'func_train') {\n warn(`trigger_elevator target ${self.target} is not a train`);\n return;\n }\n\n self.use = (entity, other, activator) =>\n triggerElevatorUse(entity, other ?? activator ?? null, entities, warn);\n self.svflags |= ServerFlags.NoClient;\n}\n\nfunction registerTriggerElevator(registry: SpawnRegistry): void {\n registry.register('trigger_elevator', (entity, context) => {\n entity.think = (self) => triggerElevatorInit(self, context.entities, context.warn);\n context.entities.scheduleThink(entity, context.entities.timeSeconds + FRAME_TIME_SECONDS);\n });\n}\n\nfunction registerTriggerMonsterJump(registry: SpawnRegistry): void {\n registry.register('trigger_monsterjump', (entity, context) => {\n const heightText = context.keyValues.height;\n const height = heightText ? Number.parseFloat(heightText) || 0 : 200;\n if (entity.angles.y === 0) {\n entity.angles = { ...entity.angles, y: 360 };\n }\n if (!entity.speed) {\n entity.speed = 200;\n }\n\n initTrigger(entity);\n entity.movedir = { ...entity.movedir, z: height };\n const touchHandler: TouchCallback = (self, other) => monsterJumpTouch(self, other);\n entity.touch = touchHandler;\n\n if (entity.spawnflags & MONSTERJUMP_SPAWNFLAGS.StartOff) {\n entity.solid = Solid.Not;\n entity.touch = undefined;\n }\n\n if (entity.spawnflags & MONSTERJUMP_SPAWNFLAGS.Toggle) {\n entity.use = (self) => {\n toggleSolid(self);\n self.touch = self.solid === Solid.Trigger ? touchHandler : undefined;\n };\n }\n });\n}\n\nexport function registerTriggerSpawns(registry: SpawnRegistry): void {\n registerTriggerMultiple(registry);\n registerTriggerOnce(registry);\n registerTriggerRelay(registry);\n registerTriggerAlways(registry);\n registerTriggerCounter(registry);\n registerTriggerKey(registry);\n registerTriggerPush(registry);\n registerTriggerHurt(registry);\n registerTriggerTeleport(registry);\n registerTriggerGravity(registry);\n registerTriggerElevator(registry);\n registerTriggerMonsterJump(registry);\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { ENTITY_FIELD_METADATA, type EntityFieldDescriptor, Entity, MoveType, Solid } from './entity.js';\nimport { registerTriggerSpawns } from './triggers.js';\nimport type { EntitySystem } from './system.js';\n\nexport type ParsedEntity = Record<string, string>;\n\ntype ParseableKeys = keyof Entity & string;\ntype FieldLookupEntry = EntityFieldDescriptor<ParseableKeys>;\n\nconst FIELD_LOOKUP: ReadonlyMap<ParseableKeys, FieldLookupEntry> = new Map(\n ENTITY_FIELD_METADATA.map((field) => [field.name as ParseableKeys, field as FieldLookupEntry]),\n);\n\nfunction parseVec3(text: string): Vec3 {\n const parts = text.trim().split(/\\s+/);\n const [x = 0, y = 0, z = 0] = parts.map((part) => Number.parseFloat(part)).map((value) => (Number.isNaN(value) ? 0 : value));\n return { x, y, z } as const;\n}\n\nfunction parseBoolean(text: string): boolean {\n const normalized = text.trim().toLowerCase();\n return normalized === '1' || normalized === 'true' || normalized === 'yes';\n}\n\nfunction parseValue(type: FieldLookupEntry['type'], value: string): unknown {\n switch (type) {\n case 'int':\n return Number.parseInt(value, 10) || 0;\n case 'float':\n return Number.parseFloat(value) || 0;\n case 'boolean':\n return parseBoolean(value);\n case 'vec3':\n return parseVec3(value);\n case 'string':\n return value;\n case 'entity':\n case 'callback':\n return undefined;\n default:\n return value;\n }\n}\n\nexport function applyEntityKeyValues(entity: Entity, values: ParsedEntity): void {\n if ('angle' in values && !('angles' in values)) {\n entity.angles = { x: 0, y: Number.parseFloat(values.angle) || 0, z: 0 };\n }\n\n for (const [key, rawValue] of Object.entries(values)) {\n if (key.startsWith('_')) {\n continue;\n }\n\n const descriptor = FIELD_LOOKUP.get(key as ParseableKeys);\n if (!descriptor) {\n continue;\n }\n\n const parsed = parseValue(descriptor.type, rawValue);\n if (parsed !== undefined) {\n (entity as unknown as Record<ParseableKeys, unknown>)[descriptor.name] = parsed;\n }\n }\n\n entity.size = {\n x: entity.maxs.x - entity.mins.x,\n y: entity.maxs.y - entity.mins.y,\n z: entity.maxs.z - entity.mins.z,\n } as const;\n}\n\nfunction parseQuoted(text: string, start: number): { value: string; nextIndex: number } {\n let index = start;\n let result = '';\n while (index < text.length) {\n const char = text[index];\n if (char === '\"') {\n return { value: result, nextIndex: index + 1 };\n }\n result += char;\n index += 1;\n }\n throw new Error('Unterminated quoted string in entity lump');\n}\n\nfunction consumeWhitespace(text: string, start: number): number {\n let index = start;\n while (index < text.length && /\\s/.test(text[index] ?? '')) {\n index += 1;\n }\n return index;\n}\n\nfunction parseToken(text: string, start: number): { token: string | null; nextIndex: number } {\n const index = consumeWhitespace(text, start);\n if (index >= text.length) {\n return { token: null, nextIndex: index };\n }\n\n const current = text[index];\n if (current === '{' || current === '}') {\n return { token: current, nextIndex: index + 1 };\n }\n\n if (current !== '\"') {\n throw new Error(`Unexpected token in entity lump: ${current}`);\n }\n\n const quoted = parseQuoted(text, index + 1);\n return { token: quoted.value, nextIndex: quoted.nextIndex };\n}\n\nexport function parseEntityLump(text: string): ParsedEntity[] {\n const entities: ParsedEntity[] = [];\n let index = 0;\n\n while (index < text.length) {\n const open = parseToken(text, index);\n index = open.nextIndex;\n if (open.token === null) {\n break;\n }\n if (open.token !== '{') {\n throw new Error('Expected { at start of entity definition');\n }\n\n const entity: ParsedEntity = {};\n\n while (true) {\n const keyToken = parseToken(text, index);\n index = keyToken.nextIndex;\n if (keyToken.token === null) {\n throw new Error('EOF reached while parsing entity');\n }\n if (keyToken.token === '}') {\n break;\n }\n\n const valueToken = parseToken(text, index);\n index = valueToken.nextIndex;\n if (valueToken.token === null || valueToken.token === '{' || valueToken.token === '}') {\n throw new Error('Malformed entity key/value pair');\n }\n\n if (!keyToken.token.startsWith('_')) {\n entity[keyToken.token] = valueToken.token;\n }\n }\n\n entities.push(entity);\n }\n\n return entities;\n}\n\nexport interface SpawnContext {\n readonly keyValues: ParsedEntity;\n readonly entities: EntitySystem;\n warn(message: string): void;\n free(entity: Entity): void;\n}\n\nexport type SpawnFunction = (entity: Entity, context: SpawnContext) => void;\n\nexport class SpawnRegistry {\n private readonly registry = new Map<string, SpawnFunction>();\n\n register(classname: string, spawn: SpawnFunction): void {\n this.registry.set(classname, spawn);\n }\n\n get(classname: string): SpawnFunction | undefined {\n return this.registry.get(classname);\n }\n}\n\nfunction defaultWarn(message: string): void {\n void message;\n}\n\nexport interface SpawnOptions {\n readonly registry: SpawnRegistry;\n readonly entities: EntitySystem;\n readonly onWarning?: (message: string) => void;\n}\n\nexport function spawnEntityFromDictionary(dictionary: ParsedEntity, options: SpawnOptions): Entity | null {\n const warn = options.onWarning ?? defaultWarn;\n const classname = dictionary.classname;\n if (!classname) {\n warn('Encountered entity with no classname');\n return null;\n }\n\n const isWorld = classname === 'worldspawn';\n const entity = isWorld ? options.entities.world : options.entities.spawn();\n applyEntityKeyValues(entity, dictionary);\n\n const context: SpawnContext = {\n keyValues: dictionary,\n entities: options.entities,\n warn,\n free(target) {\n options.entities.freeImmediate(target);\n },\n };\n\n const spawnFunc = options.registry.get(classname);\n if (!spawnFunc) {\n warn(`${classname} does not have a spawn function`);\n if (!isWorld) {\n options.entities.freeImmediate(entity);\n }\n return null;\n }\n\n spawnFunc(entity, context);\n\n if (!entity.inUse) {\n return null;\n }\n\n options.entities.finalizeSpawn(entity);\n\n return entity;\n}\n\nexport function spawnEntitiesFromText(text: string, options: SpawnOptions): Entity[] {\n const parsed = parseEntityLump(text);\n const spawned: Entity[] = [];\n\n for (const dictionary of parsed) {\n const entity = spawnEntityFromDictionary(dictionary, options);\n if (entity) {\n spawned.push(entity);\n }\n }\n\n return spawned;\n}\n\nexport function registerDefaultSpawns(registry: SpawnRegistry): void {\n registry.register('worldspawn', (entity) => {\n entity.movetype = MoveType.Push;\n entity.solid = Solid.Bsp;\n entity.modelindex = entity.modelindex || 1;\n });\n\n registry.register('info_player_start', () => {\n // No-op spawn point\n });\n\n registry.register('info_player_deathmatch', () => {\n // Deathmatch handling is deferred until game rules are implemented\n });\n\n registry.register('info_player_coop', () => {\n // Coop spawn points share info_player_start behaviour for now\n });\n\n registry.register('info_null', (entity, context) => {\n context.free(entity);\n });\n\n registry.register('info_notnull', () => {\n // Placeholder positional target\n });\n\n registry.register('info_teleport_destination', () => {\n // Destination marker for trigger_teleport\n });\n\n registerTriggerSpawns(registry);\n}\n\nexport function createDefaultSpawnRegistry(): SpawnRegistry {\n const registry = new SpawnRegistry();\n registerDefaultSpawns(registry);\n return registry;\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 restore(state: LevelFrameState): void {\n this.state = { ...state };\n }\n}\n","export const RANGE_MELEE = 20; // bboxes basically touching\nexport const RANGE_NEAR = 440;\nexport const RANGE_MID = 940;\n\nexport const FL_NOVISIBLE = 1 << 24; // super invisibility\nexport const SPAWNFLAG_MONSTER_AMBUSH = 1 << 0;\n\nexport enum AIFlags {\n Pathing = 1 << 30,\n}\n\nexport enum TraceMask {\n Opaque = 1 << 0,\n Window = 1 << 1,\n}\n","import { angleMod, degToRad, vectorToYaw } from '@quake2ts/shared';\nimport type { Vec3 } from '@quake2ts/shared';\nimport type { Entity } from '../entities/entity.js';\nimport { AIFlags } from './constants.js';\n\ntype MutableVec3 = { x: number; y: number; z: number };\n\nfunction yawVector(yawDegrees: number, distance: number): Vec3 {\n if (distance === 0) {\n return { x: 0, y: 0, z: 0 };\n }\n const radians = degToRad(yawDegrees);\n return {\n x: Math.cos(radians) * distance,\n y: Math.sin(radians) * distance,\n z: 0,\n };\n}\n\n/**\n * Mirror of the rerelease `M_walkmove` helper without collision.\n * Moves the entity along its yaw plane and always reports success.\n */\nexport function walkMove(self: Entity, yawDegrees: number, distance: number): boolean {\n const delta = yawVector(yawDegrees, distance);\n const origin = self.origin as MutableVec3;\n origin.x += delta.x;\n origin.y += delta.y;\n origin.z += delta.z;\n return true;\n}\n\n/**\n * Match the rerelease `M_ChangeYaw` turning speed rules.\n * `yaw_speed` is interpreted the same way as Quake II: degrees per tenth-second.\n */\nexport function changeYaw(self: Entity, deltaSeconds: number): void {\n const current = angleMod(self.angles.y);\n const ideal = self.ideal_yaw;\n\n if (current === ideal) {\n (self.angles as MutableVec3).y = current;\n return;\n }\n\n // The rerelease scales yaw_speed by (10 / tick_rate); using deltaSeconds keeps that\n // behavior across arbitrary fixed-step rates.\n const speed = self.yaw_speed * deltaSeconds * 10;\n\n let move = ideal - current;\n if (ideal > current) {\n if (move >= 180) move -= 360;\n } else if (move <= -180) {\n move += 360;\n }\n\n if (move > speed) move = speed;\n else if (move < -speed) move = -speed;\n\n (self.angles as MutableVec3).y = angleMod(current + move);\n}\n\nexport function facingIdeal(self: Entity): boolean {\n const delta = angleMod(self.angles.y - self.ideal_yaw);\n const hasPathing = (self.monsterinfo.aiflags & AIFlags.Pathing) !== 0;\n\n if (hasPathing) {\n return !(delta > 5 && delta < 355);\n }\n\n return !(delta > 45 && delta < 315);\n}\n\nexport function ai_move(self: Entity, distance: number): void {\n walkMove(self, self.angles.y, distance);\n}\n\nfunction setIdealYawTowards(self: Entity, target: Entity | null): void {\n if (!target) return;\n\n const toTarget: Vec3 = {\n x: target.origin.x - self.origin.x,\n y: target.origin.y - self.origin.y,\n z: target.origin.z - self.origin.z,\n };\n self.ideal_yaw = vectorToYaw(toTarget);\n}\n\nexport function ai_stand(self: Entity, deltaSeconds: number): void {\n changeYaw(self, deltaSeconds);\n}\n\nexport function ai_walk(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.goalentity);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_turn(self: Entity, distance: number, deltaSeconds: number): void {\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n changeYaw(self, deltaSeconds);\n}\n\nexport function ai_run(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.enemy ?? self.goalentity);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_face(\n self: Entity,\n enemy: Entity | null,\n distance: number,\n deltaSeconds: number,\n): void {\n if (enemy) {\n setIdealYawTowards(self, enemy);\n }\n\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n\nexport function ai_charge(self: Entity, distance: number, deltaSeconds: number): void {\n setIdealYawTowards(self, self.enemy);\n changeYaw(self, deltaSeconds);\n\n if (distance !== 0) {\n walkMove(self, self.angles.y, distance);\n }\n}\n","import type { Vec3 } from '@quake2ts/shared';\nimport { angleVectors, dotVec3, normalizeVec3, subtractVec3 } from '@quake2ts/shared';\nimport { distanceBetweenBoxesSquared } from '@quake2ts/shared';\nimport type { Entity } from '../entities/entity.js';\nimport { FL_NOVISIBLE, RANGE_MELEE, RANGE_MID, RANGE_NEAR, SPAWNFLAG_MONSTER_AMBUSH, TraceMask } from './constants.js';\n\nexport enum RangeCategory {\n Melee = 'melee',\n Near = 'near',\n Mid = 'mid',\n Far = 'far',\n}\n\nexport interface TraceResult {\n readonly fraction: number;\n readonly entity: Entity | null;\n}\n\nexport type TraceFunction = (start: Vec3, end: Vec3, ignore: Entity, mask: TraceMask) => TraceResult;\n\nfunction absBounds(entity: Entity): { mins: Vec3; maxs: Vec3 } {\n return {\n mins: {\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 maxs: {\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\nexport function rangeTo(self: Entity, other: Entity): number {\n const a = absBounds(self);\n const b = absBounds(other);\n const distanceSquared = distanceBetweenBoxesSquared(a.mins, a.maxs, b.mins, b.maxs);\n return Math.sqrt(distanceSquared);\n}\n\nexport function classifyRange(distance: number): RangeCategory {\n if (distance <= RANGE_MELEE) {\n return RangeCategory.Melee;\n }\n if (distance <= RANGE_NEAR) {\n return RangeCategory.Near;\n }\n if (distance <= RANGE_MID) {\n return RangeCategory.Mid;\n }\n return RangeCategory.Far;\n}\n\nexport function infront(self: Entity, other: Entity): boolean {\n const { forward } = angleVectors(self.angles);\n const direction = normalizeVec3(subtractVec3(other.origin, self.origin));\n const dot = dotVec3(direction, forward);\n\n if (\n (self.spawnflags & SPAWNFLAG_MONSTER_AMBUSH) !== 0 &&\n self.trail_time === 0 &&\n self.enemy === null\n ) {\n return dot > 0.15;\n }\n\n return dot > -0.3;\n}\n\nexport function visible(\n self: Entity,\n other: Entity,\n trace: TraceFunction,\n options?: { throughGlass?: boolean },\n): boolean {\n if ((other.flags & FL_NOVISIBLE) !== 0) {\n return false;\n }\n\n const start: Vec3 = { x: self.origin.x, y: self.origin.y, z: self.origin.z + self.viewheight };\n const end: Vec3 = { x: other.origin.x, y: other.origin.y, z: other.origin.z + other.viewheight };\n\n const mask = options?.throughGlass ? TraceMask.Opaque : TraceMask.Opaque | TraceMask.Window;\n const result = trace(start, end, self, mask);\n return result.fraction === 1 || result.entity === other;\n}\n","import type { GameStateSnapshot } from './index.js';\n\nconst FNV_OFFSET_BASIS = 0x811c9dc5;\nconst FNV_PRIME = 0x01000193;\n\nfunction hashBytes(hash: number, bytes: ArrayLike<number>): number {\n let h = hash >>> 0;\n for (let i = 0; i < bytes.length; i += 1) {\n h ^= bytes[i]! & 0xff;\n h = Math.imul(h, FNV_PRIME) >>> 0;\n }\n return h >>> 0;\n}\n\nfunction hashNumber(hash: number, value: number): number {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setFloat64(0, value, true);\n const bytes = new Uint8Array(buffer);\n return hashBytes(hash, bytes);\n}\n\nfunction hashString(hash: number, value: string): number {\n const bytes = new Uint8Array(value.length);\n for (let i = 0; i < value.length; i += 1) {\n bytes[i] = value.charCodeAt(i) & 0xff;\n }\n return hashBytes(hash, bytes);\n}\n\nexport function hashGameState(state: GameStateSnapshot): number {\n let hash = FNV_OFFSET_BASIS;\n\n hash = hashNumber(hash, state.gravity.x);\n hash = hashNumber(hash, state.gravity.y);\n hash = hashNumber(hash, state.gravity.z);\n\n hash = hashNumber(hash, state.origin.x);\n hash = hashNumber(hash, state.origin.y);\n hash = hashNumber(hash, state.origin.z);\n\n hash = hashNumber(hash, state.velocity.x);\n hash = hashNumber(hash, state.velocity.y);\n hash = hashNumber(hash, state.velocity.z);\n\n hash = hashNumber(hash, state.level.frameNumber);\n hash = hashNumber(hash, state.level.timeSeconds);\n hash = hashNumber(hash, state.level.previousTimeSeconds);\n hash = hashNumber(hash, state.level.deltaSeconds);\n\n hash = hashNumber(hash, state.entities.activeCount);\n hash = hashString(hash, state.entities.worldClassname);\n\n return hash >>> 0;\n}\n","import type { CvarRegistry } from '@quake2ts/engine';\nimport { CvarFlags, RandomGenerator, type RandomGeneratorState } from '@quake2ts/shared';\nimport type { RandomGenerator as RandomGeneratorType } from '@quake2ts/shared';\nimport type { EntitySystem, EntitySystemSnapshot, SerializedEntityState } from '../entities/index.js';\nimport type { LevelClock, LevelFrameState } from '../level.js';\n\nexport const SAVE_FORMAT_VERSION = 1;\n\nexport interface CvarSaveEntry {\n readonly name: string;\n readonly value: string;\n readonly flags: CvarFlags;\n}\n\nexport interface GameSaveFile {\n readonly version: number;\n readonly timestamp: number;\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly gameState: Record<string, unknown>;\n readonly level: LevelFrameState;\n readonly rng: RandomGeneratorState;\n readonly entities: EntitySystemSnapshot;\n readonly cvars: readonly CvarSaveEntry[];\n readonly configstrings: readonly string[];\n}\n\nexport interface SaveCreationOptions {\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly levelState: LevelFrameState;\n readonly entitySystem: EntitySystem;\n readonly rngState: RandomGeneratorState;\n readonly configstrings?: readonly string[];\n readonly cvars?: CvarRegistry;\n readonly gameState?: Record<string, unknown>;\n readonly timestamp?: number;\n}\n\nexport interface SaveApplyTargets {\n readonly levelClock: LevelClock;\n readonly entitySystem: EntitySystem;\n readonly rng: RandomGeneratorType;\n readonly cvars?: CvarRegistry;\n}\n\nexport interface ParseSaveOptions {\n readonly allowNewerVersion?: boolean;\n}\n\nconst MIN_SUPPORTED_VERSION = 1;\n\nfunction ensureObject(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction ensureNumber(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`${label} must be a finite number`);\n }\n return value;\n}\n\nfunction ensureNumberOrDefault(value: unknown, label: string, defaultValue: number): number {\n if (value === undefined) {\n return defaultValue;\n }\n return ensureNumber(value, label);\n}\n\nfunction ensureString(value: unknown, label: string): string {\n if (typeof value !== 'string') {\n throw new Error(`${label} must be a string`);\n }\n return value;\n}\n\nfunction ensureNumberArray(value: unknown, label: string): readonly number[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n for (const element of value) {\n ensureNumber(element, `${label} element`);\n }\n return value;\n}\n\nfunction parseLevelState(raw: unknown): LevelFrameState {\n if (raw === undefined) {\n return { frameNumber: 0, timeSeconds: 0, previousTimeSeconds: 0, deltaSeconds: 0 };\n }\n\n const level = ensureObject(raw, 'level');\n return {\n frameNumber: ensureNumberOrDefault(level.frameNumber, 'level.frameNumber', 0),\n timeSeconds: ensureNumberOrDefault(level.timeSeconds, 'level.timeSeconds', 0),\n previousTimeSeconds: ensureNumberOrDefault(level.previousTimeSeconds, 'level.previousTimeSeconds', 0),\n deltaSeconds: ensureNumberOrDefault(level.deltaSeconds, 'level.deltaSeconds', 0),\n };\n}\n\nfunction parseRngState(raw: unknown): RandomGeneratorState {\n if (raw === undefined) {\n return new RandomGenerator().getState();\n }\n\n const rng = ensureObject(raw, 'rng');\n const mt = ensureObject(rng.mt, 'rng.mt');\n const state = ensureNumberArray(mt.state, 'rng.mt.state');\n return {\n mt: {\n index: ensureNumber(mt.index, 'rng.mt.index'),\n state,\n },\n };\n}\n\nfunction parseThinkEntries(raw: unknown): EntitySystemSnapshot['thinks'] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('thinks must be an array');\n }\n\n return raw.map((entry, idx) => {\n const think = ensureObject(entry, `thinks[${idx}]`);\n return {\n time: ensureNumber(think.time, `thinks[${idx}].time`),\n entityIndex: ensureNumber(think.entityIndex, `thinks[${idx}].entityIndex`),\n };\n });\n}\n\nfunction parseEntityFields(raw: unknown): SerializedEntityState['fields'] {\n if (raw === undefined) {\n return {};\n }\n\n const fields = ensureObject(raw, 'entity.fields');\n const parsed: SerializedEntityState['fields'] = {};\n for (const [name, value] of Object.entries(fields)) {\n if (value === null) {\n parsed[name as keyof SerializedEntityState['fields']] = null;\n continue;\n }\n\n switch (typeof value) {\n case 'number':\n case 'string':\n case 'boolean':\n parsed[name as keyof SerializedEntityState['fields']] = value;\n break;\n default: {\n if (!Array.isArray(value)) {\n const object = ensureObject(value, name);\n const inventory: Record<string, number> = {};\n for (const [entryName, entryValue] of Object.entries(object)) {\n inventory[entryName] = ensureNumber(entryValue, `${name}.${entryName}`);\n }\n parsed[name as keyof SerializedEntityState['fields']] = inventory;\n break;\n }\n if (Array.isArray(value) && value.length === 3) {\n const [x, y, z] = value;\n parsed[name as keyof SerializedEntityState['fields']] = [\n ensureNumber(x, `${name}[0]`),\n ensureNumber(y, `${name}[1]`),\n ensureNumber(z, `${name}[2]`),\n ];\n break;\n }\n throw new Error(`Unsupported entity field value for ${name}`);\n }\n }\n }\n return parsed;\n}\n\nfunction parseEntities(raw: unknown): SerializedEntityState[] {\n if (!Array.isArray(raw)) {\n throw new Error('entities must be an array');\n }\n\n return raw.map((entry, idx) => {\n const entity = ensureObject(entry, `entities[${idx}]`);\n return {\n index: ensureNumber(entity.index, `entities[${idx}].index`),\n fields: parseEntityFields(entity.fields),\n };\n });\n}\n\nfunction parsePool(raw: unknown): EntitySystemSnapshot['pool'] {\n const pool = ensureObject(raw, 'pool');\n return {\n capacity: ensureNumber(pool.capacity, 'pool.capacity'),\n activeOrder: ensureNumberArray(pool.activeOrder, 'pool.activeOrder'),\n freeList: ensureNumberArray(pool.freeList, 'pool.freeList'),\n pendingFree: ensureNumberArray(pool.pendingFree, 'pool.pendingFree'),\n };\n}\n\nfunction parseEntitySnapshot(raw: unknown): EntitySystemSnapshot {\n const snapshot = ensureObject(raw, 'entities');\n return {\n timeSeconds: ensureNumber(snapshot.timeSeconds, 'entities.timeSeconds'),\n pool: parsePool(snapshot.pool),\n entities: parseEntities(snapshot.entities),\n thinks: parseThinkEntries(snapshot.thinks),\n };\n}\n\nfunction parseCvars(raw: unknown): CvarSaveEntry[] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('cvars must be an array');\n }\n\n return raw.map((entry, idx) => {\n const cvar = ensureObject(entry, `cvars[${idx}]`);\n return {\n name: ensureString(cvar.name, `cvars[${idx}].name`),\n value: ensureString(cvar.value, `cvars[${idx}].value`),\n flags: ensureNumber(cvar.flags, `cvars[${idx}].flags`) as CvarFlags,\n };\n });\n}\n\nfunction parseConfigstrings(raw: unknown): string[] {\n if (raw === undefined) {\n return [];\n }\n\n if (!Array.isArray(raw)) {\n throw new Error('configstrings must be an array');\n }\n\n return raw.map((value, idx) => ensureString(value, `configstrings[${idx}]`));\n}\n\nfunction parseGameState(raw: unknown): Record<string, unknown> {\n if (raw === undefined) {\n return {};\n }\n\n return ensureObject(raw, 'gameState');\n}\n\nfunction serializeCvars(registry: CvarRegistry | undefined): CvarSaveEntry[] {\n if (!registry) {\n return [];\n }\n\n return registry\n .list()\n .filter((cvar) => (cvar.flags & CvarFlags.Archive) !== 0)\n .map((cvar) => ({ name: cvar.name, value: cvar.string, flags: cvar.flags }));\n}\n\nfunction applyCvars(entries: readonly CvarSaveEntry[], registry: CvarRegistry | undefined): void {\n if (!registry) {\n return;\n }\n\n for (const entry of entries) {\n const existing = registry.get(entry.name);\n if (existing) {\n existing.set(entry.value);\n } else {\n registry.register({ name: entry.name, defaultValue: entry.value, flags: entry.flags });\n }\n }\n}\n\nfunction cloneRngState(state: RandomGeneratorState): RandomGeneratorState {\n return {\n mt: {\n index: state.mt.index,\n state: [...state.mt.state],\n },\n };\n}\n\nexport function createSaveFile(options: SaveCreationOptions): GameSaveFile {\n const {\n map,\n difficulty,\n playtimeSeconds,\n levelState,\n entitySystem,\n rngState,\n configstrings = [],\n cvars,\n gameState = {},\n timestamp = Date.now(),\n } = options;\n\n return {\n version: SAVE_FORMAT_VERSION,\n timestamp,\n map,\n difficulty,\n playtimeSeconds,\n gameState: { ...gameState },\n level: { ...levelState },\n rng: cloneRngState(rngState),\n entities: entitySystem.createSnapshot(),\n cvars: serializeCvars(cvars),\n configstrings: [...configstrings],\n };\n}\n\nexport function parseSaveFile(serialized: unknown, options: ParseSaveOptions = {}): GameSaveFile {\n const { allowNewerVersion = true } = options;\n const raw = typeof serialized === 'string' ? JSON.parse(serialized) : serialized;\n const save = ensureObject(raw, 'save');\n\n const versionValue = save.version ?? SAVE_FORMAT_VERSION;\n const version = ensureNumber(versionValue, 'version');\n if (version < MIN_SUPPORTED_VERSION) {\n throw new Error(`Unsupported save version ${version}`);\n }\n if (version > SAVE_FORMAT_VERSION && !allowNewerVersion) {\n throw new Error(`Save version ${version} is newer than supported ${SAVE_FORMAT_VERSION}`);\n }\n\n return {\n version,\n timestamp: ensureNumber(save.timestamp, 'timestamp'),\n map: ensureString(save.map, 'map'),\n difficulty: ensureNumber(save.difficulty, 'difficulty'),\n playtimeSeconds: ensureNumber(save.playtimeSeconds, 'playtimeSeconds'),\n gameState: parseGameState(save.gameState),\n level: parseLevelState(save.level),\n rng: parseRngState(save.rng),\n entities: parseEntitySnapshot(save.entities),\n cvars: parseCvars(save.cvars),\n configstrings: parseConfigstrings(save.configstrings),\n };\n}\n\nexport function applySaveFile(save: GameSaveFile, targets: SaveApplyTargets): void {\n targets.levelClock.restore(save.level);\n targets.entitySystem.restore(save.entities);\n targets.rng.setState(save.rng);\n applyCvars(save.cvars, targets.cvars);\n}\n","export type JsonObject = Record<string, unknown>;\n\nexport interface RereleaseGameSave {\n readonly saveVersion: number;\n readonly game: JsonObject & { readonly maxclients?: number };\n readonly clients: readonly JsonObject[];\n}\n\nexport interface RereleaseLevelSave {\n readonly saveVersion: number;\n readonly level: JsonObject;\n readonly entities: ReadonlyMap<number, JsonObject>;\n}\n\nexport type RereleaseSave = RereleaseGameSave | RereleaseLevelSave;\n\nexport interface RereleaseSaveSummary {\n readonly version: number;\n readonly kind: 'game' | 'level';\n readonly maxClients?: number;\n readonly clientCount?: number;\n readonly entityCount?: number;\n readonly highestEntityIndex?: number;\n}\n\nfunction ensureObject(value: unknown, label: string): JsonObject {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`);\n }\n return value as JsonObject;\n}\n\nfunction ensureNumber(value: unknown, label: string): number {\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n throw new Error(`${label} must be a finite number`);\n }\n return value;\n}\n\nfunction ensureArray(value: unknown, label: string): readonly unknown[] {\n if (!Array.isArray(value)) {\n throw new Error(`${label} must be an array`);\n }\n return value;\n}\n\nfunction parseEntityMap(raw: JsonObject): ReadonlyMap<number, JsonObject> {\n const map = new Map<number, JsonObject>();\n for (const [rawIndex, value] of Object.entries(raw)) {\n const index = Number(rawIndex);\n if (!Number.isInteger(index)) {\n throw new Error(`entities[${rawIndex}] must use an integer key`);\n }\n map.set(index, ensureObject(value, `entities[${rawIndex}]`));\n }\n return map;\n}\n\nexport function parseRereleaseSave(raw: unknown): RereleaseSave {\n const root = ensureObject(raw, 'rerelease save');\n const saveVersion = ensureNumber(root.save_version, 'save_version');\n const hasGame = 'game' in root;\n const hasLevel = 'level' in root;\n\n if (hasGame === hasLevel) {\n throw new Error('save must contain either game or level data');\n }\n\n if (hasGame) {\n const game = ensureObject((root as Record<string, unknown>).game, 'game');\n const clients = ensureArray((root as Record<string, unknown>).clients, 'clients').map((entry, idx) =>\n ensureObject(entry, `clients[${idx}]`),\n );\n const maxclients = game.maxclients !== undefined ? ensureNumber(game.maxclients, 'game.maxclients') : clients.length;\n if (clients.length !== maxclients) {\n throw new Error(`clients length ${clients.length} does not match game.maxclients ${maxclients}`);\n }\n return { saveVersion, game, clients };\n }\n\n const level = ensureObject((root as Record<string, unknown>).level, 'level');\n const entitiesRoot = ensureObject((root as Record<string, unknown>).entities, 'entities');\n const entities = parseEntityMap(entitiesRoot);\n return { saveVersion, level, entities };\n}\n\nexport function summarizeRereleaseSave(raw: unknown): RereleaseSaveSummary {\n const parsed = parseRereleaseSave(raw);\n if ('game' in parsed) {\n const maxClients = parsed.game.maxclients ?? parsed.clients.length;\n return {\n version: parsed.saveVersion,\n kind: 'game',\n maxClients,\n clientCount: parsed.clients.length,\n };\n }\n\n let highestEntityIndex = -1;\n for (const index of parsed.entities.keys()) {\n if (index > highestEntityIndex) {\n highestEntityIndex = index;\n }\n }\n\n return {\n version: parsed.saveVersion,\n kind: 'level',\n entityCount: parsed.entities.size,\n highestEntityIndex: highestEntityIndex >= 0 ? highestEntityIndex : undefined,\n };\n}\n","import { parseSaveFile, type GameSaveFile, type ParseSaveOptions } from './save.js';\n\nexport interface SaveSlotMetadata {\n readonly id: string;\n readonly name: string;\n readonly map: string;\n readonly difficulty: number;\n readonly playtimeSeconds: number;\n readonly timestamp: number;\n readonly version: number;\n readonly bytes: number;\n}\n\ninterface SaveRecord {\n readonly id: string;\n readonly metadata: SaveSlotMetadata;\n readonly save: GameSaveFile;\n}\n\ninterface SaveStorageAdapter {\n init(): Promise<void>;\n put(record: SaveRecord): Promise<void>;\n get(id: string): Promise<SaveRecord | null>;\n delete(id: string): Promise<boolean>;\n list(): Promise<SaveRecord[]>;\n}\n\ntype TextEncoderLike = { encode(input?: string): Uint8Array };\ntype TextEncoderCtor = new () => TextEncoderLike;\nconst TEXT_ENCODER_CTOR: TextEncoderCtor | undefined =\n (globalThis as Record<string, unknown>).TextEncoder as TextEncoderCtor | undefined;\n\nfunction cloneSave(save: GameSaveFile): GameSaveFile {\n return parseSaveFile({ ...save }, { allowNewerVersion: true });\n}\n\nfunction estimateSizeBytes(save: GameSaveFile): number {\n if (TEXT_ENCODER_CTOR) {\n const encoder = new TEXT_ENCODER_CTOR();\n return encoder.encode(JSON.stringify(save)).length;\n }\n return JSON.stringify(save).length;\n}\n\nclass MemorySaveAdapter implements SaveStorageAdapter {\n private readonly records = new Map<string, SaveRecord>();\n\n async init(): Promise<void> {\n return Promise.resolve();\n }\n\n async put(record: SaveRecord): Promise<void> {\n const copy: SaveRecord = {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n this.records.set(record.id, copy);\n }\n\n async get(id: string): Promise<SaveRecord | null> {\n const record = this.records.get(id);\n if (!record) {\n return null;\n }\n return {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n }\n\n async delete(id: string): Promise<boolean> {\n return this.records.delete(id);\n }\n\n async list(): Promise<SaveRecord[]> {\n return Array.from(this.records.values()).map((record) => ({\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n }));\n }\n}\n\ntype IndexedDbFactory = { open(name: string, version?: number): unknown };\n\nclass IndexedDbSaveAdapter implements SaveStorageAdapter {\n private db: unknown = null;\n\n constructor(\n private readonly indexedDB: IndexedDbFactory,\n private readonly dbName: string,\n private readonly storeName: string,\n ) {}\n\n async init(): Promise<void> {\n if (this.db) {\n return;\n }\n\n this.db = await new Promise<unknown>((resolve, reject) => {\n const request = this.indexedDB.open(this.dbName, 1) as any;\n request.onupgradeneeded = () => {\n request.result.createObjectStore(this.storeName, { keyPath: 'id' });\n };\n request.onerror = () => reject(request.error ?? new Error('Failed to open IndexedDB'));\n request.onsuccess = () => resolve(request.result);\n });\n }\n\n private async runTransaction<T>(mode: 'readonly' | 'readwrite', operation: (store: any) => any): Promise<T> {\n await this.init();\n const database = this.db as any;\n return new Promise<T>((resolve, reject) => {\n const transaction = database.transaction(this.storeName, mode);\n const store = transaction.objectStore(this.storeName);\n const request = operation(store);\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));\n });\n }\n\n async put(record: SaveRecord): Promise<void> {\n await this.runTransaction('readwrite', (store) => store.put(record));\n }\n\n async get(id: string): Promise<SaveRecord | null> {\n const record = await this.runTransaction<SaveRecord | null>('readonly', (store) => store.get(id));\n if (!record) {\n return null;\n }\n return {\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n };\n }\n\n async delete(id: string): Promise<boolean> {\n const existing = await this.get(id);\n if (!existing) {\n return false;\n }\n await this.runTransaction('readwrite', (store) => store.delete(id));\n return true;\n }\n\n async list(): Promise<SaveRecord[]> {\n const all = await this.runTransaction<SaveRecord[]>('readonly', (store) => store.getAll());\n return all.map((record) => ({\n id: record.id,\n metadata: { ...record.metadata },\n save: cloneSave(record.save),\n }));\n }\n}\n\nexport interface SaveStorageOptions {\n readonly dbName?: string;\n readonly storeName?: string;\n readonly indexedDB?: IndexedDbFactory | null;\n}\n\nexport interface SaveWriteOptions {\n readonly name?: string;\n}\n\nexport class SaveStorage {\n private static readonly DEFAULT_DB_NAME = 'quake2ts-saves';\n private static readonly DEFAULT_STORE = 'saves';\n private static readonly QUICK_SLOT = 'quicksave';\n\n private readonly adapter: SaveStorageAdapter;\n\n constructor(options: SaveStorageOptions = {}) {\n const { dbName = SaveStorage.DEFAULT_DB_NAME, storeName = SaveStorage.DEFAULT_STORE } = options;\n const indexedDBFactory =\n options.indexedDB ?? ((globalThis as Record<string, unknown>).indexedDB as IndexedDbFactory | undefined);\n if (indexedDBFactory) {\n this.adapter = new IndexedDbSaveAdapter(indexedDBFactory, dbName, storeName);\n } else {\n this.adapter = new MemorySaveAdapter();\n }\n }\n\n async save(slotId: string, save: GameSaveFile, options: SaveWriteOptions = {}): Promise<SaveSlotMetadata> {\n const normalized = cloneSave(save);\n const metadata: SaveSlotMetadata = {\n id: slotId,\n name: options.name ?? slotId,\n map: normalized.map,\n difficulty: normalized.difficulty,\n playtimeSeconds: normalized.playtimeSeconds,\n timestamp: normalized.timestamp,\n version: normalized.version,\n bytes: estimateSizeBytes(normalized),\n };\n\n await this.adapter.init();\n await this.adapter.put({ id: slotId, metadata, save: normalized });\n return metadata;\n }\n\n async load(slotId: string, options: ParseSaveOptions = {}): Promise<GameSaveFile> {\n await this.adapter.init();\n const record = await this.adapter.get(slotId);\n if (!record) {\n throw new Error(`Save slot ${slotId} not found`);\n }\n return parseSaveFile(record.save, options);\n }\n\n async delete(slotId: string): Promise<boolean> {\n await this.adapter.init();\n return this.adapter.delete(slotId);\n }\n\n async list(): Promise<SaveSlotMetadata[]> {\n await this.adapter.init();\n const records = await this.adapter.list();\n return records\n .map((record) => ({ ...record.metadata }))\n .sort((a, b) => b.timestamp - a.timestamp || a.id.localeCompare(b.id));\n }\n\n async quickSave(save: GameSaveFile): Promise<SaveSlotMetadata> {\n return this.save(SaveStorage.QUICK_SLOT, save, { name: 'Quick Save' });\n }\n\n async quickLoad(options: ParseSaveOptions = {}): Promise<GameSaveFile> {\n return this.load(SaveStorage.QUICK_SLOT, options);\n }\n}\n","export enum DamageFlags {\n NONE = 0,\n RADIUS = 0x00000001,\n NO_ARMOR = 0x00000002,\n ENERGY = 0x00000004,\n NO_KNOCKBACK = 0x00000008,\n BULLET = 0x00000010,\n NO_PROTECTION = 0x00000020,\n DESTROY_ARMOR = 0x00000040,\n NO_REG_ARMOR = 0x00000080,\n NO_POWER_ARMOR = 0x00000100,\n NO_INDICATOR = 0x00000200,\n}\n\nexport function hasAnyDamageFlag(flags: number, mask: DamageFlags): boolean {\n return (flags & mask) !== 0;\n}\n","import { angleVectors, type Vec3 } from '@quake2ts/shared';\nimport { DamageFlags, hasAnyDamageFlag } from './damageFlags.js';\n\nexport enum ArmorType {\n BODY = 'body',\n COMBAT = 'combat',\n JACKET = 'jacket',\n}\n\nexport interface ArmorInfo {\n readonly baseCount: number;\n readonly maxCount: number;\n readonly normalProtection: number;\n readonly energyProtection: number;\n}\n\nexport const ARMOR_INFO: Record<ArmorType, ArmorInfo> = {\n [ArmorType.JACKET]: {\n baseCount: 25,\n maxCount: 50,\n normalProtection: 0.3,\n energyProtection: 0,\n },\n [ArmorType.COMBAT]: {\n baseCount: 50,\n maxCount: 100,\n normalProtection: 0.6,\n energyProtection: 0.3,\n },\n [ArmorType.BODY]: {\n baseCount: 100,\n maxCount: 200,\n normalProtection: 0.8,\n energyProtection: 0.6,\n },\n};\n\nexport interface RegularArmorState {\n readonly armorType: ArmorType | null;\n armorCount: number;\n}\n\nexport interface RegularArmorResult {\n readonly saved: number;\n readonly remainingArmor: number;\n}\n\nexport function applyRegularArmor(\n damage: number,\n flags: number,\n state: RegularArmorState,\n): RegularArmorResult {\n if (\n damage <= 0 ||\n hasAnyDamageFlag(flags, DamageFlags.NO_ARMOR | DamageFlags.NO_REG_ARMOR) ||\n !state.armorType ||\n state.armorCount <= 0\n ) {\n return { saved: 0, remainingArmor: state.armorCount };\n }\n\n const info = ARMOR_INFO[state.armorType];\n const protection = hasAnyDamageFlag(flags, DamageFlags.ENERGY)\n ? info.energyProtection\n : info.normalProtection;\n\n let saved = Math.ceil(protection * damage);\n if (saved >= state.armorCount) {\n saved = state.armorCount;\n }\n\n if (saved <= 0) {\n return { saved: 0, remainingArmor: state.armorCount };\n }\n\n return { saved, remainingArmor: state.armorCount - saved };\n}\n\nexport type PowerArmorType = 'screen' | 'shield';\n\nexport interface PowerArmorState {\n readonly type: PowerArmorType | null;\n cellCount: number;\n readonly angles: Vec3;\n readonly origin: Vec3;\n readonly health: number;\n}\n\nexport interface PowerArmorOptions {\n readonly ctfMode?: boolean;\n}\n\nexport interface PowerArmorResult {\n readonly saved: number;\n readonly remainingCells: number;\n}\n\nexport function applyPowerArmor(\n damage: number,\n flags: number,\n hitPoint: Vec3,\n _hitNormal: Vec3,\n state: PowerArmorState,\n options: PowerArmorOptions = {},\n): PowerArmorResult {\n if (state.health <= 0 || damage <= 0) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n if (hasAnyDamageFlag(flags, DamageFlags.NO_ARMOR | DamageFlags.NO_POWER_ARMOR)) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n if (!state.type || state.cellCount <= 0) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n\n const { forward } = angleVectors(state.angles);\n const toImpact = {\n x: hitPoint.x - state.origin.x,\n y: hitPoint.y - state.origin.y,\n z: hitPoint.z - state.origin.z,\n };\n const toImpactLength = Math.hypot(toImpact.x, toImpact.y, toImpact.z);\n\n if (state.type === 'screen' && toImpactLength > 0) {\n const dir = {\n x: toImpact.x / toImpactLength,\n y: toImpact.y / toImpactLength,\n z: toImpact.z / toImpactLength,\n };\n const dot = dir.x * forward.x + dir.y * forward.y + dir.z * forward.z;\n if (dot <= 0.3) {\n return { saved: 0, remainingCells: state.cellCount };\n }\n }\n\n const ctfMode = options.ctfMode ?? false;\n const damagePerCell = state.type === 'screen' ? 1 : ctfMode ? 1 : 2;\n let adjustedDamage = state.type === 'screen' ? damage / 3 : (2 * damage) / 3;\n adjustedDamage = Math.max(1, adjustedDamage);\n\n let saved = state.cellCount * damagePerCell;\n if (hasAnyDamageFlag(flags, DamageFlags.ENERGY)) {\n saved = Math.max(1, Math.floor(saved / 2));\n }\n\n if (saved > adjustedDamage) {\n saved = Math.floor(adjustedDamage);\n }\n\n let powerUsed = saved / damagePerCell;\n if (hasAnyDamageFlag(flags, DamageFlags.ENERGY)) {\n powerUsed *= 2;\n }\n powerUsed = Math.max(1, Math.floor(powerUsed));\n\n const cellsSpent = Math.max(damagePerCell, powerUsed);\n const remainingCells = Math.max(0, state.cellCount - cellsSpent);\n\n return { saved, remainingCells };\n}\n","import { addVec3, closestPointToBox, lengthVec3, normalizeVec3, scaleVec3, subtractVec3, type Vec3 } from '@quake2ts/shared';\nimport { applyPowerArmor, applyRegularArmor, type PowerArmorState, type RegularArmorState } from './armor.js';\nimport { DamageFlags, hasAnyDamageFlag } from './damageFlags.js';\nimport { DamageMod } from './damageMods.js';\n\nexport interface DamageableCallbacks {\n pain?: (self: Damageable, attacker: Damageable | null, knockback: number, take: number, mod: DamageMod) => void;\n die?: (self: Damageable, inflictor: Damageable | null, attacker: Damageable | null, take: number, point: Vec3, mod: DamageMod) => void;\n}\n\nexport interface Damageable extends DamageableCallbacks {\n readonly id?: string;\n takedamage: boolean;\n health: number;\n readonly maxHealth?: number;\n readonly mass?: number;\n velocity: Vec3;\n readonly origin: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly flags?: EntityDamageFlags;\n readonly regularArmor?: RegularArmorState;\n readonly powerArmor?: PowerArmorState;\n}\n\nexport enum EntityDamageFlags {\n GODMODE = 1 << 0,\n IMMORTAL = 1 << 1,\n NO_KNOCKBACK = 1 << 2,\n NO_DAMAGE_EFFECTS = 1 << 3,\n}\n\nexport interface DamageApplicationResult {\n readonly take: number;\n readonly psave: number;\n readonly asave: number;\n readonly knocked: Vec3;\n readonly killed: boolean;\n readonly remainingArmor?: number;\n readonly remainingCells?: number;\n}\n\nexport interface DamageSource {\n readonly origin: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface RadiusDamageHit {\n readonly target: Damageable;\n readonly result: DamageApplicationResult | null;\n readonly appliedDamage: number;\n}\n\nexport interface RadiusDamageOptions {\n readonly canDamage?: (ent: Damageable, inflictor: DamageSource) => boolean;\n}\n\nfunction applyKnockback(\n targ: Damageable,\n attacker: Damageable | null,\n dir: Vec3,\n knockback: number,\n dflags: number,\n): Vec3 {\n const hasNoKnockback =\n hasAnyDamageFlag(dflags, DamageFlags.NO_KNOCKBACK) || ((targ.flags ?? 0) & EntityDamageFlags.NO_KNOCKBACK) !== 0;\n if (hasNoKnockback || knockback === 0) {\n return { x: 0, y: 0, z: 0 };\n }\n\n const mass = Math.max(50, targ.mass ?? 200);\n const normalized = normalizeVec3(dir);\n const scale = attacker === targ ? 1600 : 500;\n const delta = scaleVec3(normalized, (scale * knockback) / mass);\n targ.velocity = addVec3(targ.velocity, delta);\n return delta;\n}\n\nfunction applyProtection(\n targ: Damageable,\n point: Vec3,\n normal: Vec3,\n damage: number,\n dflags: number,\n): [number, number, number, number?, number?] {\n let take = damage;\n let psave = 0;\n let asave = 0;\n let remainingCells: number | undefined;\n let remainingArmor: number | undefined;\n\n if (targ.powerArmor) {\n const result = applyPowerArmor(damage, dflags, point, normal, targ.powerArmor);\n psave = result.saved;\n remainingCells = result.remainingCells;\n take -= psave;\n }\n\n if (targ.regularArmor) {\n const result = applyRegularArmor(take, dflags, targ.regularArmor);\n asave = result.saved;\n remainingArmor = result.remainingArmor;\n take -= asave;\n }\n\n return [Math.max(0, take), psave, asave, remainingCells, remainingArmor];\n}\n\nfunction targetCenter(ent: DamageSource | Damageable): Vec3 {\n if (ent.mins && ent.maxs) {\n return {\n x: ent.origin.x + (ent.mins.x + ent.maxs.x) * 0.5,\n y: ent.origin.y + (ent.mins.y + ent.maxs.y) * 0.5,\n z: ent.origin.z + (ent.mins.z + ent.maxs.z) * 0.5,\n };\n }\n return ent.origin;\n}\n\nexport function T_Damage(\n targ: Damageable,\n inflictor: Damageable | null,\n attacker: Damageable | null,\n dir: Vec3,\n point: Vec3,\n normal: Vec3,\n damage: number,\n knockback: number,\n dflags: number,\n mod: DamageMod,\n): DamageApplicationResult | null {\n if (!targ.takedamage || damage <= 0) {\n return null;\n }\n\n const protectedByGod =\n !hasAnyDamageFlag(dflags, DamageFlags.NO_PROTECTION) && ((targ.flags ?? 0) & EntityDamageFlags.GODMODE) !== 0;\n\n if (protectedByGod) {\n return {\n take: 0,\n psave: 0,\n asave: damage,\n knocked: { x: 0, y: 0, z: 0 },\n killed: false,\n };\n }\n\n const knocked = applyKnockback(targ, attacker, dir, knockback, dflags);\n const [take, psave, asave, remainingCells, remainingArmor] = applyProtection(targ, point, normal, damage, dflags);\n\n if (targ.powerArmor && remainingCells !== undefined) {\n (targ.powerArmor as PowerArmorState).cellCount = remainingCells;\n }\n if (targ.regularArmor) {\n (targ.regularArmor as RegularArmorState).armorCount = remainingArmor ?? targ.regularArmor.armorCount;\n }\n\n let actualTake = take;\n\n if (actualTake > 0) {\n targ.health -= actualTake;\n }\n\n const killed = targ.health <= 0;\n if (killed) {\n if (targ.flags && (targ.flags & EntityDamageFlags.IMMORTAL)) {\n targ.health = Math.max(1, targ.health);\n } else if (targ.die) {\n targ.die(targ, inflictor, attacker, actualTake, point, mod);\n }\n } else if (actualTake > 0 && targ.pain) {\n targ.pain(targ, attacker, knockback, actualTake, mod);\n }\n\n return { take: actualTake, psave, asave, knocked, killed, remainingCells, remainingArmor };\n}\n\nexport function T_RadiusDamage(\n entities: readonly Damageable[],\n inflictor: DamageSource,\n attacker: Damageable | null,\n damage: number,\n ignore: Damageable | null,\n radius: number,\n dflags: number,\n mod: DamageMod,\n options: RadiusDamageOptions = {},\n): RadiusDamageHit[] {\n const hits: RadiusDamageHit[] = [];\n const inflictorCenter = targetCenter(inflictor);\n const canDamage = options.canDamage ?? (() => true);\n\n for (const ent of entities) {\n if (ent === ignore || !ent.takedamage || !canDamage(ent, inflictor)) {\n continue;\n }\n\n const entCenter = ent.mins && ent.maxs\n ? closestPointToBox(inflictorCenter, addVec3(ent.origin, ent.mins), addVec3(ent.origin, ent.maxs))\n : targetCenter(ent);\n const toTarget = subtractVec3(inflictorCenter, entCenter);\n const distance = lengthVec3(toTarget);\n if (radius > 0 && distance > radius) {\n continue;\n }\n\n const points = damage - 0.5 * distance;\n if (points <= 0) {\n continue;\n }\n\n const adjustedDamage = ent === attacker ? points * 0.5 : points;\n const dir = normalizeVec3(subtractVec3(ent.origin, inflictorCenter));\n const result = T_Damage(ent, inflictor as Damageable | null, attacker, dir, entCenter, dir, adjustedDamage, adjustedDamage, dflags | DamageFlags.RADIUS, mod);\n hits.push({ target: ent, result, appliedDamage: adjustedDamage });\n }\n\n return hits;\n}\n","/**\n * Means-of-death identifiers mirrored from the Quake II rerelease `mod_id_t`\n * enumeration in `g_local.h`. The numeric ordering is significant for\n * obituary strings and damage filtering, so we retain the exact sequence from\n * the C++ sources.\n */\nexport enum DamageMod {\n UNKNOWN = 0,\n BLASTER = 1,\n SHOTGUN = 2,\n SSHOTGUN = 3,\n MACHINEGUN = 4,\n CHAINGUN = 5,\n GRENADE = 6,\n G_SPLASH = 7,\n ROCKET = 8,\n R_SPLASH = 9,\n HYPERBLASTER = 10,\n RAILGUN = 11,\n BFG_LASER = 12,\n BFG_BLAST = 13,\n BFG_EFFECT = 14,\n HANDGRENADE = 15,\n HG_SPLASH = 16,\n WATER = 17,\n SLIME = 18,\n LAVA = 19,\n CRUSH = 20,\n TELEFRAG = 21,\n TELEFRAG_SPAWN = 22,\n FALLING = 23,\n SUICIDE = 24,\n HELD_GRENADE = 25,\n EXPLOSIVE = 26,\n BARREL = 27,\n BOMB = 28,\n EXIT = 29,\n SPLASH = 30,\n TARGET_LASER = 31,\n TRIGGER_HURT = 32,\n HIT = 33,\n TARGET_BLASTER = 34,\n RIPPER = 35,\n PHALANX = 36,\n BRAINTENTACLE = 37,\n BLASTOFF = 38,\n GEKK = 39,\n TRAP = 40,\n CHAINFIST = 41,\n DISINTEGRATOR = 42,\n ETF_RIFLE = 43,\n BLASTER2 = 44,\n HEATBEAM = 45,\n TESLA = 46,\n PROX = 47,\n NUKE = 48,\n VENGEANCE_SPHERE = 49,\n HUNTER_SPHERE = 50,\n DEFENDER_SPHERE = 51,\n TRACKER = 52,\n DBALL_CRUSH = 53,\n DOPPLE_EXPLODE = 54,\n DOPPLE_VENGEANCE = 55,\n DOPPLE_HUNTER = 56,\n GRAPPLE = 57,\n BLUEBLASTER = 58,\n}\n\n/**\n * Ordered list of the MOD_* identifiers. Tests use this to verify we stay in\n * lockstep with the rerelease values and to drive lookup helpers that need a\n * stable iteration order.\n */\nexport const ORDERED_DAMAGE_MODS: readonly DamageMod[] = [\n DamageMod.UNKNOWN,\n DamageMod.BLASTER,\n DamageMod.SHOTGUN,\n DamageMod.SSHOTGUN,\n DamageMod.MACHINEGUN,\n DamageMod.CHAINGUN,\n DamageMod.GRENADE,\n DamageMod.G_SPLASH,\n DamageMod.ROCKET,\n DamageMod.R_SPLASH,\n DamageMod.HYPERBLASTER,\n DamageMod.RAILGUN,\n DamageMod.BFG_LASER,\n DamageMod.BFG_BLAST,\n DamageMod.BFG_EFFECT,\n DamageMod.HANDGRENADE,\n DamageMod.HG_SPLASH,\n DamageMod.WATER,\n DamageMod.SLIME,\n DamageMod.LAVA,\n DamageMod.CRUSH,\n DamageMod.TELEFRAG,\n DamageMod.TELEFRAG_SPAWN,\n DamageMod.FALLING,\n DamageMod.SUICIDE,\n DamageMod.HELD_GRENADE,\n DamageMod.EXPLOSIVE,\n DamageMod.BARREL,\n DamageMod.BOMB,\n DamageMod.EXIT,\n DamageMod.SPLASH,\n DamageMod.TARGET_LASER,\n DamageMod.TRIGGER_HURT,\n DamageMod.HIT,\n DamageMod.TARGET_BLASTER,\n DamageMod.RIPPER,\n DamageMod.PHALANX,\n DamageMod.BRAINTENTACLE,\n DamageMod.BLASTOFF,\n DamageMod.GEKK,\n DamageMod.TRAP,\n DamageMod.CHAINFIST,\n DamageMod.DISINTEGRATOR,\n DamageMod.ETF_RIFLE,\n DamageMod.BLASTER2,\n DamageMod.HEATBEAM,\n DamageMod.TESLA,\n DamageMod.PROX,\n DamageMod.NUKE,\n DamageMod.VENGEANCE_SPHERE,\n DamageMod.HUNTER_SPHERE,\n DamageMod.DEFENDER_SPHERE,\n DamageMod.TRACKER,\n DamageMod.DBALL_CRUSH,\n DamageMod.DOPPLE_EXPLODE,\n DamageMod.DOPPLE_VENGEANCE,\n DamageMod.DOPPLE_HUNTER,\n DamageMod.GRAPPLE,\n DamageMod.BLUEBLASTER,\n];\n\n/**\n * Returns the stable string name (e.g. `MOD_RAILGUN`) used by the rerelease\n * for obituary strings and logging.\n */\nexport function damageModName(mod: DamageMod): string {\n return `MOD_${DamageMod[mod]}`;\n}\n","import {\n CONTENTS_LAVA,\n CONTENTS_SLIME,\n WaterLevel,\n addVec3,\n boxesIntersect,\n type Bounds3,\n type Vec3,\n} from '@quake2ts/shared';\n\nimport { DamageFlags } from './damageFlags.js';\nimport { DamageMod } from './damageMods.js';\nimport { T_Damage, type Damageable, type DamageApplicationResult } from './damage.js';\nimport { MoveType, Solid } from '../entities/entity.js';\n\nconst ZERO: Vec3 = { x: 0, y: 0, z: 0 };\n\nexport enum EnvironmentalFlags {\n IN_WATER = 1 << 0,\n IMMUNE_LAVA = 1 << 1,\n IMMUNE_SLIME = 1 << 2,\n}\n\nexport interface EnvironmentalDamageTarget extends Damageable {\n waterlevel: WaterLevel;\n watertype: number;\n airFinished: number;\n painDebounceTime: number;\n damageDebounceTime: number;\n environmentFlags?: EnvironmentalFlags;\n}\n\nexport interface EnvironmentalDamageEvent {\n readonly mod: DamageMod;\n readonly amount: number;\n readonly result: DamageApplicationResult | null;\n}\n\nexport interface EnvironmentalDamageResult {\n readonly events: EnvironmentalDamageEvent[];\n readonly enteredWater: boolean;\n readonly leftWater: boolean;\n}\n\nfunction applyDamageEvent(\n target: EnvironmentalDamageTarget,\n amount: number,\n mod: DamageMod,\n): DamageApplicationResult | null {\n return T_Damage(target, null, null, ZERO, target.origin, ZERO, amount, 0, DamageFlags.NO_ARMOR, mod);\n}\n\nexport function applyEnvironmentalDamage(\n target: EnvironmentalDamageTarget,\n nowMs: number,\n): EnvironmentalDamageResult {\n const events: EnvironmentalDamageEvent[] = [];\n let flags = target.environmentFlags ?? 0;\n let enteredWater = false;\n let leftWater = false;\n\n if (target.waterlevel === WaterLevel.None) {\n if ((flags & EnvironmentalFlags.IN_WATER) !== 0) {\n flags &= ~EnvironmentalFlags.IN_WATER;\n leftWater = true;\n }\n\n if (target.airFinished < nowMs && target.painDebounceTime <= nowMs) {\n const elapsedSeconds = Math.floor((nowMs - target.airFinished) / 1000);\n const amount = Math.min(15, 2 + 2 * elapsedSeconds);\n const result = applyDamageEvent(target, amount, DamageMod.WATER);\n target.painDebounceTime = nowMs + 1000;\n events.push({ mod: DamageMod.WATER, amount, result });\n }\n } else {\n target.airFinished = nowMs + 9000;\n if ((flags & EnvironmentalFlags.IN_WATER) === 0) {\n flags |= EnvironmentalFlags.IN_WATER;\n enteredWater = true;\n target.damageDebounceTime = 0;\n }\n\n if (target.damageDebounceTime <= nowMs) {\n if ((target.watertype & CONTENTS_LAVA) !== 0 && (flags & EnvironmentalFlags.IMMUNE_LAVA) === 0) {\n const amount = 10 * target.waterlevel;\n const result = applyDamageEvent(target, amount, DamageMod.LAVA);\n target.damageDebounceTime = nowMs + 100;\n events.push({ mod: DamageMod.LAVA, amount, result });\n } else if ((target.watertype & CONTENTS_SLIME) !== 0 && (flags & EnvironmentalFlags.IMMUNE_SLIME) === 0) {\n const amount = 4 * target.waterlevel;\n const result = applyDamageEvent(target, amount, DamageMod.SLIME);\n target.damageDebounceTime = nowMs + 100;\n events.push({ mod: DamageMod.SLIME, amount, result });\n }\n }\n }\n\n target.environmentFlags = flags;\n\n return { events, enteredWater, leftWater };\n}\n\nexport type FallingEvent = 'footstep' | 'fallshort' | 'fall' | 'fallfar' | null;\n\nexport interface FallingDamageContext {\n readonly impactDelta: number;\n readonly waterLevel: WaterLevel;\n readonly onLadder?: boolean;\n readonly isDead?: boolean;\n readonly isPlayerModel?: boolean;\n readonly isNoClip?: boolean;\n readonly grappleBlockingFallDamage?: boolean;\n readonly clampFreeFall?: boolean;\n readonly skipDamage?: boolean;\n}\n\nexport interface FallingDamageResult {\n readonly damage: number;\n readonly event: FallingEvent;\n readonly fallValue: number;\n readonly adjustedDelta: number;\n}\n\nexport function calculateFallingDamage(context: FallingDamageContext): FallingDamageResult {\n const {\n impactDelta,\n waterLevel,\n onLadder = false,\n isDead = false,\n isPlayerModel = true,\n isNoClip = false,\n grappleBlockingFallDamage = false,\n clampFreeFall = false,\n skipDamage = false,\n } = context;\n\n if (isDead || !isPlayerModel || isNoClip || grappleBlockingFallDamage || waterLevel === WaterLevel.Under) {\n return { damage: 0, event: null, fallValue: 0, adjustedDelta: 0 };\n }\n\n let delta = impactDelta * impactDelta * 0.0001;\n\n if (waterLevel === WaterLevel.Waist) {\n delta *= 0.25;\n } else if (waterLevel === WaterLevel.Feet) {\n delta *= 0.5;\n }\n\n if (clampFreeFall) {\n delta = Math.min(30, delta);\n }\n\n if (delta < 1) {\n return { damage: 0, event: null, fallValue: 0, adjustedDelta: delta };\n }\n\n let event: FallingEvent = null;\n let damage = 0;\n let fallValue = 0;\n\n if (delta < 15) {\n event = onLadder ? null : 'footstep';\n } else {\n fallValue = Math.min(delta * 0.5, 40);\n\n if (delta > 30) {\n event = delta >= 55 ? 'fallfar' : 'fall';\n damage = Math.max(1, (delta - 30) * 0.5);\n } else {\n event = 'fallshort';\n }\n }\n\n if (skipDamage) {\n damage = 0;\n }\n\n return { damage, event, fallValue, adjustedDelta: delta };\n}\n\nexport function applyFallingDamage(\n target: Damageable,\n context: FallingDamageContext,\n): FallingDamageResult {\n const result = calculateFallingDamage(context);\n\n if (result.damage > 0 && !context.skipDamage) {\n T_Damage(\n target,\n null,\n null,\n { x: 0, y: 0, z: 1 },\n target.origin,\n ZERO,\n result.damage,\n 0,\n DamageFlags.NO_ARMOR,\n DamageMod.FALLING,\n );\n }\n\n return result;\n}\n\nexport interface CrushableTarget extends Damageable {\n readonly isMonster?: boolean;\n readonly isClient?: boolean;\n}\n\nexport interface CrushDamageOptions {\n readonly baseDamage?: number;\n readonly nonLivingDamage?: number;\n readonly gibDamage?: number;\n}\n\nexport interface CrushDamageResult {\n readonly amount: number;\n readonly result: DamageApplicationResult | null;\n}\n\nexport function applyCrushDamage(\n crusher: Damageable,\n target: CrushableTarget,\n options: CrushDamageOptions = {},\n): CrushDamageResult {\n const nonLivingDamage = options.nonLivingDamage ?? 100_000;\n const gibDamage = options.gibDamage ?? 100;\n const baseDamage = options.baseDamage ?? (crusher as any).dmg ?? 10;\n\n const amount = !target.isMonster && !target.isClient ? nonLivingDamage : target.health < 1 ? gibDamage : baseDamage;\n const result = T_Damage(target, crusher, crusher, ZERO, target.origin, ZERO, amount, 1, DamageFlags.NONE, DamageMod.CRUSH);\n\n return { amount, result };\n}\n\nexport interface TelefragEntity extends Damageable {\n readonly movetype?: MoveType;\n readonly solid?: Solid;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface TelefragTarget extends Damageable {\n readonly inUse?: boolean;\n readonly movetype?: MoveType;\n readonly solid?: Solid;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n}\n\nexport interface TelefragEvent {\n readonly target: TelefragTarget;\n readonly result: DamageApplicationResult | null;\n}\n\nexport interface TelefragResult {\n readonly events: TelefragEvent[];\n readonly cleared: boolean;\n}\n\nexport interface TelefragOptions {\n readonly mod?: DamageMod;\n}\n\nfunction absoluteBounds(ent: { readonly origin: Vec3; readonly mins?: Vec3; readonly maxs?: Vec3 }): Bounds3 {\n const mins = ent.mins ?? ZERO;\n const maxs = ent.maxs ?? ZERO;\n\n return {\n mins: addVec3(ent.origin, mins),\n maxs: addVec3(ent.origin, maxs),\n };\n}\n\nexport function killBox(\n teleporter: TelefragEntity,\n targets: readonly TelefragTarget[],\n options: TelefragOptions = {},\n): TelefragResult {\n if (teleporter.movetype === MoveType.Noclip) {\n return { events: [], cleared: true };\n }\n\n const mod = options.mod ?? DamageMod.TELEFRAG;\n const teleBounds = absoluteBounds(teleporter);\n const events: TelefragEvent[] = [];\n let cleared = true;\n\n for (const target of targets) {\n if (target === teleporter || target.inUse === false) {\n continue;\n }\n\n const solidity = target.solid ?? Solid.Not;\n if (!target.takedamage || solidity === Solid.Not || solidity === Solid.Trigger || solidity === Solid.Bsp) {\n continue;\n }\n\n if (!boxesIntersect(teleBounds, absoluteBounds(target))) {\n continue;\n }\n\n const result = T_Damage(target, teleporter, teleporter, ZERO, target.origin, ZERO, 100_000, 0, DamageFlags.NO_PROTECTION, mod);\n events.push({ target, result });\n\n if (!result || !result.killed || target.health > 0) {\n cleared = false;\n }\n }\n\n return { events, cleared };\n}\n","export enum AmmoType {\n Bullets = 0,\n Shells,\n Rockets,\n Grenades,\n Cells,\n Slugs,\n}\n\nexport const AMMO_TYPE_COUNT = Object.keys(AmmoType).length / 2;\n\nexport type AmmoCaps = readonly number[];\n\nexport interface AmmoInventory {\n readonly caps: AmmoCaps;\n counts: number[];\n}\n\nexport interface AmmoAdjustmentResult {\n readonly ammoType: AmmoType;\n readonly added: number;\n readonly newCount: number;\n readonly capped: number;\n readonly pickedUp: boolean;\n}\n\nexport enum AmmoItemId {\n Shells = 'ammo_shells',\n Bullets = 'ammo_bullets',\n Rockets = 'ammo_rockets',\n Grenades = 'ammo_grenades',\n Cells = 'ammo_cells',\n Slugs = 'ammo_slugs',\n}\n\nexport interface AmmoItemDefinition {\n readonly id: AmmoItemId;\n readonly ammoType: AmmoType;\n readonly quantity: number;\n readonly weaponAmmo: boolean;\n}\n\nconst AMMO_ITEM_DEFINITIONS: Record<AmmoItemId, AmmoItemDefinition> = {\n [AmmoItemId.Shells]: { id: AmmoItemId.Shells, ammoType: AmmoType.Shells, quantity: 10, weaponAmmo: false },\n [AmmoItemId.Bullets]: { id: AmmoItemId.Bullets, ammoType: AmmoType.Bullets, quantity: 50, weaponAmmo: false },\n [AmmoItemId.Rockets]: { id: AmmoItemId.Rockets, ammoType: AmmoType.Rockets, quantity: 5, weaponAmmo: false },\n [AmmoItemId.Grenades]: { id: AmmoItemId.Grenades, ammoType: AmmoType.Grenades, quantity: 5, weaponAmmo: true },\n [AmmoItemId.Cells]: { id: AmmoItemId.Cells, ammoType: AmmoType.Cells, quantity: 50, weaponAmmo: false },\n [AmmoItemId.Slugs]: { id: AmmoItemId.Slugs, ammoType: AmmoType.Slugs, quantity: 10, weaponAmmo: false },\n};\n\nexport function getAmmoItemDefinition(id: AmmoItemId): AmmoItemDefinition {\n return AMMO_ITEM_DEFINITIONS[id];\n}\n\nexport function createAmmoInventory(caps: AmmoCaps = createBaseAmmoCaps()): AmmoInventory {\n return { caps: caps.slice(), counts: Array(AMMO_TYPE_COUNT).fill(0) };\n}\n\n/**\n * Mirrors the rerelease defaults in p_client.cpp where max ammo counts are\n * seeded to 50, then overridden for select types (bullets/shells/cells).\n */\nexport function createBaseAmmoCaps(): number[] {\n const caps = Array(AMMO_TYPE_COUNT).fill(50);\n caps[AmmoType.Bullets] = 200;\n caps[AmmoType.Shells] = 100;\n caps[AmmoType.Cells] = 200;\n return caps;\n}\n\nexport function clampAmmoCounts(counts: readonly number[], caps: AmmoCaps): number[] {\n const limit = Math.min(counts.length, caps.length);\n const clamped: number[] = counts.slice(0, limit);\n\n for (let i = 0; i < limit; i++) {\n const cap = caps[i];\n if (cap !== undefined) {\n clamped[i] = Math.min(counts[i], cap);\n }\n }\n\n return clamped;\n}\n\nexport function addAmmo(inventory: AmmoInventory, ammoType: AmmoType, amount: number): AmmoAdjustmentResult {\n const cap = inventory.caps[ammoType];\n const current = inventory.counts[ammoType] ?? 0;\n\n if (cap !== undefined && current >= cap) {\n return { ammoType, added: 0, newCount: current, capped: cap, pickedUp: false };\n }\n\n const uncapped = current + amount;\n const newCount = cap === undefined ? uncapped : Math.min(uncapped, cap);\n const added = newCount - current;\n\n inventory.counts[ammoType] = newCount;\n\n return { ammoType, added, newCount, capped: cap ?? Number.POSITIVE_INFINITY, pickedUp: added > 0 };\n}\n\nexport interface AmmoPickupOptions {\n readonly countOverride?: number;\n}\n\nexport function pickupAmmo(\n inventory: AmmoInventory,\n itemId: AmmoItemId,\n options: AmmoPickupOptions = {},\n): AmmoAdjustmentResult {\n const def = getAmmoItemDefinition(itemId);\n const amount = options.countOverride ?? def.quantity;\n\n return addAmmo(inventory, def.ammoType, amount);\n}\n","import { ARMOR_INFO, ArmorType, type RegularArmorState } from '../combat/armor.js';\nimport {\n AmmoInventory,\n AmmoItemId,\n AmmoType,\n AmmoAdjustmentResult,\n AmmoCaps,\n addAmmo,\n createAmmoInventory,\n pickupAmmo,\n} from './ammo.js';\n\nexport enum WeaponId {\n Blaster = 'blaster',\n Shotgun = 'shotgun',\n SuperShotgun = 'super_shotgun',\n Machinegun = 'machinegun',\n Chaingun = 'chaingun',\n GrenadeLauncher = 'grenade_launcher',\n RocketLauncher = 'rocket_launcher',\n HyperBlaster = 'hyperblaster',\n Railgun = 'railgun',\n BFG10K = 'bfg10k',\n}\n\nexport enum PowerupId {\n QuadDamage = 'quad',\n Invulnerability = 'invulnerability',\n EnviroSuit = 'enviro_suit',\n Rebreather = 'rebreather',\n Silencer = 'silencer',\n}\n\nexport enum KeyId {\n Blue = 'blue',\n Red = 'red',\n Green = 'green',\n Yellow = 'yellow',\n}\n\nexport interface PlayerInventoryOptions {\n readonly ammoCaps?: AmmoCaps;\n readonly weapons?: readonly WeaponId[];\n readonly currentWeapon?: WeaponId;\n readonly armor?: RegularArmorState | null;\n readonly powerups?: Iterable<[PowerupId, number | null]>;\n readonly keys?: readonly KeyId[];\n}\n\nexport interface PlayerInventory {\n readonly ammo: AmmoInventory;\n readonly ownedWeapons: Set<WeaponId>;\n currentWeapon?: WeaponId;\n armor: RegularArmorState | null;\n readonly powerups: Map<PowerupId, number | null>;\n readonly keys: Set<KeyId>;\n}\n\nexport function createPlayerInventory(options: PlayerInventoryOptions = {}): PlayerInventory {\n const ammo = createAmmoInventory(options.ammoCaps);\n const ownedWeapons = new Set(options.weapons ?? []);\n const powerups = new Map<PowerupId, number | null>(options.powerups ?? []);\n const keys = new Set(options.keys ?? []);\n\n return {\n ammo,\n ownedWeapons,\n currentWeapon: options.currentWeapon,\n armor: options.armor ?? null,\n powerups,\n keys,\n };\n}\n\nexport function giveAmmo(inventory: PlayerInventory, ammoType: AmmoType, amount: number): AmmoAdjustmentResult {\n return addAmmo(inventory.ammo, ammoType, amount);\n}\n\nexport function giveAmmoItem(\n inventory: PlayerInventory,\n itemId: AmmoItemId,\n options?: Parameters<typeof pickupAmmo>[2],\n): AmmoAdjustmentResult {\n return pickupAmmo(inventory.ammo, itemId, options);\n}\n\nexport function giveWeapon(inventory: PlayerInventory, weapon: WeaponId, select = false): boolean {\n const hadWeapon = inventory.ownedWeapons.has(weapon);\n inventory.ownedWeapons.add(weapon);\n if (select || !inventory.currentWeapon) {\n inventory.currentWeapon = weapon;\n }\n return !hadWeapon;\n}\n\nexport function hasWeapon(inventory: PlayerInventory, weapon: WeaponId): boolean {\n return inventory.ownedWeapons.has(weapon);\n}\n\nexport function selectWeapon(inventory: PlayerInventory, weapon: WeaponId): boolean {\n if (!inventory.ownedWeapons.has(weapon)) {\n return false;\n }\n inventory.currentWeapon = weapon;\n return true;\n}\n\nexport function equipArmor(inventory: PlayerInventory, armorType: ArmorType | null, amount: number): RegularArmorState | null {\n if (!armorType || amount <= 0) {\n inventory.armor = null;\n return null;\n }\n\n const info = ARMOR_INFO[armorType];\n const armorCount = Math.min(amount, info.maxCount);\n inventory.armor = { armorType, armorCount };\n return inventory.armor;\n}\n\nexport function addPowerup(inventory: PlayerInventory, powerup: PowerupId, expiresAt: number | null): void {\n inventory.powerups.set(powerup, expiresAt);\n}\n\nexport function hasPowerup(inventory: PlayerInventory, powerup: PowerupId): boolean {\n return inventory.powerups.has(powerup);\n}\n\nexport function clearExpiredPowerups(inventory: PlayerInventory, nowMs: number): void {\n for (const [id, expiresAt] of inventory.powerups.entries()) {\n if (expiresAt !== null && expiresAt <= nowMs) {\n inventory.powerups.delete(id);\n }\n }\n}\n\nexport function addKey(inventory: PlayerInventory, key: KeyId): boolean {\n const before = inventory.keys.size;\n inventory.keys.add(key);\n return inventory.keys.size > before;\n}\n\nexport function hasKey(inventory: PlayerInventory, key: KeyId): boolean {\n return inventory.keys.has(key);\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';\nexport * from './ai/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 { hashGameState } from './checksum.js';\nexport * from './save/index.js';\nexport * from './combat/index.js';\nexport * from './inventory/index.js';\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\nexport interface MersenneTwisterState {\n readonly index: number;\n readonly state: readonly number[];\n}\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 getState(): MersenneTwisterState {\n return {\n index: this.index,\n state: Array.from(this.state),\n };\n }\n\n setState(snapshot: MersenneTwisterState): void {\n if (snapshot.state.length !== STATE_SIZE) {\n throw new Error(`Expected ${STATE_SIZE} MT state values, received ${snapshot.state.length}`);\n }\n\n this.index = snapshot.index;\n this.state = Uint32Array.from(snapshot.state, (value) => value >>> 0);\n }\n}\n\nexport interface RandomGeneratorOptions {\n readonly seed?: number;\n}\n\nexport interface RandomGeneratorState {\n readonly mt: MersenneTwisterState;\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 getState(): RandomGeneratorState {\n return { mt: this.mt.getState() };\n }\n\n setState(snapshot: RandomGeneratorState): void {\n this.mt.setState(snapshot.mt);\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_TRIGGER: ContentsFlag = 0x40000000;\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 { CONTENTS_TRIGGER } from './contents.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { ZERO_VEC3, addVec3, scaleVec3, subtractVec3 } 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 visibility?: CollisionVisibility;\n}\n\nexport interface CollisionVisibilityCluster {\n pvs: Uint8Array;\n phs: Uint8Array;\n}\n\nexport interface CollisionVisibility {\n numClusters: number;\n clusters: readonly CollisionVisibilityCluster[];\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 visibility?: CollisionVisibility;\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 interface CollisionTraceResult {\n fraction: number;\n endpos: Vec3;\n plane: CollisionPlane | null;\n planeNormal?: Vec3;\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\nconst MAX_CHECKCOUNT = Number.MAX_SAFE_INTEGER - 1;\nlet globalBrushCheckCount = 1;\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 visibility: lumps.visibility,\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\nfunction findLeafIndex(point: Vec3, model: CollisionModel, headnode: number): number {\n let nodeIndex = headnode;\n\n while (nodeIndex >= 0) {\n const node = model.nodes[nodeIndex];\n const dist = planeDistanceToPoint(node.plane, point);\n nodeIndex = dist >= 0 ? node.children[0] : node.children[1];\n }\n\n return -1 - nodeIndex;\n}\n\nfunction computeLeafContents(model: CollisionModel, leafIndex: number, point: Vec3): number {\n const leaf = model.leaves[leafIndex];\n let contents = leaf.contents;\n\n const brushCheckCount = nextBrushCheckCount();\n const start = leaf.firstLeafBrush;\n const end = start + leaf.numLeafBrushes;\n\n for (let i = start; i < end; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n if (pointInsideBrush(point, brush)) {\n contents |= brush.contents;\n }\n }\n\n return contents;\n}\n\nfunction nextBrushCheckCount(): number {\n const count = globalBrushCheckCount;\n globalBrushCheckCount += 1;\n if (globalBrushCheckCount >= MAX_CHECKCOUNT) {\n globalBrushCheckCount = 1;\n }\n return count;\n}\n\nfunction isPointBounds(mins: Vec3, maxs: Vec3): boolean {\n return mins.x === 0 && mins.y === 0 && mins.z === 0 && maxs.x === 0 && maxs.y === 0 && maxs.z === 0;\n}\n\nfunction planeOffsetForBounds(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n if (isPointBounds(mins, maxs)) return 0;\n\n const offset =\n plane.normal.x * (plane.normal.x < 0 ? maxs.x : mins.x) +\n plane.normal.y * (plane.normal.y < 0 ? maxs.y : mins.y) +\n plane.normal.z * (plane.normal.z < 0 ? maxs.z : mins.z);\n\n return offset;\n}\n\nfunction planeOffsetMagnitude(plane: CollisionPlane, mins: Vec3, maxs: Vec3): number {\n return Math.abs(planeOffsetForBounds(plane, mins, maxs));\n}\n\nfunction lerpPoint(start: Vec3, end: Vec3, t: number): Vec3 {\n return addVec3(start, scaleVec3(subtractVec3(end, start), t));\n}\n\nfunction finalizeTrace(trace: TraceResult, start: Vec3, end: Vec3): CollisionTraceResult {\n const clampedFraction = trace.allsolid ? 0 : trace.fraction;\n const endpos = lerpPoint(start, end, clampedFraction);\n\n return {\n fraction: clampedFraction,\n endpos,\n plane: trace.plane,\n planeNormal: trace.startsolid ? undefined : trace.plane?.normal,\n contents: trace.contents,\n surfaceFlags: trace.surfaceFlags,\n startsolid: trace.startsolid,\n allsolid: trace.allsolid,\n };\n}\n\nfunction clusterForPoint(point: Vec3, model: CollisionModel, headnode: number): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return model.leaves[leafIndex]?.cluster ?? -1;\n}\n\nfunction clusterVisible(\n visibility: CollisionVisibility,\n from: number,\n to: number,\n usePhs: boolean,\n): boolean {\n if (!visibility || visibility.numClusters === 0) return true;\n if (from < 0 || to < 0) return false;\n if (from >= visibility.clusters.length || to >= visibility.numClusters) return false;\n\n const cluster = visibility.clusters[from];\n const set = usePhs ? cluster.phs : cluster.pvs;\n const byte = set[to >> 3];\n if (byte === undefined) return false;\n\n return (byte & (1 << (to & 7))) !== 0;\n}\n\nfunction recursiveHullCheck(params: {\n readonly model: CollisionModel;\n readonly nodeIndex: number;\n readonly startFraction: number;\n readonly endFraction: number;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly traceStart: Vec3;\n readonly traceEnd: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contentMask: number;\n readonly trace: TraceResult;\n readonly brushCheckCount: number;\n}): void {\n const {\n model,\n nodeIndex,\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n } = params;\n\n if (trace.fraction <= startFraction) {\n return;\n }\n\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if ((brush.contents & contentMask) === 0) continue;\n if (!brush.sides.length) continue;\n if (brush.checkcount === brushCheckCount) continue;\n\n brush.checkcount = brushCheckCount;\n\n clipBoxToBrush({ start: traceStart, end: traceEnd, mins, maxs, brush, trace });\n if (trace.allsolid) {\n return;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetForBounds(plane, mins, maxs);\n\n const startDist = planeDistanceToPoint(plane, start) + offset;\n const endDist = planeDistanceToPoint(plane, end) + offset;\n\n if (startDist >= 0 && endDist >= 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[0],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n if (startDist < 0 && endDist < 0) {\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1],\n startFraction,\n endFraction,\n start,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n return;\n }\n\n let side = 0;\n let idist = 1 / (startDist - endDist);\n let fraction1 = (startDist - DIST_EPSILON) * idist;\n let fraction2 = (startDist + DIST_EPSILON) * idist;\n\n if (startDist < endDist) {\n side = 1;\n fraction1 = (startDist + DIST_EPSILON) * idist;\n fraction2 = (startDist - DIST_EPSILON) * idist;\n }\n\n if (fraction1 < 0) fraction1 = 0;\n else if (fraction1 > 1) fraction1 = 1;\n\n if (fraction2 < 0) fraction2 = 0;\n else if (fraction2 > 1) fraction2 = 1;\n\n const midFraction = startFraction + (endFraction - startFraction) * fraction1;\n const midPoint = lerpPoint(start, end, fraction1);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[side],\n startFraction,\n endFraction: midFraction,\n start,\n end: midPoint,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n const updatedFraction = trace.fraction;\n\n if (updatedFraction <= midFraction) {\n return;\n }\n\n const midFraction2 = startFraction + (endFraction - startFraction) * fraction2;\n const midPoint2 = lerpPoint(start, end, fraction2);\n\n recursiveHullCheck({\n model,\n nodeIndex: node.children[1 - side],\n startFraction: midFraction2,\n endFraction,\n start: midPoint2,\n end,\n traceStart,\n traceEnd,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n}\n\nexport interface CollisionTraceParams {\n readonly model: CollisionModel;\n readonly start: Vec3;\n readonly end: Vec3;\n readonly mins?: Vec3;\n readonly maxs?: Vec3;\n readonly headnode?: number;\n readonly contentMask?: number;\n}\n\nexport function traceBox(params: CollisionTraceParams): CollisionTraceResult {\n const { model, start, end } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n const headnode = params.headnode ?? 0;\n\n const trace = createDefaultTrace();\n const brushCheckCount = nextBrushCheckCount();\n\n recursiveHullCheck({\n model,\n nodeIndex: headnode,\n startFraction: 0,\n endFraction: 1,\n start,\n end,\n traceStart: start,\n traceEnd: end,\n mins,\n maxs,\n contentMask,\n trace,\n brushCheckCount,\n });\n\n return finalizeTrace(trace, start, end);\n}\n\nexport function pointContents(point: Vec3, model: CollisionModel, headnode = 0): number {\n const leafIndex = findLeafIndex(point, model, headnode);\n return computeLeafContents(model, leafIndex, point);\n}\n\nexport function pointContentsMany(points: readonly Vec3[], model: CollisionModel, headnode = 0): number[] {\n const leafCache = new Map<number, number>();\n\n return points.map((point) => {\n const leafIndex = findLeafIndex(point, model, headnode);\n const leaf = model.leaves[leafIndex];\n\n if (leaf.numLeafBrushes === 0) {\n const cached = leafCache.get(leafIndex);\n if (cached !== undefined) {\n return cached;\n }\n\n leafCache.set(leafIndex, leaf.contents);\n return leaf.contents;\n }\n\n return computeLeafContents(model, leafIndex, point);\n });\n}\n\nexport function boxContents(origin: Vec3, mins: Vec3, maxs: Vec3, model: CollisionModel, headnode = 0): number {\n const brushCheckCount = nextBrushCheckCount();\n let contents = 0;\n\n function traverse(nodeIndex: number) {\n if (nodeIndex < 0) {\n const leafIndex = -1 - nodeIndex;\n const leaf = model.leaves[leafIndex];\n\n contents |= leaf.contents;\n\n const brushStart = leaf.firstLeafBrush;\n const brushEnd = brushStart + leaf.numLeafBrushes;\n\n for (let i = brushStart; i < brushEnd; i += 1) {\n const brushIndex = model.leafBrushes[i];\n const brush = model.brushes[brushIndex];\n\n if (brush.checkcount === brushCheckCount) continue;\n brush.checkcount = brushCheckCount;\n\n if (brush.sides.length === 0) continue;\n\n const result = testBoxInBrush(origin, mins, maxs, brush);\n if (result.startsolid) {\n contents |= result.contents;\n }\n }\n return;\n }\n\n const node = model.nodes[nodeIndex];\n const plane = node.plane;\n const offset = planeOffsetMagnitude(plane, mins, maxs);\n const dist = planeDistanceToPoint(plane, origin);\n\n if (offset === 0) {\n traverse(dist >= 0 ? node.children[0] : node.children[1]);\n return;\n }\n\n if (dist > offset) {\n traverse(node.children[0]);\n return;\n }\n\n if (dist < -offset) {\n traverse(node.children[1]);\n return;\n }\n\n traverse(node.children[0]);\n traverse(node.children[1]);\n }\n\n traverse(headnode);\n\n return contents;\n}\n\nexport function inPVS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, false);\n}\n\nexport function inPHS(p1: Vec3, p2: Vec3, model: CollisionModel, headnode = 0): boolean {\n const { visibility } = model;\n if (!visibility) return true;\n\n const cluster1 = clusterForPoint(p1, model, headnode);\n const cluster2 = clusterForPoint(p2, model, headnode);\n\n return clusterVisible(visibility, cluster1, cluster2, true);\n}\n\nexport interface CollisionEntityLink {\n readonly id: number;\n readonly origin: Vec3;\n readonly mins: Vec3;\n readonly maxs: Vec3;\n readonly contents: number;\n readonly surfaceFlags?: number;\n}\n\ninterface CollisionEntityState extends CollisionEntityLink {\n readonly brush: CollisionBrush;\n readonly bounds: { readonly mins: Vec3; readonly maxs: Vec3 };\n}\n\nfunction axisAlignedPlane(normal: Vec3, dist: number, type: number): CollisionPlane {\n return { normal, dist, type, signbits: computePlaneSignBits(normal) };\n}\n\nfunction makeEntityBrush(link: CollisionEntityLink): CollisionBrush {\n const sx = link.surfaceFlags ?? 0;\n const xMax = link.origin.x + link.maxs.x;\n const xMin = link.origin.x + link.mins.x;\n const yMax = link.origin.y + link.maxs.y;\n const yMin = link.origin.y + link.mins.y;\n const zMax = link.origin.z + link.maxs.z;\n const zMin = link.origin.z + link.mins.z;\n\n const planes: CollisionPlane[] = [\n axisAlignedPlane({ x: 1, y: 0, z: 0 }, xMax, 0),\n axisAlignedPlane({ x: -1, y: 0, z: 0 }, -xMin, 0),\n axisAlignedPlane({ x: 0, y: 1, z: 0 }, yMax, 1),\n axisAlignedPlane({ x: 0, y: -1, z: 0 }, -yMin, 1),\n axisAlignedPlane({ x: 0, y: 0, z: 1 }, zMax, 2),\n axisAlignedPlane({ x: 0, y: 0, z: -1 }, -zMin, 2),\n ];\n\n const sides: CollisionBrushSide[] = planes.map((plane) => ({ plane, surfaceFlags: sx }));\n\n return { contents: link.contents, sides, checkcount: 0 };\n}\n\nfunction makeEntityState(link: CollisionEntityLink): CollisionEntityState {\n const brush = makeEntityBrush(link);\n return {\n ...link,\n brush,\n bounds: {\n mins: {\n x: link.origin.x + link.mins.x,\n y: link.origin.y + link.mins.y,\n z: link.origin.z + link.mins.z,\n },\n maxs: {\n x: link.origin.x + link.maxs.x,\n y: link.origin.y + link.maxs.y,\n z: link.origin.z + link.maxs.z,\n },\n },\n };\n}\n\nfunction boundsIntersect(a: { mins: Vec3; maxs: Vec3 }, b: { mins: Vec3; maxs: Vec3 }): 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\nfunction pickBetterTrace(\n best: CollisionTraceResult,\n candidate: CollisionTraceResult,\n): boolean {\n if (candidate.allsolid && !best.allsolid) return true;\n if (candidate.startsolid && !best.startsolid) return true;\n return candidate.fraction < best.fraction;\n}\n\nexport interface CollisionEntityTraceParams extends CollisionTraceParams {\n readonly passId?: number;\n}\n\nexport interface CollisionEntityTraceResult extends CollisionTraceResult {\n readonly entityId: number | null;\n}\n\nexport class CollisionEntityIndex {\n private readonly entities = new Map<number, CollisionEntityState>();\n\n link(entity: CollisionEntityLink): void {\n this.entities.set(entity.id, makeEntityState(entity));\n }\n\n unlink(entityId: number): void {\n this.entities.delete(entityId);\n }\n\n trace(params: CollisionEntityTraceParams): CollisionEntityTraceResult {\n const { passId } = params;\n const mins = params.mins ?? ZERO_VEC3;\n const maxs = params.maxs ?? ZERO_VEC3;\n const contentMask = params.contentMask ?? 0xffffffff;\n\n let bestTrace: CollisionTraceResult;\n let bestEntity: number | null = null;\n\n if (params.model) {\n bestTrace = traceBox(params);\n } else {\n bestTrace = finalizeTrace(createDefaultTrace(), params.start, params.end);\n }\n\n for (const entity of this.entities.values()) {\n if (entity.id === passId) continue;\n if ((entity.contents & contentMask) === 0) continue;\n\n const trace = createDefaultTrace();\n clipBoxToBrush({ start: params.start, end: params.end, mins, maxs, brush: entity.brush, trace });\n\n if (trace.contents === 0) {\n trace.contents = entity.contents;\n }\n\n const candidate = finalizeTrace(trace, params.start, params.end);\n if (pickBetterTrace(bestTrace, candidate)) {\n bestTrace = candidate;\n bestEntity = entity.id;\n }\n }\n\n return { ...bestTrace, entityId: bestEntity };\n }\n\n gatherTriggerTouches(origin: Vec3, mins: Vec3, maxs: Vec3, mask = CONTENTS_TRIGGER): number[] {\n const results: number[] = [];\n const queryBounds = {\n mins: addVec3(origin, mins),\n maxs: addVec3(origin, maxs),\n };\n\n for (const entity of this.entities.values()) {\n if ((entity.contents & mask) === 0) continue;\n if (boundsIntersect(queryBounds, entity.bounds)) {\n results.push(entity.id);\n }\n }\n\n return results;\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","export interface ContractValidationResult {\n missing: string[];\n nonFunctions: string[];\n extras: string[];\n}\n\nexport interface ContractValidationOptions {\n readonly name?: string;\n readonly allowExtra?: boolean;\n}\n\nexport type ContractFunctionMap<Keys extends readonly string[]> = Record<Keys[number], (...args: unknown[]) => unknown>;\n\nfunction normalize(object: Record<string, unknown> | undefined): Record<string, unknown> {\n return object ?? {};\n}\n\nexport function validateContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): ContractValidationResult {\n const normalized = normalize(table);\n const missing: string[] = [];\n const nonFunctions: string[] = [];\n\n for (const key of requiredKeys) {\n if (!(key in normalized)) {\n missing.push(key);\n continue;\n }\n\n if (typeof normalized[key] !== 'function') {\n nonFunctions.push(key);\n }\n }\n\n const extras = options.allowExtra === false ? Object.keys(normalized).filter((key) => !requiredKeys.includes(key)) : [];\n\n return { missing, nonFunctions, extras } satisfies ContractValidationResult;\n}\n\nexport function assertContract<Keys extends readonly string[]>(\n table: Record<string, unknown> | undefined,\n requiredKeys: Keys,\n options: ContractValidationOptions = {},\n): asserts table is ContractFunctionMap<Keys> {\n const { missing, nonFunctions, extras } = validateContract(table, requiredKeys, options);\n if (missing.length === 0 && nonFunctions.length === 0 && extras.length === 0) {\n return;\n }\n\n const pieces: string[] = [];\n if (missing.length > 0) {\n pieces.push(`missing: ${missing.join(', ')}`);\n }\n if (nonFunctions.length > 0) {\n pieces.push(`non-functions: ${nonFunctions.join(', ')}`);\n }\n if (extras.length > 0) {\n pieces.push(`extras: ${extras.join(', ')}`);\n }\n\n const label = options.name ?? 'contract';\n throw new Error(`${label} validation failed (${pieces.join('; ')})`);\n}\n\nexport const GAME_IMPORT_KEYS = [\n 'Broadcast_Print',\n 'Com_Print',\n 'Client_Print',\n 'Center_Print',\n 'sound',\n 'positioned_sound',\n 'local_sound',\n 'configstring',\n 'get_configstring',\n 'Com_Error',\n 'modelindex',\n 'soundindex',\n 'imageindex',\n 'setmodel',\n 'trace',\n 'clip',\n 'pointcontents',\n 'inPVS',\n 'inPHS',\n 'SetAreaPortalState',\n 'AreasConnected',\n 'linkentity',\n 'unlinkentity',\n 'BoxEdicts',\n 'multicast',\n 'unicast',\n] as const;\n\nexport const GAME_EXPORT_KEYS = [\n 'PreInit',\n 'Init',\n 'Shutdown',\n 'SpawnEntities',\n 'WriteGameJson',\n 'ReadGameJson',\n 'WriteLevelJson',\n 'ReadLevelJson',\n 'CanSave',\n 'ClientConnect',\n 'ClientThink',\n 'RunFrame',\n 'Pmove',\n] as const;\n\nexport const CGAME_IMPORT_KEYS = [\n 'Com_Print',\n 'get_configstring',\n 'Com_Error',\n 'TagMalloc',\n 'TagFree',\n 'AddCommandString',\n 'CL_FrameValid',\n 'CL_FrameTime',\n 'CL_ClientTime',\n 'CL_ServerFrame',\n 'Draw_RegisterPic',\n 'Draw_GetPicSize',\n 'SCR_DrawChar',\n 'SCR_DrawPic',\n 'SCR_DrawColorPic',\n] as const;\n\nexport const CGAME_EXPORT_KEYS = [\n 'Init',\n 'Shutdown',\n 'DrawHUD',\n 'TouchPics',\n 'LayoutFlags',\n 'GetActiveWeaponWheelWeapon',\n 'GetOwnedWeaponWheelWeapons',\n 'GetWeaponWheelAmmoCount',\n 'GetPowerupWheelCount',\n 'GetHitMarkerDamage',\n 'Pmove',\n 'ParseConfigString',\n 'ParseCenterPrint',\n 'ClearNotify',\n 'ClearCenterprint',\n 'NotifyMessage',\n 'GetMonsterFlashOffset',\n] as const;\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 { angleMod } from '../math/angles.js';\nimport type { Vec3 } from '../math/vec3.js';\nimport { PlayerButton } from '../pmove/constants.js';\n\nexport interface UserCommand {\n readonly msec: number;\n readonly buttons: PlayerButton;\n readonly angles: Vec3;\n readonly forwardmove: number;\n readonly sidemove: number;\n readonly upmove: number;\n readonly serverFrame?: number;\n}\n\nexport interface MouseDelta {\n readonly deltaX: number;\n readonly deltaY: number;\n}\n\nexport interface MouseLookOptions {\n readonly sensitivity: number;\n readonly invertY: boolean;\n readonly sensitivityX?: number;\n readonly sensitivityY?: number;\n}\n\nexport const DEFAULT_FORWARD_SPEED = 200;\nexport const DEFAULT_SIDE_SPEED = 200;\nexport const DEFAULT_UP_SPEED = 200;\nexport const DEFAULT_YAW_SPEED = 140;\nexport const DEFAULT_PITCH_SPEED = 150;\nexport const DEFAULT_MOUSE_SENSITIVITY = 3;\n\nfunction clampPitch(pitch: number): number {\n const normalized = angleMod(pitch);\n\n if (normalized > 89 && normalized < 180) return 89;\n if (normalized < 271 && normalized >= 180) return 271;\n\n return normalized;\n}\n\nexport function addViewAngles(current: Vec3, delta: Vec3): Vec3 {\n return {\n x: clampPitch(current.x + delta.x),\n y: angleMod(current.y + delta.y),\n z: angleMod(current.z + delta.z),\n } satisfies Vec3;\n}\n\nexport function mouseDeltaToViewDelta(delta: MouseDelta, options: MouseLookOptions): Vec3 {\n const yawScale = options.sensitivityX ?? options.sensitivity;\n const pitchScale = (options.sensitivityY ?? options.sensitivity) * (options.invertY ? -1 : 1);\n\n return {\n x: delta.deltaY * pitchScale,\n y: delta.deltaX * yawScale,\n z: 0,\n } satisfies Vec3;\n}\n"],"mappings":"wcAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,qBAAAE,KCOO,IAAMC,GAAkB,CAAE,EAAG,EAAG,EAAG,EAAG,EAAG,CAAE,EAK5CC,GAAa,KAAK,GAAK,IAUtB,SAASC,EAAQC,EAASC,EAAe,CAC9C,MAAO,CAAE,EAAGD,EAAE,EAAIC,EAAE,EAAG,EAAGD,EAAE,EAAIC,EAAE,EAAG,EAAGD,EAAE,EAAIC,EAAE,CAAE,CACpD,CAUO,SAASC,EAAUF,EAASG,EAAsB,CACvD,MAAO,CAAE,EAAGH,EAAE,EAAIG,EAAQ,EAAGH,EAAE,EAAIG,EAAQ,EAAGH,EAAE,EAAIG,CAAO,CAC7D,CAMO,SAASC,EAAQJ,EAASC,EAAiB,CAChD,OAAOD,EAAE,EAAIC,EAAE,EAAID,EAAE,EAAIC,EAA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ASI,EAAA,EAAxB,eACAJ,EAAAA,EAAA,MAAQA,EAAA,aAAeK,EAAA,EAAvB,QACAL,EAAAA,EAAA,YAAcA,EAAA,MAAQM,EAAA,EAAtB,cACAN,EAAAA,EAAA,QAAUA,EAAA,YAAcO,EAAA,EAAxB,UACAP,EAAAA,EAAA,aAAeA,EAAA,QAAUQ,EAAA,EAAzB,eACAR,EAAAA,EAAA,UAAYA,EAAA,aAAeS,EAAA,EAA3B,YACAT,EAAAA,EAAA,cAAgBA,EAAA,UAAYS,EAAA,EAA5B,gBACAT,EAAAA,EAAA,YAAcA,EAAA,cAAgBS,EAAA,EAA9B,cACAT,EAAAA,EAAA,UAAYA,EAAA,YAAc,CAAA,EAA1B,YACAA,EAAAA,EAAA,iBAAmBA,EAAA,UAAY,CAAA,EAA/B,mBAzBUA,IAAAA,IAAA,CAAA,CAAA,EA6BCU,GAAoBV,GAAkB,iB1JtD5C,SAASW,IAAkB,CAChC,IAAMC,EAASC,GAAa,CAC1B,MAAMC,EAAOC,EAAK,CAChB,MAAO,CAAE,MAAAD,EAAO,IAAAC,EAAK,SAAU,CAAE,CACnC,CACF,CAAC,EAEKC,EAAOC,GAAW,CACtB,MAAMH,EAAOC,EAAK,CAChB,MAAO,CAAE,MAAAD,EAAO,IAAAC,EAAK,SAAU,CAAE,CACnC,CACF,EAAG,CAAE,QAASG,EAAU,CAAC,EAEnBC,EAASC,GAAa,CAAE,OAAQ,CAAE,MAAO,KAAO,CAAE,MAAOF,GAAW,IAAKA,GAAW,SAAU,CAAE,EAAG,CAAE,CAAC,EAEtGG,EAAUC,GAAoBV,EAAQI,EAAMG,CAAmC,EACrF,OAAAE,EAAQ,MAAM,EAEP,CAAE,OAAAT,EAAQ,KAAAI,EAAM,OAAAG,EAAQ,QAAAE,CAAQ,CACzC","names":["src_exports","__export","bootstrapViewer","ZERO_VEC3","DEG_TO_RAD","addVec3","a","b","scaleVec3","scalar","dotVec3","lengthSquaredVec3","lengthVec3","normalizeVec3","len","PITCH","YAW","ROLL","DEG2RAD_FACTOR","RAD2DEG_FACTOR","axisComponent","vec","axis","degToRad","degrees","angleMod","angle","value","angleVectors","angles","yaw","pitch","roll","sy","cy","sp","cp","sr","cr","forward","right","up","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_CHECKCOUNT","MAX_CLIENTS","MAX_LIGHTSTYLES","MAX_MODELS","MAX_SOUNDS","MAX_IMAGES","MAX_ITEMS","MAX_GENERAL","MAX_SHADOW_LIGHTS","MAX_WHEEL_ITEMS","ConfigStringIndex","MAX_CONFIGSTRINGS","WaterLevel","PmFlag","hasPmFlag","flags","flag","PmType","PlayerButton","applyPmoveFriction","params","velocity","frametime","onGround","groundIsSlick","onLadder","waterlevel","pmFriction","pmStopSpeed","pmWaterFriction","speed","lengthVec3","drop","control","newspeed","scale","scaleVec3","applyPmoveAccelerate","wishdir","wishspeed","accel","currentSpeed","dotVec3","addSpeed","accelSpeed","applyPmoveAirAccelerate","wishspd","buildAirGroundWish","forward","right","cmd","maxSpeed","wishvel","normalizeVec3","buildWaterWish","addVec3","addAngles","cmdAngles","deltaAngles","clampPitch","pitch","clampViewAngles","params","pmFlags","viewangles","vectors","angleVectors","DEFAULTS","DEFAULT_GRAVITY","ZERO_VEC3","MSEC_MAX","defaultPredictionState","PmFlag","PmType","WaterLevel","normalizeState","state","lerp","a","b","t","lerpAngle","delta","angleMod","interpolatePredictionState","previous","latest","alpha","clamped","simulateCommand","cmd","settings","frametime","onGround","hasPmFlag","onLadder","velocity","applyPmoveFriction","viewangles","forward","right","clampViewAngles","wish","buildWaterWish","buildAirGroundWish","applyPmoveAccelerate","maxSpeed","clampedWish","applyPmoveAirAccelerate","originDelta","scaleVec3","origin","addVec3","ClientPrediction","frame","normalized","DEFAULT_SETTINGS","clampViewOffset","offset","computeBobMove","xyspeed","frameTimeMs","computeBobValues","previousBobTime","pmFlags","bobMove","bobTimeRun","bobTime","ViewEffects","kick","angleVectors","bobValues","pitchTilt","dotVec3","rollTilt","pitchDelta","rollDelta","bobHeight","kickPitch","kickRoll","ratio","sample","normalizeCommand","command","InputAction","BUTTON_ACTIONS","PlayerButton","ACTION_LOOKUP","action","normalizeCommand","createClient","imports","prediction","ClientPrediction","view","ViewEffects","latestFrame","lastRendered","lastView","initial","command","sample","interpolatePredictionState","frameTimeMs","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_CHECKCOUNT","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","RERELEASE_KNOWN_PAKS","FLOAT_BYTES","STRIDE","BSP_VERTEX_LAYOUT","SKYBOX_POSITIONS","createEngine","imports","callbacks","options","FixedTimestepLoop","ZERO_VEC3","DEG_TO_RAD","DEG2RAD_FACTOR","RAD2DEG_FACTOR","STATE_SIZE","MIDDLE_WORD","MATRIX_A","UPPER_MASK","LOWER_MASK","TWO_POW_32","MersenneTwister19937","seed","i","prev","next","y","snapshot","value","RandomGenerator","options","minInclusive","maxExclusive","epsilon","span","limit","sample","minMs","maxMs","container","createRandomGenerator","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_CHECKCOUNT","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","DEFAULT_MONSTER_INFO","Entity","index","ENTITY_FIELD_METADATA","MAX_EDICTS","WORLD_INDEX","EntityPool","maxEntities","i","world","count","_","current","value","entity","activeOrder","snapshot","seen","noteIndex","label","ThinkScheduler","timeSeconds","a","b","time","entries","resolver","entry","currentTimeSeconds","next","computeBounds","boundsIntersect","SERIALIZABLE_FIELDS","field","DESCRIPTORS","descriptor","serializeVec3","vec","deserializeVec3","x","y","z","assignField","name","serializeInventory","inventory","deserializeInventory","parsed","key","EntitySystem","createRandomGenerator","callback","nextThinkSeconds","classname","matches","targetname","choice","targetBounds","other","activator","delayed","self","entities","fields","indexToEntity","pendingEntityRefs","serialized","ref","target","activeEntities","first","firstBounds","j","second","secondBounds","bucket","victim","FRAME_TIME_SECONDS","FIELD_LOOKUP","ENTITY_FIELD_METADATA","field","orderedStageNames","GameFrameLoop","initialStages","stageName","handler","stage","handlers","index","startTimeMs","step","previousTimeMs","context","i","writeIndex","readIndex","ZERO_STATE","LevelClock","startSeconds","state","FL_NOVISIBLE","SAVE_FORMAT_VERSION","MIN_SUPPORTED_VERSION","ensureObject","value","label","ensureNumber","ensureNumberOrDefault","defaultValue","ensureString","ensureNumberArray","element","parseLevelState","raw","level","parseRngState","RandomGenerator","rng","mt","state","parseThinkEntries","entry","idx","think","parseEntityFields","fields","parsed","name","object","inventory","entryName","entryValue","x","y","z","parseEntities","entity","parsePool","pool","parseEntitySnapshot","snapshot","parseCvars","cvar","parseConfigstrings","parseGameState","parseSaveFile","serialized","options","allowNewerVersion","raw","save","ensureObject","versionValue","SAVE_FORMAT_VERSION","version","ensureNumber","MIN_SUPPORTED_VERSION","ensureString","parseGameState","parseLevelState","parseRngState","parseEntitySnapshot","parseCvars","parseConfigstrings","TEXT_ENCODER_CTOR","cloneSave","save","parseSaveFile","estimateSizeBytes","MemorySaveAdapter","record","copy","id","IndexedDbSaveAdapter","indexedDB","dbName","storeName","resolve","reject","request","mode","operation","database","store","_SaveStorage","options","indexedDBFactory","slotId","normalized","metadata","a","b","AmmoType","AMMO_TYPE_COUNT","ZERO_VEC3","createGame","engine","options","gravity","levelClock","LevelClock","frameLoop","GameFrameLoop","entities","EntitySystem","context","deltaSeconds","velocity","origin","snapshot","frame","resetState","startTimeMs","step","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_CHECKCOUNT","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"]}
|