@adatechnology/game-shapes 0.2.4 → 0.2.5
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/dist/index.global.js.map +1 -1
- package/package.json +2 -2
package/dist/index.global.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/color.ts","../src/hash.ts","../src/math.ts","../src/primitives/three-generators.ts","../src/primitives/difference.ts","../src/primitives/earcut.ts","../src/primitives/extrude.ts","../src/primitives/index.ts","../src/random.ts","../src/registry.ts","../schema/shape.schema.json","../src/schema.ts","../src/generate.ts","../src/merge.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/index.ts","../src/instance.ts","../src/cache.ts","../src/pool.ts","../src/worker.ts"],"sourcesContent":["export { generate, isPrimitiveNode, keyOptions, shapeKey } from './generate'\nexport {\n box,\n buildPrimitive,\n circle,\n clearTemplateCache,\n clonePrimitive,\n computeVertexNormals,\n cone,\n cylinder,\n difference,\n extrude,\n lathe,\n plane,\n primitiveParameters,\n ring,\n setTemplateCacheSize,\n sphere,\n templateCacheStats,\n torus,\n} from './primitives'\nexport type { DetailOptions } from './primitives'\nexport { byteSizeOf, cloneBuffers, mergeTransformed, transferablesOf } from './merge'\nexport type { MergedArrays, TransformedPiece } from './merge'\nexport { SHAPE_SCHEMA, assertValidShape, validateShape } from './schema'\nexport { defaultShapeGenerators, getGenerator, listGenerators, registerGenerator, unregisterGenerator } from './registry'\nexport type { ShapeGenerators } from './registry'\nexport { createShapes } from './instance'\nexport type { Shapes, ShapesOptions } from './instance'\nexport { canonicalJson, hash64, hashValue } from './hash'\nexport { mulberry32, streamFor } from './random'\nexport { colorChannels, colorHex, srgbToLinear } from './color'\nexport { compose, headingMatrix, identity4, isAffine, matrixOf, multiply, normalMatrix, quaternionFromEuler, transformPoint } from './math'\nexport type { Matrix3, Matrix4 } from './math'\nexport type * from './types'\nexport { createShapeCache } from './cache'\nexport type { ShapeCache, ShapeCacheOptions, ShapeCacheStats } from './cache'\nexport { createShapePool } from './pool'\nexport type { ShapePool, ShapePoolOptions, ShapePoolStats, ShapeRequest, WorkerLike } from './pool'\nexport { installShapeWorker } from './worker'\nexport type { ShapeJob, ShapeReply, ShapeWorkerOptions, WorkerScopeLike } from './worker'\n","import type { Color } from './types'\n\n/** A colour as `0xRRGGBB`: numbers as given (floored, as three's `setHex`), `'#rrggbb'` strings parsed. */\nexport function colorHex(color: Color | undefined, fallback = 0xffffff): number {\n if (color === undefined) return fallback\n if (typeof color === 'number') return Math.floor(color)\n const match = /^#([0-9a-fA-F]{6})$/.exec(color)\n if (!match) throw new Error(`game-shapes: colour \"${color}\" is not 0xRRGGBB or #rrggbb`)\n return parseInt(match[1] as string, 16)\n}\n\n/** three's `SRGBToLinear` (r160 `ColorManagement`), the same constants. */\nexport const srgbToLinear = (c: number): number => (c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4))\n\n/**\n * The rgb floats of a hex colour as three's `Color.setHex` stores them: the channels over 255 (`'srgb'`), converted to the linear working space\n * when colour management is on (`'linear'`).\n */\nexport function colorChannels(hex: number, space: 'linear' | 'srgb'): [number, number, number] {\n const r = ((hex >> 16) & 255) / 255\n const g = ((hex >> 8) & 255) / 255\n const b = (hex & 255) / 255\n return space === 'linear' ? [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)] : [r, g, b]\n}\n","/**\n * Canonical JSON (keys sorted, `undefined` left out, `-0` kept as `-0`, typed arrays as plain lists) and a 64-bit FNV-1a of it in two 32-bit\n * lanes: the key a shape is cached and shared by.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'number') return Object.is(value, -0) ? '-0' : Number.isFinite(value) ? String(value) : JSON.stringify(String(value))\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'function') throw new Error('game-shapes: a function cannot be part of a shape (register it as a generator)')\n if (ArrayBuffer.isView(value)) return canonicalJson(Array.from(value as unknown as ArrayLike<number>))\n if (Array.isArray(value)) return `[${value.map((item) => (item === undefined ? 'null' : canonicalJson(item))).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined).sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\nconst lane = (text: string, offset: number, prime: number): string => {\n let hash = offset\n for (let index = 0; index < text.length; index++) {\n hash ^= text.charCodeAt(index)\n hash = Math.imul(hash, prime)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** 64-bit FNV-1a of a text as 16 hex digits (two independent 32-bit lanes). */\nexport const hash64 = (text: string): string => lane(text, 0x811c9dc5, 0x01000193) + lane(text, 0x050c5d1f, 0x5bd1e995)\n\n/** `hash64(canonicalJson(value))`. */\nexport const hashValue = (value: unknown): string => hash64(canonicalJson(value))\n","/*\n * Matrix and quaternion arithmetic as three.js r160 does it (MIT, https://github.com/mrdoob/three.js): the same expressions in the same order, so a\n * vertex baked here has the same bits as one baked by `Matrix4.compose` / `multiplyMatrices` / `Matrix3.getNormalMatrix` / `Vector3.normalize`.\n * Matrices are column-major arrays of 16 (4 x 4) or 9 (3 x 3) numbers, the layout of three's `elements`.\n */\nimport type { Mat4, RotationOrder, Transform, Vec3 } from './types'\n\nexport type Matrix4 = number[]\nexport type Matrix3 = number[]\n\nexport const identity4 = (): Matrix4 => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n\n/** `Quaternion.setFromEuler` (x, y, z, w). */\nexport function quaternionFromEuler(x: number, y: number, z: number, order: RotationOrder = 'XYZ'): [number, number, number, number] {\n const cos = Math.cos\n const sin = Math.sin\n const c1 = cos(x / 2)\n const c2 = cos(y / 2)\n const c3 = cos(z / 2)\n const s1 = sin(x / 2)\n const s2 = sin(y / 2)\n const s3 = sin(z / 2)\n switch (order) {\n case 'XYZ':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'YXZ':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n case 'ZXY':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'ZYX':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n case 'YZX':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'XZY':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n default:\n throw new Error(`game-shapes: unknown rotation order \"${String(order)}\"`)\n }\n}\n\n/** `Matrix4.compose(position, quaternion, scale)`. */\nexport function compose(px: number, py: number, pz: number, q: readonly [number, number, number, number], sx: number, sy: number, sz: number): Matrix4 {\n const [x, y, z, w] = q\n const x2 = x + x\n const y2 = y + y\n const z2 = z + z\n const xx = x * x2\n const xy = x * y2\n const xz = x * z2\n const yy = y * y2\n const yz = y * z2\n const zz = z * z2\n const wx = w * x2\n const wy = w * y2\n const wz = w * z2\n return [\n (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0,\n px, py, pz, 1,\n ]\n}\n\n/** `Matrix4.makeRotationY(theta)` followed by `setPosition(x, y, z)`. */\nexport function headingMatrix(theta: number, x = 0, y = 0, z = 0): Matrix4 {\n const c = Math.cos(theta)\n const s = Math.sin(theta)\n return [c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, x, y, z, 1]\n}\n\n/** `Matrix4.multiplyMatrices(a, b)`: a x b. */\nexport function multiply(ae: readonly number[], be: readonly number[]): Matrix4 {\n const a11 = ae[0]!, a12 = ae[4]!, a13 = ae[8]!, a14 = ae[12]!\n const a21 = ae[1]!, a22 = ae[5]!, a23 = ae[9]!, a24 = ae[13]!\n const a31 = ae[2]!, a32 = ae[6]!, a33 = ae[10]!, a34 = ae[14]!\n const a41 = ae[3]!, a42 = ae[7]!, a43 = ae[11]!, a44 = ae[15]!\n const b11 = be[0]!, b12 = be[4]!, b13 = be[8]!, b14 = be[12]!\n const b21 = be[1]!, b22 = be[5]!, b23 = be[9]!, b24 = be[13]!\n const b31 = be[2]!, b32 = be[6]!, b33 = be[10]!, b34 = be[14]!\n const b41 = be[3]!, b42 = be[7]!, b43 = be[11]!, b44 = be[15]!\n return [\n a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41,\n a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41,\n a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41,\n a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41,\n a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42,\n a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42,\n a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42,\n a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42,\n a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43,\n a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43,\n a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43,\n a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43,\n a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44,\n a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44,\n a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44,\n a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44,\n ]\n}\n\n/** `Matrix3.getNormalMatrix(m)`: the inverse transpose of the upper 3 x 3 (all zeros when singular, as three). */\nexport function normalMatrix(me: readonly number[]): Matrix3 {\n // setFromMatrix4\n const n11 = me[0]!, n21 = me[1]!, n31 = me[2]!\n const n12 = me[4]!, n22 = me[5]!, n32 = me[6]!\n const n13 = me[8]!, n23 = me[9]!, n33 = me[10]!\n // invert\n const t11 = n33 * n22 - n32 * n23\n const t12 = n32 * n13 - n33 * n12\n const t13 = n23 * n12 - n22 * n13\n const det = n11 * t11 + n21 * t12 + n31 * t13\n if (det === 0) return [0, 0, 0, 0, 0, 0, 0, 0, 0]\n const detInv = 1 / det\n const te = [\n t11 * detInv,\n (n31 * n23 - n33 * n21) * detInv,\n (n32 * n21 - n31 * n22) * detInv,\n t12 * detInv,\n (n33 * n11 - n31 * n13) * detInv,\n (n31 * n12 - n32 * n11) * detInv,\n t13 * detInv,\n (n21 * n13 - n23 * n11) * detInv,\n (n22 * n11 - n21 * n12) * detInv,\n ]\n // transpose\n let tmp = te[1]!\n te[1] = te[3]!\n te[3] = tmp\n tmp = te[2]!\n te[2] = te[6]!\n te[6] = tmp\n tmp = te[5]!\n te[5] = te[7]!\n te[7] = tmp\n return te\n}\n\n/** True when the last row is (0, 0, 0, 1): `applyMatrix4`'s divide by w is then a multiply by exactly 1. */\nexport const isAffine = (e: readonly number[]): boolean => e[3] === 0 && e[7] === 0 && e[11] === 0 && e[15] === 1\n\n/** `Vector3.applyMatrix4`. */\nexport function transformPoint(e: readonly number[], x: number, y: number, z: number): [number, number, number] {\n const w = 1 / (e[3]! * x + e[7]! * y + e[11]! * z + e[15]!)\n return [(e[0]! * x + e[4]! * y + e[8]! * z + e[12]!) * w, (e[1]! * x + e[5]! * y + e[9]! * z + e[13]!) * w, (e[2]! * x + e[6]! * y + e[10]! * z + e[14]!) * w]\n}\n\nconst toVec3 = (scale: number | Vec3 | undefined): Vec3 => (scale === undefined ? [1, 1, 1] : typeof scale === 'number' ? [scale, scale, scale] : scale)\n\n/** True when the transform has no field set. */\nexport const isIdentityTransform = (t: Transform): boolean =>\n t.matrix === undefined && t.heading === undefined && t.position === undefined && t.rotation === undefined && t.scale === undefined\n\n/** The local matrix of a transform, or `null` when it has none. */\nexport function matrixOf(t: Transform): Matrix4 | null {\n if (t.matrix !== undefined) return [...t.matrix]\n if (t.heading !== undefined) {\n const p = t.position ?? [0, 0, 0]\n return headingMatrix(t.heading, p[0], p[1], p[2])\n }\n if (t.position === undefined && t.rotation === undefined && t.scale === undefined) return null\n const p = t.position ?? [0, 0, 0]\n const r = t.rotation ?? [0, 0, 0]\n const s = toVec3(t.scale)\n return compose(p[0], p[1], p[2], quaternionFromEuler(r[0], r[1], r[2], t.rotationOrder ?? 'XYZ'), s[0], s[1], s[2])\n}\n\n/** The matrix as given, as a plain array (for `ShapePart.matrix`). */\nexport const asMat4 = (m: Matrix4 | null): Mat4 => (m ? [...m] : identity4())\n","/*\n * The geometry generators of three.js r160 (MIT, https://github.com/mrdoob/three.js, src/geometries/*.js), ported line by line: the same loops,\n * the same expressions in the same order, numbers pushed into plain arrays and stored as Float32 at the end, exactly as `Float32BufferAttribute`\n * does. A test compares every array of every generator with three's, bit for bit, over a grid of parameters.\n */\nimport type { GeometryGroup, PrimitiveBuffers } from '../types'\n\nexport interface Arrays {\n vertices: number[]\n normals: number[]\n uvs: number[]\n indices: number[] | null\n groups: GeometryGroup[]\n}\n\n/** three's `arrayNeedsUint32`: 32-bit indices once any index reaches 65535. */\nexport function needsUint32(array: ArrayLike<number>): boolean {\n for (let i = array.length - 1; i >= 0; --i) if ((array[i] as number) >= 65535) return true\n return false\n}\n\nexport const indexArray = (indices: ArrayLike<number>): Uint16Array | Uint32Array => (needsUint32(indices) ? new Uint32Array(indices) : new Uint16Array(indices))\n\nexport function pack(type: string, parameters: Record<string, unknown>, a: Arrays): PrimitiveBuffers {\n return {\n type,\n parameters,\n positions: new Float32Array(a.vertices),\n normals: new Float32Array(a.normals),\n uvs: new Float32Array(a.uvs),\n ...(a.indices ? { indices: indexArray(a.indices) } : {}),\n groups: a.groups,\n }\n}\n\nconst normalize3 = (x: number, y: number, z: number): [number, number, number] => {\n const length = Math.sqrt(x * x + y * y + z * z)\n const s = 1 / (length || 1)\n return [x * s, y * s, z * s]\n}\n\nexport function box(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1): PrimitiveBuffers {\n const parameters = { width, height, depth, widthSegments, heightSegments, depthSegments }\n widthSegments = Math.floor(widthSegments)\n heightSegments = Math.floor(heightSegments)\n depthSegments = Math.floor(depthSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const groups: GeometryGroup[] = []\n let numberOfVertices = 0\n let groupStart = 0\n type Axis = 'x' | 'y' | 'z'\n const buildPlane = (u: Axis, v: Axis, w: Axis, udir: number, vdir: number, width: number, height: number, depth: number, gridX: number, gridY: number, materialIndex: number): void => {\n const segmentWidth = width / gridX\n const segmentHeight = height / gridY\n const widthHalf = width / 2\n const heightHalf = height / 2\n const depthHalf = depth / 2\n const gridX1 = gridX + 1\n const gridY1 = gridY + 1\n let vertexCounter = 0\n let groupCount = 0\n const vector = { x: 0, y: 0, z: 0 }\n for (let iy = 0; iy < gridY1; iy++) {\n const y = iy * segmentHeight - heightHalf\n for (let ix = 0; ix < gridX1; ix++) {\n const x = ix * segmentWidth - widthHalf\n vector[u] = x * udir\n vector[v] = y * vdir\n vector[w] = depthHalf\n vertices.push(vector.x, vector.y, vector.z)\n vector[u] = 0\n vector[v] = 0\n vector[w] = depth > 0 ? 1 : -1\n normals.push(vector.x, vector.y, vector.z)\n uvs.push(ix / gridX)\n uvs.push(1 - iy / gridY)\n vertexCounter += 1\n }\n }\n for (let iy = 0; iy < gridY; iy++) {\n for (let ix = 0; ix < gridX; ix++) {\n const a = numberOfVertices + ix + gridX1 * iy\n const b = numberOfVertices + ix + gridX1 * (iy + 1)\n const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1)\n const d = numberOfVertices + (ix + 1) + gridX1 * iy\n indices.push(a, b, d)\n indices.push(b, c, d)\n groupCount += 6\n }\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex })\n groupStart += groupCount\n numberOfVertices += vertexCounter\n }\n buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0)\n buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1)\n buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2)\n buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3)\n buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4)\n buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5)\n return pack('BoxGeometry', parameters, { vertices, normals, uvs, indices, groups })\n}\n\nfunction cylinderArrays(radiusTop: number, radiusBottom: number, height: number, radialSegments: number, heightSegments: number, openEnded: boolean, thetaStart: number, thetaLength: number): Arrays {\n radialSegments = Math.floor(radialSegments)\n heightSegments = Math.floor(heightSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const groups: GeometryGroup[] = []\n let index = 0\n const indexArray: number[][] = []\n const halfHeight = height / 2\n let groupStart = 0\n\n const generateTorso = (): void => {\n let groupCount = 0\n const slope = (radiusBottom - radiusTop) / height\n for (let y = 0; y <= heightSegments; y++) {\n const indexRow: number[] = []\n const v = y / heightSegments\n const radius = v * (radiusBottom - radiusTop) + radiusTop\n for (let x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments\n const theta = u * thetaLength + thetaStart\n const sinTheta = Math.sin(theta)\n const cosTheta = Math.cos(theta)\n vertices.push(radius * sinTheta, -v * height + halfHeight, radius * cosTheta)\n const n = normalize3(sinTheta, slope, cosTheta)\n normals.push(n[0], n[1], n[2])\n uvs.push(u, 1 - v)\n indexRow.push(index++)\n }\n indexArray.push(indexRow)\n }\n for (let x = 0; x < radialSegments; x++) {\n for (let y = 0; y < heightSegments; y++) {\n const a = indexArray[y]![x]!\n const b = indexArray[y + 1]![x]!\n const c = indexArray[y + 1]![x + 1]!\n const d = indexArray[y]![x + 1]!\n indices.push(a, b, d)\n indices.push(b, c, d)\n groupCount += 6\n }\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex: 0 })\n groupStart += groupCount\n }\n\n const generateCap = (top: boolean): void => {\n const centerIndexStart = index\n let groupCount = 0\n const radius = top === true ? radiusTop : radiusBottom\n const sign = top === true ? 1 : -1\n for (let x = 1; x <= radialSegments; x++) {\n vertices.push(0, halfHeight * sign, 0)\n normals.push(0, sign, 0)\n uvs.push(0.5, 0.5)\n index++\n }\n const centerIndexEnd = index\n for (let x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments\n const theta = u * thetaLength + thetaStart\n const cosTheta = Math.cos(theta)\n const sinTheta = Math.sin(theta)\n vertices.push(radius * sinTheta, halfHeight * sign, radius * cosTheta)\n normals.push(0, sign, 0)\n uvs.push(cosTheta * 0.5 + 0.5, sinTheta * 0.5 * sign + 0.5)\n index++\n }\n for (let x = 0; x < radialSegments; x++) {\n const c = centerIndexStart + x\n const i = centerIndexEnd + x\n if (top === true) indices.push(i, i + 1, c)\n else indices.push(i + 1, i, c)\n groupCount += 3\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex: top === true ? 1 : 2 })\n groupStart += groupCount\n }\n\n generateTorso()\n if (openEnded === false) {\n if (radiusTop > 0) generateCap(true)\n if (radiusBottom > 0) generateCap(false)\n }\n return { vertices, normals, uvs, indices, groups }\n}\n\nexport function cylinder(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }\n return pack('CylinderGeometry', parameters, cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength))\n}\n\nexport function cone(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }\n return pack('ConeGeometry', parameters, cylinderArrays(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength))\n}\n\nexport function sphere(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI): PrimitiveBuffers {\n const parameters = { radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength }\n widthSegments = Math.max(3, Math.floor(widthSegments))\n heightSegments = Math.max(2, Math.floor(heightSegments))\n const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI)\n let index = 0\n const grid: number[][] = []\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let iy = 0; iy <= heightSegments; iy++) {\n const verticesRow: number[] = []\n const v = iy / heightSegments\n let uOffset = 0\n if (iy === 0 && thetaStart === 0) uOffset = 0.5 / widthSegments\n else if (iy === heightSegments && thetaEnd === Math.PI) uOffset = -0.5 / widthSegments\n for (let ix = 0; ix <= widthSegments; ix++) {\n const u = ix / widthSegments\n const x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)\n const y = radius * Math.cos(thetaStart + v * thetaLength)\n const z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)\n vertices.push(x, y, z)\n const n = normalize3(x, y, z)\n normals.push(n[0], n[1], n[2])\n uvs.push(u + uOffset, 1 - v)\n verticesRow.push(index++)\n }\n grid.push(verticesRow)\n }\n for (let iy = 0; iy < heightSegments; iy++) {\n for (let ix = 0; ix < widthSegments; ix++) {\n const a = grid[iy]![ix + 1]!\n const b = grid[iy]![ix]!\n const c = grid[iy + 1]![ix]!\n const d = grid[iy + 1]![ix + 1]!\n if (iy !== 0 || thetaStart > 0) indices.push(a, b, d)\n if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d)\n }\n }\n return pack('SphereGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function plane(width = 1, height = 1, widthSegments = 1, heightSegments = 1): PrimitiveBuffers {\n const parameters = { width, height, widthSegments, heightSegments }\n const widthHalf = width / 2\n const heightHalf = height / 2\n const gridX = Math.floor(widthSegments)\n const gridY = Math.floor(heightSegments)\n const gridX1 = gridX + 1\n const gridY1 = gridY + 1\n const segmentWidth = width / gridX\n const segmentHeight = height / gridY\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let iy = 0; iy < gridY1; iy++) {\n const y = iy * segmentHeight - heightHalf\n for (let ix = 0; ix < gridX1; ix++) {\n const x = ix * segmentWidth - widthHalf\n vertices.push(x, -y, 0)\n normals.push(0, 0, 1)\n uvs.push(ix / gridX)\n uvs.push(1 - iy / gridY)\n }\n }\n for (let iy = 0; iy < gridY; iy++) {\n for (let ix = 0; ix < gridX; ix++) {\n const a = ix + gridX1 * iy\n const b = ix + gridX1 * (iy + 1)\n const c = ix + 1 + gridX1 * (iy + 1)\n const d = ix + 1 + gridX1 * iy\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('PlaneGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function circle(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, segments, thetaStart, thetaLength }\n segments = Math.max(3, segments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n vertices.push(0, 0, 0)\n normals.push(0, 0, 1)\n uvs.push(0.5, 0.5)\n for (let s = 0, i = 3; s <= segments; s++, i += 3) {\n const segment = thetaStart + (s / segments) * thetaLength\n // the vector's z stays 0, as three's Vector3\n vertices.push(radius * Math.cos(segment), radius * Math.sin(segment), 0)\n normals.push(0, 0, 1)\n uvs.push(((vertices[i] as number) / radius + 1) / 2, ((vertices[i + 1] as number) / radius + 1) / 2)\n }\n for (let i = 1; i <= segments; i++) indices.push(i, i + 1, 0)\n return pack('CircleGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function ring(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength }\n thetaSegments = Math.max(3, thetaSegments)\n phiSegments = Math.max(1, phiSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n let radius = innerRadius\n const radiusStep = (outerRadius - innerRadius) / phiSegments\n for (let j = 0; j <= phiSegments; j++) {\n for (let i = 0; i <= thetaSegments; i++) {\n const segment = thetaStart + (i / thetaSegments) * thetaLength\n const x = radius * Math.cos(segment)\n const y = radius * Math.sin(segment)\n vertices.push(x, y, 0)\n normals.push(0, 0, 1)\n uvs.push((x / outerRadius + 1) / 2, (y / outerRadius + 1) / 2)\n }\n radius += radiusStep\n }\n for (let j = 0; j < phiSegments; j++) {\n const thetaSegmentLevel = j * (thetaSegments + 1)\n for (let i = 0; i < thetaSegments; i++) {\n const segment = i + thetaSegmentLevel\n const a = segment\n const b = segment + thetaSegments + 1\n const c = segment + thetaSegments + 2\n const d = segment + 1\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('RingGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function lathe(points: ReadonlyArray<readonly [number, number]>, segments = 12, phiStart = 0, phiLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { points: points.map(([x, y]) => ({ x, y })), segments, phiStart, phiLength }\n segments = Math.floor(segments)\n phiLength = Math.max(0, Math.min(Math.PI * 2, phiLength))\n const indices: number[] = []\n const vertices: number[] = []\n const uvs: number[] = []\n const initNormals: number[] = []\n const normals: number[] = []\n const inverseSegments = 1.0 / segments\n const normal = { x: 0, y: 0, z: 0 }\n const curNormal = { x: 0, y: 0, z: 0 }\n const prevNormal = { x: 0, y: 0, z: 0 }\n let dx = 0\n let dy = 0\n const last = points.length - 1\n const px = (j: number): number => (points[j] as readonly [number, number])[0]\n const py = (j: number): number => (points[j] as readonly [number, number])[1]\n const setNormalized = (): void => {\n const n = normalize3(normal.x, normal.y, normal.z)\n normal.x = n[0]\n normal.y = n[1]\n normal.z = n[2]\n }\n for (let j = 0; j <= last; j++) {\n if (j === 0) {\n dx = px(j + 1) - px(j)\n dy = py(j + 1) - py(j)\n normal.x = dy * 1.0\n normal.y = -dx\n normal.z = dy * 0.0\n prevNormal.x = normal.x\n prevNormal.y = normal.y\n prevNormal.z = normal.z\n setNormalized()\n initNormals.push(normal.x, normal.y, normal.z)\n } else if (j === last) {\n initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z)\n } else {\n dx = px(j + 1) - px(j)\n dy = py(j + 1) - py(j)\n normal.x = dy * 1.0\n normal.y = -dx\n normal.z = dy * 0.0\n curNormal.x = normal.x\n curNormal.y = normal.y\n curNormal.z = normal.z\n normal.x += prevNormal.x\n normal.y += prevNormal.y\n normal.z += prevNormal.z\n setNormalized()\n initNormals.push(normal.x, normal.y, normal.z)\n prevNormal.x = curNormal.x\n prevNormal.y = curNormal.y\n prevNormal.z = curNormal.z\n }\n }\n for (let i = 0; i <= segments; i++) {\n const phi = phiStart + i * inverseSegments * phiLength\n const sin = Math.sin(phi)\n const cos = Math.cos(phi)\n for (let j = 0; j <= last; j++) {\n vertices.push(px(j) * sin, py(j), px(j) * cos)\n uvs.push(i / segments, j / (points.length - 1))\n const x = (initNormals[3 * j + 0] as number) * sin\n const y = initNormals[3 * j + 1] as number\n const z = (initNormals[3 * j + 0] as number) * cos\n normals.push(x, y, z)\n }\n }\n for (let i = 0; i < segments; i++) {\n for (let j = 0; j < points.length - 1; j++) {\n const base = j + i * points.length\n const a = base\n const b = base + points.length\n const c = base + points.length + 1\n const d = base + 1\n indices.push(a, b, d)\n indices.push(c, d, b)\n }\n }\n return pack('LatheGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function torus(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, tube, radialSegments, tubularSegments, arc }\n radialSegments = Math.floor(radialSegments)\n tubularSegments = Math.floor(tubularSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let j = 0; j <= radialSegments; j++) {\n for (let i = 0; i <= tubularSegments; i++) {\n const u = (i / tubularSegments) * arc\n const v = (j / radialSegments) * Math.PI * 2\n const x = (radius + tube * Math.cos(v)) * Math.cos(u)\n const y = (radius + tube * Math.cos(v)) * Math.sin(u)\n const z = tube * Math.sin(v)\n vertices.push(x, y, z)\n const cx = radius * Math.cos(u)\n const cy = radius * Math.sin(u)\n const n = normalize3(x - cx, y - cy, z - 0)\n normals.push(n[0], n[1], n[2])\n uvs.push(i / tubularSegments)\n uvs.push(j / radialSegments)\n }\n }\n for (let j = 1; j <= radialSegments; j++) {\n for (let i = 1; i <= tubularSegments; i++) {\n const a = (tubularSegments + 1) * j + i - 1\n const b = (tubularSegments + 1) * (j - 1) + i - 1\n const c = (tubularSegments + 1) * (j - 1) + i\n const d = (tubularSegments + 1) * j + i\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('TorusGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n","import type { HoleSpec, PrimitiveBuffers, Vec3 } from '../types'\nimport { indexArray } from './three-generators'\n\n/**\n * A box (centred, `size = [w, h, d]`) minus rectangular prisms that go all the way through it along z: the cheap, exact boolean (walls with\n * windows and doors). The face is cut into a grid at every hole edge; each solid cell gets its front and back quads, and every cell edge between\n * solid and empty (a hole or the outside) gets a quad over the depth facing the empty side, so the outer sides and the reveals come out of the\n * same rule. Front uvs map the face to [0, 1]; side uvs run along the edge and the depth.\n */\nexport function difference(size: Vec3, subtract: readonly HoleSpec[]): PrimitiveBuffers {\n const [w, h, d] = size\n const hw = w / 2\n const hh = h / 2\n const hd = d / 2\n const holes = subtract\n .map((hole) => ({ x0: Math.max(-hw, Math.min(hole.min[0], hole.max[0])), x1: Math.min(hw, Math.max(hole.min[0], hole.max[0])), y0: Math.max(-hh, Math.min(hole.min[1], hole.max[1])), y1: Math.min(hh, Math.max(hole.min[1], hole.max[1])) }))\n .filter((hole) => hole.x1 > hole.x0 && hole.y1 > hole.y0)\n const cuts = (lo: number, hi: number, values: number[]): number[] => [...new Set([lo, hi, ...values.filter((v) => v > lo && v < hi)])].sort((a, b) => a - b)\n const xs = cuts(-hw, hw, holes.flatMap((hole) => [hole.x0, hole.x1]))\n const ys = cuts(-hh, hh, holes.flatMap((hole) => [hole.y0, hole.y1]))\n const nx = xs.length - 1\n const ny = ys.length - 1\n const solid = (i: number, j: number): boolean => {\n if (i < 0 || j < 0 || i >= nx || j >= ny) return false\n const cx = ((xs[i] as number) + (xs[i + 1] as number)) / 2\n const cy = ((ys[j] as number) + (ys[j + 1] as number)) / 2\n return !holes.some((hole) => cx > hole.x0 && cx < hole.x1 && cy > hole.y0 && cy < hole.y1)\n }\n const positions: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const indices: number[] = []\n const quad = (corners: readonly (readonly [number, number, number])[], normal: readonly [number, number, number], uv: readonly (readonly [number, number])[]): void => {\n const base = positions.length / 3\n for (let k = 0; k < 4; k++) {\n positions.push(...(corners[k] as [number, number, number]))\n normals.push(...normal)\n uvs.push(...(uv[k] as [number, number]))\n }\n indices.push(base, base + 1, base + 2, base, base + 2, base + 3)\n }\n const fu = (x: number): number => (x + hw) / w\n const fv = (y: number): number => (y + hh) / h\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n if (!solid(i, j)) continue\n const x0 = xs[i] as number\n const x1 = xs[i + 1] as number\n const y0 = ys[j] as number\n const y1 = ys[j + 1] as number\n quad([[x0, y0, hd], [x1, y0, hd], [x1, y1, hd], [x0, y1, hd]], [0, 0, 1], [[fu(x0), fv(y0)], [fu(x1), fv(y0)], [fu(x1), fv(y1)], [fu(x0), fv(y1)]])\n quad([[x1, y0, -hd], [x0, y0, -hd], [x0, y1, -hd], [x1, y1, -hd]], [0, 0, -1], [[1 - fu(x1), fv(y0)], [1 - fu(x0), fv(y0)], [1 - fu(x0), fv(y1)], [1 - fu(x1), fv(y1)]])\n const zu = (z: number): number => (z + hd) / d\n if (!solid(i - 1, j)) quad([[x0, y0, -hd], [x0, y0, hd], [x0, y1, hd], [x0, y1, -hd]], [-1, 0, 0], [[zu(-hd), fv(y0)], [zu(hd), fv(y0)], [zu(hd), fv(y1)], [zu(-hd), fv(y1)]])\n if (!solid(i + 1, j)) quad([[x1, y0, hd], [x1, y0, -hd], [x1, y1, -hd], [x1, y1, hd]], [1, 0, 0], [[zu(hd), fv(y0)], [zu(-hd), fv(y0)], [zu(-hd), fv(y1)], [zu(hd), fv(y1)]])\n if (!solid(i, j - 1)) quad([[x0, y0, -hd], [x1, y0, -hd], [x1, y0, hd], [x0, y0, hd]], [0, -1, 0], [[fu(x0), zu(-hd)], [fu(x1), zu(-hd)], [fu(x1), zu(hd)], [fu(x0), zu(hd)]])\n if (!solid(i, j + 1)) quad([[x0, y1, hd], [x1, y1, hd], [x1, y1, -hd], [x0, y1, -hd]], [0, 1, 0], [[fu(x0), zu(hd)], [fu(x1), zu(hd)], [fu(x1), zu(-hd)], [fu(x0), zu(-hd)]])\n }\n }\n return {\n type: 'BufferGeometry',\n parameters: { size: [w, h, d], subtract: holes.map((hole) => ({ min: [hole.x0, hole.y0], max: [hole.x1, hole.y1] })) },\n positions: new Float32Array(positions),\n normals: new Float32Array(normals),\n uvs: new Float32Array(uvs),\n indices: indexArray(indices),\n groups: [],\n }\n}\n","// Copy of three.js r160 src/extras/Earcut.js (MIT), itself a port of mapbox/earcut v2.2.4 (ISC), with types added and the logic kept as is so triangulation matches three\n/**\n * Port from https://github.com/mapbox/earcut (v2.2.4)\n */\n\nconst Earcut = {\n\n\ttriangulate: function ( data: ArrayLike<number>, holeIndices?: ArrayLike<number> | null, dim = 2 ): number[] {\n\n\t\tconst hasHoles = holeIndices && holeIndices.length;\n\t\tconst outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;\n\t\tlet outerNode = linkedList( data, 0, outerLen, dim, true );\n\t\tconst triangles: number[] = [];\n\n\t\tif ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;\n\n\t\tlet minX, minY, maxX, maxY, x, y, invSize;\n\n\t\tif ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );\n\n\t\t// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n\t\tif ( data.length > 80 * dim ) {\n\n\t\t\tminX = maxX = data[ 0 ];\n\t\t\tminY = maxY = data[ 1 ];\n\n\t\t\tfor ( let i = dim; i < outerLen; i += dim ) {\n\n\t\t\t\tx = data[ i ];\n\t\t\t\ty = data[ i + 1 ];\n\t\t\t\tif ( x < minX ) minX = x;\n\t\t\t\tif ( y < minY ) minY = y;\n\t\t\t\tif ( x > maxX ) maxX = x;\n\t\t\t\tif ( y > maxY ) maxY = y;\n\n\t\t\t}\n\n\t\t\t// minX, minY and invSize are later used to transform coords into integers for z-order calculation\n\t\t\tinvSize = Math.max( maxX - minX, maxY - minY );\n\t\t\tinvSize = invSize !== 0 ? 32767 / invSize : 0;\n\n\t\t}\n\n\t\tearcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );\n\n\t\treturn triangles;\n\n\t}\n\n};\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList( data: ArrayLike<number>, start: number, end: number, dim: number, clockwise: boolean ): EarNode | undefined {\n\n\tlet i: number, last: EarNode | undefined;\n\n\tif ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {\n\n\t\tfor ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t} else {\n\n\t\tfor ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t}\n\n\tif ( last && equals( last, last.next ) ) {\n\n\t\tremoveNode( last );\n\t\tlast = last.next;\n\n\t}\n\n\treturn last;\n\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints( start: EarNode | null | undefined, end?: EarNode | null ): EarNode | null | undefined {\n\n\tif ( ! start ) return start;\n\tif ( ! end ) end = start;\n\n\tlet p = start,\n\t\tagain;\n\tdo {\n\n\t\tagain = false;\n\n\t\tif ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {\n\n\t\t\tremoveNode( p );\n\t\t\tp = end = p.prev;\n\t\t\tif ( p === p.next ) break;\n\t\t\tagain = true;\n\n\t\t} else {\n\n\t\t\tp = p.next;\n\n\t\t}\n\n\t} while ( again || p !== end );\n\n\treturn end;\n\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked( ear: EarNode | null | undefined, triangles: number[], dim: number, minX: number | undefined, minY: number | undefined, invSize: number | undefined, pass: number ): void {\n\n\tif ( ! ear ) return;\n\n\t// interlink polygon nodes in z-order\n\tif ( ! pass && invSize ) indexCurve( ear, minX as number, minY as number, invSize ); // set with invSize\n\n\tlet stop = ear,\n\t\tprev, next;\n\n\t// iterate through ears, slicing them one by one\n\twhile ( ear.prev !== ear.next ) {\n\n\t\tprev = ear.prev;\n\t\tnext = ear.next;\n\n\t\tif ( invSize ? isEarHashed( ear, minX as number, minY as number, invSize ) : isEar( ear ) ) {\n\n\t\t\t// cut off the triangle\n\t\t\ttriangles.push( prev.i / dim | 0 );\n\t\t\ttriangles.push( ear.i / dim | 0 );\n\t\t\ttriangles.push( next.i / dim | 0 );\n\n\t\t\tremoveNode( ear );\n\n\t\t\t// skipping the next vertex leads to less sliver triangles\n\t\t\tear = next.next;\n\t\t\tstop = next.next;\n\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tear = next;\n\n\t\t// if we looped through the whole remaining polygon and can't find any more ears\n\t\tif ( ear === stop ) {\n\n\t\t\t// try filtering points and slicing again\n\t\t\tif ( ! pass ) {\n\n\t\t\t\tearcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );\n\n\t\t\t\t// if this didn't work, try curing all small self-intersections locally\n\n\t\t\t} else if ( pass === 1 ) {\n\n\t\t\t\tear = cureLocalIntersections( filterPoints( ear )!, triangles, dim );\n\t\t\t\tearcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );\n\n\t\t\t\t// as a last resort, try splitting the remaining polygon into two\n\n\t\t\t} else if ( pass === 2 ) {\n\n\t\t\t\tsplitEarcut( ear, triangles, dim, minX, minY, invSize );\n\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar( ear: EarNode ): boolean {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\t// now make sure we don't have other points inside the potential ear\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\tlet p = c.next;\n\twhile ( p !== a ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&\n\t\t\tarea( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.next;\n\n\t}\n\n\treturn true;\n\n}\n\nfunction isEarHashed( ear: EarNode, minX: number, minY: number, invSize: number ): boolean {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\t// z-order range for the current triangle bbox;\n\tconst minZ = zOrder( x0, y0, minX, minY, invSize ),\n\t\tmaxZ = zOrder( x1, y1, minX, minY, invSize );\n\n\tlet p = ear.prevZ,\n\t\tn = ear.nextZ;\n\n\t// look for points inside the triangle in both directions\n\twhile ( p && p.z >= minZ && n && n.z <= maxZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\t// look for remaining points in decreasing z-order\n\twhile ( p && p.z >= minZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t}\n\n\t// look for remaining points in increasing z-order\n\twhile ( n && n.z <= maxZ ) {\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\treturn true;\n\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections( start: EarNode, triangles: number[], dim: number ): EarNode {\n\n\tlet p = start;\n\tdo {\n\n\t\tconst a = p.prev,\n\t\t\tb = p.next.next;\n\n\t\tif ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {\n\n\t\t\ttriangles.push( a.i / dim | 0 );\n\t\t\ttriangles.push( p.i / dim | 0 );\n\t\t\ttriangles.push( b.i / dim | 0 );\n\n\t\t\t// remove two nodes involved\n\t\t\tremoveNode( p );\n\t\t\tremoveNode( p.next );\n\n\t\t\tp = start = b;\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn filterPoints( p )!;\n\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut( start: EarNode, triangles: number[], dim: number, minX: number | undefined, minY: number | undefined, invSize: number | undefined ): void {\n\n\t// look for a valid diagonal that divides the polygon into two\n\tlet a = start;\n\tdo {\n\n\t\tlet b = a.next.next;\n\t\twhile ( b !== a.prev ) {\n\n\t\t\tif ( a.i !== b.i && isValidDiagonal( a, b ) ) {\n\n\t\t\t\t// split the polygon in two by the diagonal\n\t\t\t\tlet c = splitPolygon( a, b );\n\n\t\t\t\t// filter colinear points around the cuts\n\t\t\t\ta = filterPoints( a, a.next )!;\n\t\t\t\tc = filterPoints( c, c.next )!;\n\n\t\t\t\t// run earcut on each half\n\t\t\t\tearcutLinked( a, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\tearcutLinked( c, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tb = b.next;\n\n\t\t}\n\n\t\ta = a.next;\n\n\t} while ( a !== start );\n\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles( data: ArrayLike<number>, holeIndices: ArrayLike<number>, outerNode: EarNode, dim: number ): EarNode {\n\n\tconst queue: EarNode[] = [];\n\tlet i, len, start, end, list;\n\n\tfor ( i = 0, len = holeIndices.length; i < len; i ++ ) {\n\n\t\tstart = holeIndices[ i ] * dim;\n\t\tend = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;\n\t\tlist = linkedList( data, start, end, dim, false )!;\n\t\tif ( list === list.next ) list.steiner = true;\n\t\tqueue.push( getLeftmost( list ) );\n\n\t}\n\n\tqueue.sort( compareX );\n\n\t// process holes from left to right\n\tfor ( i = 0; i < queue.length; i ++ ) {\n\n\t\touterNode = eliminateHole( queue[ i ], outerNode );\n\n\t}\n\n\treturn outerNode;\n\n}\n\nfunction compareX( a: EarNode, b: EarNode ): number {\n\n\treturn a.x - b.x;\n\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole( hole: EarNode, outerNode: EarNode ): EarNode {\n\n\tconst bridge = findHoleBridge( hole, outerNode );\n\tif ( ! bridge ) {\n\n\t\treturn outerNode;\n\n\t}\n\n\tconst bridgeReverse = splitPolygon( bridge, hole );\n\n\t// filter collinear points around the cuts\n\tfilterPoints( bridgeReverse, bridgeReverse.next );\n\treturn filterPoints( bridge, bridge.next )!;\n\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge( hole: EarNode, outerNode: EarNode ): EarNode | null {\n\n\tlet p = outerNode,\n\t\tqx = - Infinity,\n\t\tm;\n\n\tconst hx = hole.x, hy = hole.y;\n\n\t// find a segment intersected by a ray from the hole's leftmost point to the left;\n\t// segment's endpoint with lesser x will be potential connection point\n\tdo {\n\n\t\tif ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {\n\n\t\t\tconst x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );\n\t\t\tif ( x <= hx && x > qx ) {\n\n\t\t\t\tqx = x;\n\t\t\t\tm = p.x < p.next.x ? p : p.next;\n\t\t\t\tif ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== outerNode );\n\n\tif ( ! m ) return null;\n\n\t// look for points inside the triangle of hole point, segment intersection and endpoint;\n\t// if there are no points found, we have a valid connection;\n\t// otherwise choose the point of the minimum angle with the ray as connection point\n\n\tconst stop = m,\n\t\tmx = m.x,\n\t\tmy = m.y;\n\tlet tanMin = Infinity, tan;\n\n\tp = m;\n\n\tdo {\n\n\t\tif ( hx >= p.x && p.x >= mx && hx !== p.x &&\n\t\t\t\tpointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {\n\n\t\t\ttan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential\n\n\t\t\tif ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {\n\n\t\t\t\tm = p;\n\t\t\t\ttanMin = tan;\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== stop );\n\n\treturn m;\n\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector( m: EarNode, p: EarNode ): boolean {\n\n\treturn area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;\n\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve( start: EarNode, minX: number, minY: number, invSize: number ): void {\n\n\tlet p = start;\n\tdo {\n\n\t\tif ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );\n\t\tp.prevZ = p.prev;\n\t\tp.nextZ = p.next;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\tp.prevZ!.nextZ = null;\n\tp.prevZ = null;\n\n\tsortLinked( p );\n\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked( list: EarNode | null ): EarNode | null {\n\n\tlet i, p: EarNode | null, q: EarNode | null, e: EarNode, tail: EarNode | null, numMerges, pSize, qSize,\n\t\tinSize = 1;\n\n\tdo {\n\n\t\tp = list;\n\t\tlist = null;\n\t\ttail = null;\n\t\tnumMerges = 0;\n\n\t\twhile ( p ) {\n\n\t\t\tnumMerges ++;\n\t\t\tq = p;\n\t\t\tpSize = 0;\n\t\t\tfor ( i = 0; i < inSize; i ++ ) {\n\n\t\t\t\tpSize ++;\n\t\t\t\tq = q!.nextZ;\n\t\t\t\tif ( ! q ) break;\n\n\t\t\t}\n\n\t\t\tqSize = inSize;\n\n\t\t\twhile ( pSize > 0 || ( qSize > 0 && q ) ) {\n\n\t\t\t\tif ( pSize !== 0 && ( qSize === 0 || ! q || p!.z <= q.z ) ) {\n\n\t\t\t\t\te = p!;\n\t\t\t\t\tp = p!.nextZ;\n\t\t\t\t\tpSize --;\n\n\t\t\t\t} else {\n\n\t\t\t\t\te = q!;\n\t\t\t\t\tq = q!.nextZ;\n\t\t\t\t\tqSize --;\n\n\t\t\t\t}\n\n\t\t\t\tif ( tail ) tail.nextZ = e;\n\t\t\t\telse list = e;\n\n\t\t\t\te.prevZ = tail;\n\t\t\t\ttail = e;\n\n\t\t\t}\n\n\t\t\tp = q;\n\n\t\t}\n\n\t\ttail!.nextZ = null;\n\t\tinSize *= 2;\n\n\t} while ( numMerges > 1 );\n\n\treturn list;\n\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder( x: number, y: number, minX: number, minY: number, invSize: number ): number {\n\n\t// coords are transformed into non-negative 15-bit integer range\n\tx = ( x - minX ) * invSize | 0;\n\ty = ( y - minY ) * invSize | 0;\n\n\tx = ( x | ( x << 8 ) ) & 0x00FF00FF;\n\tx = ( x | ( x << 4 ) ) & 0x0F0F0F0F;\n\tx = ( x | ( x << 2 ) ) & 0x33333333;\n\tx = ( x | ( x << 1 ) ) & 0x55555555;\n\n\ty = ( y | ( y << 8 ) ) & 0x00FF00FF;\n\ty = ( y | ( y << 4 ) ) & 0x0F0F0F0F;\n\ty = ( y | ( y << 2 ) ) & 0x33333333;\n\ty = ( y | ( y << 1 ) ) & 0x55555555;\n\n\treturn x | ( y << 1 );\n\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost( start: EarNode ): EarNode {\n\n\tlet p = start,\n\t\tleftmost = start;\n\tdo {\n\n\t\tif ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn leftmost;\n\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle( ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number ): boolean {\n\n\treturn ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&\n ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&\n ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );\n\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal( a: EarNode, b: EarNode ): boolean | number { // truthy: `area` can be the answer\n\n\treturn a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges\n ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible\n ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors\n equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case\n\n}\n\n// signed area of a triangle\nfunction area( p: EarNode, q: EarNode, r: EarNode ): number {\n\n\treturn ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );\n\n}\n\n// check if two points are equal\nfunction equals( p1: EarNode, p2: EarNode ): boolean {\n\n\treturn p1.x === p2.x && p1.y === p2.y;\n\n}\n\n// check if two segments intersect\nfunction intersects( p1: EarNode, q1: EarNode, p2: EarNode, q2: EarNode ): boolean {\n\n\tconst o1 = sign( area( p1, q1, p2 ) );\n\tconst o2 = sign( area( p1, q1, q2 ) );\n\tconst o3 = sign( area( p2, q2, p1 ) );\n\tconst o4 = sign( area( p2, q2, q1 ) );\n\n\tif ( o1 !== o2 && o3 !== o4 ) return true; // general case\n\n\tif ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n\tif ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n\tif ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n\tif ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n\treturn false;\n\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment( p: EarNode, q: EarNode, r: EarNode ): boolean {\n\n\treturn q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );\n\n}\n\nfunction sign( num: number ): number {\n\n\treturn num > 0 ? 1 : num < 0 ? - 1 : 0;\n\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon( a: EarNode, b: EarNode ): boolean {\n\n\tlet p = a;\n\tdo {\n\n\t\tif ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n\t\t\tintersects( p, p.next, a, b ) ) return true;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn false;\n\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside( a: EarNode, b: EarNode ): boolean {\n\n\treturn area( a.prev, a, a.next ) < 0 ?\n\t\tarea( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :\n\t\tarea( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;\n\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside( a: EarNode, b: EarNode ): boolean {\n\n\tlet p = a,\n\t\tinside = false;\n\tconst px = ( a.x + b.x ) / 2,\n\t\tpy = ( a.y + b.y ) / 2;\n\tdo {\n\n\t\tif ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&\n\t\t\t( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )\n\t\t\tinside = ! inside;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn inside;\n\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon( a: EarNode, b: EarNode ): EarNode {\n\n\tconst a2 = new Node( a.i, a.x, a.y ),\n\t\tb2 = new Node( b.i, b.x, b.y ),\n\t\tan = a.next,\n\t\tbp = b.prev;\n\n\ta.next = b;\n\tb.prev = a;\n\n\ta2.next = an;\n\tan.prev = a2;\n\n\tb2.next = a2;\n\ta2.prev = b2;\n\n\tbp.next = b2;\n\tb2.prev = bp;\n\n\treturn b2;\n\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode( i: number, x: number, y: number, last: EarNode | null | undefined ): EarNode {\n\n\tconst p = new Node( i, x, y );\n\n\tif ( ! last ) {\n\n\t\tp.prev = p;\n\t\tp.next = p;\n\n\t} else {\n\n\t\tp.next = last.next;\n\t\tp.prev = last;\n\t\tlast.next.prev = p;\n\t\tlast.next = p;\n\n\t}\n\n\treturn p;\n\n}\n\nfunction removeNode( p: EarNode ): void {\n\n\tp.next.prev = p.prev;\n\tp.prev.next = p.next;\n\n\tif ( p.prevZ ) p.prevZ.nextZ = p.nextZ;\n\tif ( p.nextZ ) p.nextZ.prevZ = p.prevZ;\n\n}\n\nclass Node {\n\n\t// vertex index in coordinates array\n\tdeclare i: number;\n\t// vertex coordinates\n\tdeclare x: number;\n\tdeclare y: number;\n\t// previous and next vertex nodes in a polygon ring (set as soon as the node is linked: a node in a ring always has both)\n\tdeclare prev: EarNode;\n\tdeclare next: EarNode;\n\t// z-order curve value\n\tdeclare z: number;\n\t// previous and next nodes in z-order\n\tdeclare prevZ: EarNode | null;\n\tdeclare nextZ: EarNode | null;\n\t// indicates whether this is a steiner point\n\tdeclare steiner: boolean;\n\n\tconstructor( i: number, x: number, y: number ) {\n\n\t\t// vertex index in coordinates array\n\t\tthis.i = i;\n\n\t\t// vertex coordinates\n\t\tthis.x = x;\n\t\tthis.y = y;\n\n\t\t// previous and next vertex nodes in a polygon ring\n\t\tthis.prev = null as unknown as EarNode;\n\t\tthis.next = null as unknown as EarNode;\n\n\t\t// z-order curve value\n\t\tthis.z = 0;\n\n\t\t// previous and next nodes in z-order\n\t\tthis.prevZ = null;\n\t\tthis.nextZ = null;\n\n\t\t// indicates whether this is a steiner point\n\t\tthis.steiner = false;\n\n\t}\n\n}\n\n/** A vertex of the polygon ring. */\ntype EarNode = Node;\n\nfunction signedArea( data: ArrayLike<number>, start: number, end: number, dim: number ): number {\n\n\tlet sum = 0;\n\tfor ( let i = start, j = end - dim; i < end; i += dim ) {\n\n\t\tsum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );\n\t\tj = i;\n\n\t}\n\n\treturn sum;\n\n}\n\nexport { Earcut };\n","/*\n * three.js r160 `ExtrudeGeometry` (MIT) for straight-edged shapes, ported line by line: the outline is sampled as `Shape.extractPoints` samples a\n * path of `LineCurve`s, triangulated by three's `ShapeUtils.triangulateShape` (Earcut), bevelled and walled in the same order, with the\n * `WorldUVGenerator` uvs and `computeVertexNormals` on the Float32 positions. Path extrusion (`extrudePath`) is not supported.\n */\nimport type { BevelSpec, GeometryGroup, PrimitiveBuffers, ShapeOutline, Vec2 } from '../types'\nimport { Earcut } from './earcut'\n\ninterface P {\n x: number\n y: number\n}\n\nconst equals = (a: P, b: P): boolean => a.x === b.x && a.y === b.y\n\n/** `LineCurve.getPoint(t)`. */\nconst linePoint = (v1: P, v2: P, t: number): P => (t === 1 ? { x: v2.x, y: v2.y } : { x: (v2.x - v1.x) * t + v1.x, y: (v2.y - v1.y) * t + v1.y })\n\n/** `Path.setFromPoints(points).getPoints()`: one `LineCurve` per edge, resolution 1, consecutive duplicates dropped, not closed. */\nfunction pathPoints(points: readonly Vec2[]): P[] {\n const out: P[] = []\n let last: P | undefined\n for (let i = 1; i < points.length; i++) {\n const v1 = { x: (points[i - 1] as Vec2)[0], y: (points[i - 1] as Vec2)[1] }\n const v2 = { x: (points[i] as Vec2)[0], y: (points[i] as Vec2)[1] }\n for (let d = 0; d <= 1; d++) {\n const point = linePoint(v1, v2, d / 1)\n if (last && equals(last, point)) continue\n out.push(point)\n last = point\n }\n }\n return out\n}\n\nfunction area(contour: readonly P[]): number {\n const n = contour.length\n let a = 0.0\n for (let p = n - 1, q = 0; q < n; p = q++) a += (contour[p] as P).x * (contour[q] as P).y - (contour[q] as P).x * (contour[p] as P).y\n return a * 0.5\n}\nconst isClockWise = (pts: readonly P[]): boolean => area(pts) < 0\n\nfunction removeDupEndPts(points: P[]): void {\n const l = points.length\n if (l > 2 && equals(points[l - 1] as P, points[0] as P)) points.pop()\n}\n\nfunction triangulateShape(contour: P[], holes: P[][]): number[][] {\n const vertices: number[] = []\n const holeIndices: number[] = []\n const faces: number[][] = []\n removeDupEndPts(contour)\n for (const p of contour) vertices.push(p.x, p.y)\n let holeIndex = contour.length\n holes.forEach(removeDupEndPts)\n for (let i = 0; i < holes.length; i++) {\n holeIndices.push(holeIndex)\n holeIndex += (holes[i] as P[]).length\n for (const p of holes[i] as P[]) vertices.push(p.x, p.y)\n }\n const triangles: number[] = Earcut.triangulate(vertices, holeIndices)\n for (let i = 0; i < triangles.length; i += 3) faces.push(triangles.slice(i, i + 3))\n return faces\n}\n\n/** `BufferGeometry.computeVertexNormals` for non-indexed Float32 positions, then `normalizeNormals`, both stored as Float32. */\nexport function computeVertexNormals(positions: Float32Array, indices?: ArrayLike<number>): Float32Array {\n const normals = new Float32Array(positions.length)\n const get = (array: Float32Array, i: number): [number, number, number] => [array[i * 3] as number, array[i * 3 + 1] as number, array[i * 3 + 2] as number]\n const face = (vA: number, vB: number, vC: number): [number, number, number] => {\n const pA = get(positions, vA)\n const pB = get(positions, vB)\n const pC = get(positions, vC)\n const cb = [pC[0] - pB[0], pC[1] - pB[1], pC[2] - pB[2]] as const\n const ab = [pA[0] - pB[0], pA[1] - pB[1], pA[2] - pB[2]] as const\n // Vector3.cross\n return [cb[1] * ab[2] - cb[2] * ab[1], cb[2] * ab[0] - cb[0] * ab[2], cb[0] * ab[1] - cb[1] * ab[0]]\n }\n const set = (i: number, x: number, y: number, z: number): void => {\n normals[i * 3] = x\n normals[i * 3 + 1] = y\n normals[i * 3 + 2] = z\n }\n if (indices) {\n for (let i = 0; i < indices.length; i += 3) {\n const vA = indices[i] as number\n const vB = indices[i + 1] as number\n const vC = indices[i + 2] as number\n const cb = face(vA, vB, vC)\n for (const v of [vA, vB, vC]) {\n const n = get(normals, v)\n set(v, n[0] + cb[0], n[1] + cb[1], n[2] + cb[2])\n }\n }\n } else {\n for (let i = 0; i < positions.length / 3; i += 3) {\n const cb = face(i, i + 1, i + 2)\n set(i, cb[0], cb[1], cb[2])\n set(i + 1, cb[0], cb[1], cb[2])\n set(i + 2, cb[0], cb[1], cb[2])\n }\n }\n for (let i = 0; i < normals.length / 3; i++) {\n const [x, y, z] = get(normals, i)\n const s = 1 / (Math.sqrt(x * x + y * y + z * z) || 1)\n set(i, x * s, y * s, z * s)\n }\n return normals\n}\n\nexport function extrude(outline: ShapeOutline, depth = 1, steps = 1, bevel: false | BevelSpec | undefined = undefined): PrimitiveBuffers {\n const parameters = { shape: outline, depth, steps, bevel: bevel ?? {} }\n const verticesArray: number[] = []\n const uvArray: number[] = []\n const groups: GeometryGroup[] = []\n const placeholder: number[] = []\n\n const bevelEnabled = bevel !== false\n const spec: BevelSpec = bevel === false || bevel === undefined ? {} : bevel\n let bevelThickness = spec.thickness !== undefined ? spec.thickness : 0.2\n let bevelSize = spec.size !== undefined ? spec.size : bevelThickness - 0.1\n let bevelOffset = spec.offset !== undefined ? spec.offset : 0\n let bevelSegments = spec.segments !== undefined ? spec.segments : 3\n if (!bevelEnabled) {\n bevelSegments = 0\n bevelThickness = 0\n bevelSize = 0\n bevelOffset = 0\n }\n\n let vertices = pathPoints(outline.outer)\n const holes = (outline.holes ?? []).map(pathPoints)\n const reverse = !isClockWise(vertices)\n if (reverse) {\n vertices = vertices.reverse()\n for (let h = 0; h < holes.length; h++) {\n const ahole = holes[h] as P[]\n if (isClockWise(ahole)) holes[h] = ahole.reverse()\n }\n }\n const faces = triangulateShape(vertices, holes)\n const contour = vertices\n for (const ahole of holes) vertices = vertices.concat(ahole)\n\n const scalePt2 = (pt: P, vec: P, size: number): P => ({ x: pt.x + vec.x * size, y: pt.y + vec.y * size })\n const vlen = vertices.length\n const flen = faces.length\n\n const getBevelVec = (inPt: P, inPrev: P, inNext: P): P => {\n let vTransX: number\n let vTransY: number\n let shrinkBy: number\n const vPrevX = inPt.x - inPrev.x\n const vPrevY = inPt.y - inPrev.y\n const vNextX = inNext.x - inPt.x\n const vNextY = inNext.y - inPt.y\n const vPrevLensq = vPrevX * vPrevX + vPrevY * vPrevY\n const collinear0 = vPrevX * vNextY - vPrevY * vNextX\n if (Math.abs(collinear0) > Number.EPSILON) {\n const vPrevLen = Math.sqrt(vPrevLensq)\n const vNextLen = Math.sqrt(vNextX * vNextX + vNextY * vNextY)\n const ptPrevShiftX = inPrev.x - vPrevY / vPrevLen\n const ptPrevShiftY = inPrev.y + vPrevX / vPrevLen\n const ptNextShiftX = inNext.x - vNextY / vNextLen\n const ptNextShiftY = inNext.y + vNextX / vNextLen\n const sf = ((ptNextShiftX - ptPrevShiftX) * vNextY - (ptNextShiftY - ptPrevShiftY) * vNextX) / (vPrevX * vNextY - vPrevY * vNextX)\n vTransX = ptPrevShiftX + vPrevX * sf - inPt.x\n vTransY = ptPrevShiftY + vPrevY * sf - inPt.y\n const vTransLensq = vTransX * vTransX + vTransY * vTransY\n if (vTransLensq <= 2) return { x: vTransX, y: vTransY }\n shrinkBy = Math.sqrt(vTransLensq / 2)\n } else {\n let directionEq = false\n if (vPrevX > Number.EPSILON) {\n if (vNextX > Number.EPSILON) directionEq = true\n } else if (vPrevX < -Number.EPSILON) {\n if (vNextX < -Number.EPSILON) directionEq = true\n } else if (Math.sign(vPrevY) === Math.sign(vNextY)) {\n directionEq = true\n }\n if (directionEq) {\n vTransX = -vPrevY\n vTransY = vPrevX\n shrinkBy = Math.sqrt(vPrevLensq)\n } else {\n vTransX = vPrevX\n vTransY = vPrevY\n shrinkBy = Math.sqrt(vPrevLensq / 2)\n }\n }\n return { x: vTransX / shrinkBy, y: vTransY / shrinkBy }\n }\n\n const movements = (ring: readonly P[]): P[] => {\n const out: P[] = []\n for (let i = 0, il = ring.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {\n if (j === il) j = 0\n if (k === il) k = 0\n out[i] = getBevelVec(ring[i] as P, ring[j] as P, ring[k] as P)\n }\n return out\n }\n const contourMovements = movements(contour)\n const holesMovements: P[][] = []\n let verticesMovements = contourMovements.concat()\n for (const ahole of holes) {\n const oneHoleMovements = movements(ahole)\n holesMovements.push(oneHoleMovements)\n verticesMovements = verticesMovements.concat(oneHoleMovements)\n }\n\n const v = (x: number, y: number, z: number): void => {\n placeholder.push(x)\n placeholder.push(y)\n placeholder.push(z)\n }\n const bevelLayer = (b: number, zOf: (z: number) => number): void => {\n const t = b / bevelSegments\n const z = bevelThickness * Math.cos((t * Math.PI) / 2)\n const bs = bevelSize * Math.sin((t * Math.PI) / 2) + bevelOffset\n for (let i = 0; i < contour.length; i++) {\n const vert = scalePt2(contour[i] as P, contourMovements[i] as P, bs)\n v(vert.x, vert.y, zOf(z))\n }\n for (let h = 0; h < holes.length; h++) {\n const ahole = holes[h] as P[]\n const oneHoleMovements = holesMovements[h] as P[]\n for (let i = 0; i < ahole.length; i++) {\n const vert = scalePt2(ahole[i] as P, oneHoleMovements[i] as P, bs)\n v(vert.x, vert.y, zOf(z))\n }\n }\n }\n for (let b = 0; b < bevelSegments; b++) bevelLayer(b, (z) => -z)\n const bs = bevelSize + bevelOffset\n for (let i = 0; i < vlen; i++) {\n const vert = bevelEnabled ? scalePt2(vertices[i] as P, verticesMovements[i] as P, bs) : (vertices[i] as P)\n v(vert.x, vert.y, 0)\n }\n for (let s = 1; s <= steps; s++) {\n for (let i = 0; i < vlen; i++) {\n const vert = bevelEnabled ? scalePt2(vertices[i] as P, verticesMovements[i] as P, bs) : (vertices[i] as P)\n v(vert.x, vert.y, (depth / steps) * s)\n }\n }\n for (let b = bevelSegments - 1; b >= 0; b--) bevelLayer(b, (z) => depth + z)\n\n const addVertex = (index: number): void => {\n verticesArray.push(placeholder[index * 3 + 0] as number)\n verticesArray.push(placeholder[index * 3 + 1] as number)\n verticesArray.push(placeholder[index * 3 + 2] as number)\n }\n const addUV = (x: number, y: number): void => {\n uvArray.push(x)\n uvArray.push(y)\n }\n const at = (index: number, axis: number): number => verticesArray[index * 3 + axis] as number\n const f3 = (a: number, b: number, c: number): void => {\n addVertex(a)\n addVertex(b)\n addVertex(c)\n const nextIndex = verticesArray.length / 3\n for (const index of [nextIndex - 3, nextIndex - 2, nextIndex - 1]) addUV(at(index, 0), at(index, 1))\n }\n const f4 = (a: number, b: number, c: number, d: number): void => {\n addVertex(a)\n addVertex(b)\n addVertex(d)\n addVertex(b)\n addVertex(c)\n addVertex(d)\n const nextIndex = verticesArray.length / 3\n const iA = nextIndex - 6\n const iB = nextIndex - 3\n const iC = nextIndex - 2\n const iD = nextIndex - 1\n const byX = Math.abs(at(iA, 1) - at(iB, 1)) < Math.abs(at(iA, 0) - at(iB, 0))\n const uv = (index: number): [number, number] => [byX ? at(index, 0) : at(index, 1), 1 - at(index, 2)]\n const uvs = [uv(iA), uv(iB), uv(iC), uv(iD)]\n for (const k of [0, 1, 3, 1, 2, 3]) addUV(...(uvs[k] as [number, number]))\n }\n\n // lid faces\n let start = verticesArray.length / 3\n if (bevelEnabled) {\n let offset = 0\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[2] as number) + offset, (face[1] as number) + offset, (face[0] as number) + offset)\n }\n const layer = steps + bevelSegments * 2\n offset = vlen * layer\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[0] as number) + offset, (face[1] as number) + offset, (face[2] as number) + offset)\n }\n } else {\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3(face[2] as number, face[1] as number, face[0] as number)\n }\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[0] as number) + vlen * steps, (face[1] as number) + vlen * steps, (face[2] as number) + vlen * steps)\n }\n }\n groups.push({ start, count: verticesArray.length / 3 - start, materialIndex: 0 })\n\n // side faces\n start = verticesArray.length / 3\n const sidewalls = (ring: readonly P[], layeroffset: number): void => {\n let i = ring.length\n while (--i >= 0) {\n const j = i\n let k = i - 1\n if (k < 0) k = ring.length - 1\n for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {\n const slen1 = vlen * s\n const slen2 = vlen * (s + 1)\n f4(layeroffset + j + slen1, layeroffset + k + slen1, layeroffset + k + slen2, layeroffset + j + slen2)\n }\n }\n }\n let layeroffset = 0\n sidewalls(contour, layeroffset)\n layeroffset += contour.length\n for (const ahole of holes) {\n sidewalls(ahole, layeroffset)\n layeroffset += ahole.length\n }\n groups.push({ start, count: verticesArray.length / 3 - start, materialIndex: 1 })\n\n const positions = new Float32Array(verticesArray)\n return { type: 'ExtrudeGeometry', parameters, positions, normals: computeVertexNormals(positions), uvs: new Float32Array(uvArray), groups }\n}\n","import { canonicalJson } from '../hash'\nimport type { MeshNode, PrimitiveBuffers, PrimitiveNode } from '../types'\nimport { difference } from './difference'\nimport { computeVertexNormals, extrude } from './extrude'\nimport { box, circle, cone, cylinder, indexArray, lathe, plane, ring, sphere, torus } from './three-generators'\n\nexport { box, circle, cone, cylinder, lathe, plane, ring, sphere, torus } from './three-generators'\nexport { computeVertexNormals, extrude } from './extrude'\nexport { difference } from './difference'\n\n/** How a level of detail changes a primitive. */\nexport interface DetailOptions {\n /** Multiplies the segment counts of round primitives (1 leaves them as given). */\n readonly detail?: number\n /** Floor of the scaled segment counts (default 3). */\n readonly minSegments?: number\n}\n\nconst PARAMETER_KEYS: Readonly<Record<PrimitiveNode['kind'], readonly string[]>> = {\n box: ['size', 'segments'],\n cylinder: ['radiusTop', 'radiusBottom', 'height', 'radialSegments', 'heightSegments', 'openEnded', 'thetaStart', 'thetaLength'],\n cone: ['radius', 'height', 'radialSegments', 'heightSegments', 'openEnded', 'thetaStart', 'thetaLength'],\n sphere: ['radius', 'widthSegments', 'heightSegments', 'phiStart', 'phiLength', 'thetaStart', 'thetaLength'],\n plane: ['width', 'height', 'widthSegments', 'heightSegments'],\n circle: ['radius', 'segments', 'thetaStart', 'thetaLength'],\n ring: ['innerRadius', 'outerRadius', 'thetaSegments', 'phiSegments', 'thetaStart', 'thetaLength'],\n lathe: ['points', 'segments', 'phiStart', 'phiLength'],\n torus: ['radius', 'tube', 'radialSegments', 'tubularSegments', 'arc'],\n extrude: ['shape', 'depth', 'steps', 'bevel'],\n difference: ['size', 'subtract'],\n mesh: ['positions', 'normals', 'uvs', 'indices'],\n}\n\n/** The segment fields `detail` scales, per kind. */\nconst SEGMENT_KEYS: Readonly<Partial<Record<PrimitiveNode['kind'], readonly string[]>>> = {\n cylinder: ['radialSegments'],\n cone: ['radialSegments'],\n sphere: ['widthSegments', 'heightSegments'],\n circle: ['segments'],\n ring: ['thetaSegments'],\n lathe: ['segments'],\n torus: ['radialSegments', 'tubularSegments'],\n}\n/** three's defaults of the segment fields, so a scaled default is scaled from the right number. */\nconst SEGMENT_DEFAULTS: Readonly<Record<string, number>> = { radialSegments: 32, widthSegments: 32, heightSegments: 16, segments: 12, thetaSegments: 32, tubularSegments: 48 }\nconst segmentDefault = (kind: string, key: string): number => (kind === 'circle' && key === 'segments' ? 32 : kind === 'torus' && key === 'radialSegments' ? 12 : (SEGMENT_DEFAULTS[key] as number))\n\n/** The parameters of a primitive node (no transform, colour or name), with the level of detail applied: what its geometry depends on. */\nexport function primitiveParameters(node: PrimitiveNode, options: DetailOptions = {}): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const source = node as unknown as Record<string, unknown>\n for (const key of PARAMETER_KEYS[node.kind]) if (source[key] !== undefined) out[key] = source[key]\n const detail = options.detail ?? 1\n if (detail !== 1) {\n const floor = options.minSegments ?? 3\n for (const key of SEGMENT_KEYS[node.kind] ?? []) {\n const given = (out[key] as number | undefined) ?? segmentDefault(node.kind, key)\n out[key] = Math.max(floor, Math.round(given * detail))\n }\n }\n return out\n}\n\nfunction mesh(p: MeshNode): PrimitiveBuffers {\n const positions = new Float32Array(p.positions as number[])\n const indices = p.indices ? indexArray(p.indices as number[]) : undefined\n return {\n type: 'BufferGeometry',\n parameters: {},\n positions,\n normals: p.normals ? new Float32Array(p.normals as number[]) : computeVertexNormals(positions, indices),\n uvs: p.uvs ? new Float32Array(p.uvs as number[]) : new Float32Array((positions.length / 3) * 2),\n ...(indices ? { indices } : {}),\n groups: [],\n }\n}\n\n/** Builds a node whose parameters were already resolved (`primitiveParameters` merged over it, so the detail level is applied). */\nfunction make(p: PrimitiveNode): PrimitiveBuffers {\n switch (p.kind) {\n case 'box': {\n const size = p.size ?? [1, 1, 1]\n const segments = p.segments ?? [1, 1, 1]\n return box(size[0], size[1], size[2], segments[0], segments[1], segments[2])\n }\n case 'cylinder':\n return cylinder(p.radiusTop, p.radiusBottom, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength)\n case 'cone':\n return cone(p.radius, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength)\n case 'sphere':\n return sphere(p.radius, p.widthSegments, p.heightSegments, p.phiStart, p.phiLength, p.thetaStart, p.thetaLength)\n case 'plane':\n return plane(p.width, p.height, p.widthSegments, p.heightSegments)\n case 'circle':\n return circle(p.radius, p.segments, p.thetaStart, p.thetaLength)\n case 'ring':\n return ring(p.innerRadius, p.outerRadius, p.thetaSegments, p.phiSegments, p.thetaStart, p.thetaLength)\n case 'lathe':\n return lathe(p.points, p.segments, p.phiStart, p.phiLength)\n case 'torus':\n return torus(p.radius, p.tube, p.radialSegments, p.tubularSegments, p.arc)\n case 'extrude':\n return extrude(p.shape, p.depth, p.steps, p.bevel)\n case 'difference':\n return difference(p.size, p.subtract ?? [])\n case 'mesh':\n return mesh(p)\n default:\n throw new Error(`game-shapes: unknown primitive kind \"${String((p as { kind: unknown }).kind)}\"`)\n }\n}\n\n/** Templates by their parameter text: the same cylinder is generated once per process. Read-only by contract. */\nconst templates = new Map<string, PrimitiveBuffers>()\nlet templateLimit = 4096\nconst stats = { hits: 0, misses: 0 }\n\n/** Sets how many primitive templates are kept (least recently used out; 0 turns the cache off). */\nexport function setTemplateCacheSize(size: number): void {\n templateLimit = Math.max(0, Math.floor(size))\n while (templates.size > templateLimit) templates.delete(templates.keys().next().value as string)\n}\nexport function clearTemplateCache(): void {\n templates.clear()\n stats.hits = 0\n stats.misses = 0\n}\nexport const templateCacheStats = (): { size: number; hits: number; misses: number } => ({ size: templates.size, ...stats })\n\n/**\n * The geometry of one primitive on its own, not baked: the arrays three's generator of the same kind builds, bit for bit (meshes and differences\n * are `BufferGeometry`). The result comes from a shared template cache and must not be written to (copy it with `clonePrimitive`).\n */\nexport function buildPrimitive(node: PrimitiveNode, options: DetailOptions = {}): PrimitiveBuffers {\n const parameters = primitiveParameters(node, options)\n // raw meshes are not worth a key of their whole arrays; they are cheap to wrap\n if (node.kind === 'mesh' || templateLimit === 0) return make({ ...node, ...parameters } as PrimitiveNode)\n const key = `${node.kind}:${canonicalJson(parameters)}`\n const cached = templates.get(key)\n if (cached) {\n stats.hits++\n templates.delete(key)\n templates.set(key, cached)\n return cached\n }\n stats.misses++\n const built = make({ ...node, ...parameters } as PrimitiveNode)\n templates.set(key, built)\n if (templates.size > templateLimit) templates.delete(templates.keys().next().value as string)\n return built\n}\n\n/** A copy that owns its arrays. */\nexport function clonePrimitive(p: PrimitiveBuffers): PrimitiveBuffers {\n return {\n type: p.type,\n parameters: p.parameters,\n positions: p.positions.slice(),\n normals: p.normals.slice(),\n uvs: p.uvs.slice(),\n ...(p.indices ? { indices: p.indices.slice() } : {}),\n groups: p.groups.map((group) => ({ ...group })),\n }\n}\n","import { hash64 } from './hash'\n\n/** mulberry32: a small, fast 32-bit seeded stream in [0, 1). */\nexport function mulberry32(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** The stream of one node: its own per (seed, generator, path), so adding a node never shifts another node's draws. */\nexport const streamFor = (seed: number | string, generator: string, path: string): (() => number) =>\n mulberry32(parseInt(hash64(`${String(seed)}\\u0000${generator}\\u0000${path}`).slice(0, 8), 16))\n","import type { ShapeGenerator } from './types'\n\nconst GENERATOR_NAME = /^[a-zA-Z][\\w.:-]*$/\n\n/** The generators of one set: what `{ kind: 'custom', generator: name, params }` nodes look up. */\nexport interface ShapeGenerators {\n /**\n * Registers a generator: a pure function of its params and a seeded stream that returns a node. A worker that generates shapes with custom nodes must\n * register the same generators (import the same module in the worker script).\n */\n register(name: string, generator: ShapeGenerator): void\n unregister(name: string): boolean\n get(name: string): ShapeGenerator | undefined\n list(): string[]\n /** The generators by name, as `GenerateOptions.generators` takes them. */\n record(): Readonly<Record<string, ShapeGenerator>>\n}\n\nexport const generatorsOver = (generators: Map<string, ShapeGenerator>): ShapeGenerators => ({\n register(name, generator) {\n if (!GENERATOR_NAME.test(name)) throw new Error(`game-shapes: generator name \"${name}\" must start with a letter and use letters, digits, \".\", \":\", \"-\" or \"_\"`)\n generators.set(name, generator)\n },\n unregister: (name) => generators.delete(name),\n get: (name) => generators.get(name),\n list: () => [...generators.keys()].sort(),\n record: () => Object.fromEntries(generators),\n})\n\nlet defaultGenerators: ShapeGenerators | undefined\n\n/** The set behind `registerGenerator`, `getGenerator` and the rest of the global functions, created on first use. */\nexport const defaultShapeGenerators = (): ShapeGenerators => (defaultGenerators ??= generatorsOver(new Map()))\n\n/** @deprecated use `createShapes(...).register`. */\nexport const registerGenerator = (name: string, generator: ShapeGenerator): void => defaultShapeGenerators().register(name, generator)\n/** @deprecated use `createShapes(...).unregister`. */\nexport const unregisterGenerator = (name: string): boolean => defaultShapeGenerators().unregister(name)\n/** @deprecated use `createShapes(...).get`. */\nexport const getGenerator = (name: string): ShapeGenerator | undefined => defaultShapeGenerators().get(name)\n/** @deprecated use `createShapes(...).list`. */\nexport const listGenerators = (): string[] => defaultShapeGenerators().list()\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://github.com/Andersonfrfilho/adatechnology-game-kit/packages/game-shapes/schema/shape.schema.json\",\n \"title\": \"game-shapes shape\",\n \"type\": \"object\",\n \"required\": [\n \"version\",\n \"root\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"version\": {\n \"const\": 1\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"materials\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/material\"\n }\n },\n \"root\": {\n \"$ref\": \"#/$defs/node\"\n },\n \"lod\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/lodLevel\"\n }\n },\n \"cullDistance\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n }\n },\n \"$defs\": {\n \"number\": {\n \"type\": \"number\"\n },\n \"count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"vec2\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 2,\n \"maxItems\": 2\n },\n \"vec3\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 3,\n \"maxItems\": 3\n },\n \"mat4\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 16,\n \"maxItems\": 16\n },\n \"color\": {\n \"oneOf\": [\n {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 16777215\n },\n {\n \"type\": \"string\",\n \"pattern\": \"^#[0-9a-fA-F]{6}$\"\n }\n ]\n },\n \"uvRect\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"u0\",\n \"v0\",\n \"u1\",\n \"v1\"\n ],\n \"properties\": {\n \"u0\": {\n \"type\": \"number\"\n },\n \"v0\": {\n \"type\": \"number\"\n },\n \"u1\": {\n \"type\": \"number\"\n },\n \"v1\": {\n \"type\": \"number\"\n }\n }\n },\n \"rotationOrder\": {\n \"enum\": [\n \"XYZ\",\n \"YXZ\",\n \"ZXY\",\n \"ZYX\",\n \"YZX\",\n \"XZY\"\n ]\n },\n \"transform\": {\n \"type\": \"object\",\n \"properties\": {\n \"position\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"rotation\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"rotationOrder\": {\n \"$ref\": \"#/$defs/rotationOrder\"\n },\n \"scale\": {\n \"oneOf\": [\n {\n \"type\": \"number\"\n },\n {\n \"$ref\": \"#/$defs/vec3\"\n }\n ]\n },\n \"heading\": {\n \"type\": \"number\"\n },\n \"matrix\": {\n \"$ref\": \"#/$defs/mat4\"\n }\n }\n },\n \"instance\": {\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/transform\"\n }\n ],\n \"properties\": {\n \"position\": true,\n \"rotation\": true,\n \"rotationOrder\": true,\n \"scale\": true,\n \"heading\": true,\n \"matrix\": true,\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n }\n },\n \"unevaluatedProperties\": false\n },\n \"material\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"roughness\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"metalness\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"opacity\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"transparent\": {\n \"type\": \"boolean\"\n },\n \"emissive\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"emissiveIntensity\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"side\": {\n \"enum\": [\n \"front\",\n \"back\",\n \"double\"\n ]\n },\n \"flatShading\": {\n \"type\": \"boolean\"\n },\n \"vertexColors\": {\n \"type\": \"boolean\"\n },\n \"depthWrite\": {\n \"type\": \"boolean\"\n }\n }\n },\n \"lodLevel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"distance\",\n \"detail\"\n ],\n \"properties\": {\n \"distance\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"detail\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0,\n \"maximum\": 1\n },\n \"minSize\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"minSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n }\n }\n },\n \"common\": {\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/transform\"\n }\n ],\n \"properties\": {\n \"kind\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"part\": {\n \"type\": \"string\"\n },\n \"material\": {\n \"type\": \"string\"\n },\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"uv\": {\n \"$ref\": \"#/$defs/uvRect\"\n },\n \"instances\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/instance\"\n }\n },\n \"minDetail\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0,\n \"maximum\": 1\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"node\": {\n \"type\": \"object\",\n \"required\": [\n \"kind\"\n ],\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/common\"\n }\n ],\n \"oneOf\": [\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"group\"\n },\n \"children\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/node\"\n }\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"box\"\n },\n \"size\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"segments\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"minItems\": 3,\n \"maxItems\": 3\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"cylinder\"\n },\n \"radiusTop\": {\n \"type\": \"number\"\n },\n \"radiusBottom\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"openEnded\": {\n \"type\": \"boolean\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"cone\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"openEnded\": {\n \"type\": \"boolean\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"sphere\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"widthSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 2\n },\n \"phiStart\": {\n \"type\": \"number\"\n },\n \"phiLength\": {\n \"type\": \"number\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"plane\"\n },\n \"width\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"widthSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"circle\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"ring\"\n },\n \"innerRadius\": {\n \"type\": \"number\"\n },\n \"outerRadius\": {\n \"type\": \"number\"\n },\n \"thetaSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"phiSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"required\": [\n \"points\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"lathe\"\n },\n \"points\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 2\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"phiStart\": {\n \"type\": \"number\"\n },\n \"phiLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"torus\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"tube\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"tubularSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"arc\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"required\": [\n \"shape\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"extrude\"\n },\n \"shape\": {\n \"type\": \"object\",\n \"required\": [\n \"outer\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"outer\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 3\n },\n \"holes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 3\n }\n }\n }\n },\n \"depth\": {\n \"type\": \"number\"\n },\n \"steps\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"bevel\": {\n \"oneOf\": [\n {\n \"const\": false\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"thickness\": {\n \"type\": \"number\"\n },\n \"size\": {\n \"type\": \"number\"\n },\n \"offset\": {\n \"type\": \"number\"\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n }\n }\n }\n ]\n }\n }\n },\n {\n \"required\": [\n \"size\",\n \"subtract\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"difference\"\n },\n \"size\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"subtract\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"min\",\n \"max\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"min\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"max\": {\n \"$ref\": \"#/$defs/vec2\"\n }\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"positions\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"mesh\"\n },\n \"positions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"normals\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"uvs\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"indices\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/count\"\n }\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"point\"\n },\n \"data\": {}\n }\n },\n {\n \"required\": [\n \"generator\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"custom\"\n },\n \"generator\": {\n \"type\": \"string\"\n },\n \"params\": {}\n }\n }\n ]\n }\n }\n}\n","import schemaJson from '../schema/shape.schema.json'\nimport type { ShapeSchema } from './types'\n\n/** The JSON Schema (draft 2020-12) of a shape document; the same file ships as `@adatechnology/game-shapes/schema.json`. */\nexport const SHAPE_SCHEMA: Readonly<Record<string, unknown>> = schemaJson\n\ntype Check = (value: unknown) => string | null\n\nconst num: Check = (v) => (typeof v === 'number' && Number.isFinite(v) ? null : 'expected a finite number')\nconst bool: Check = (v) => (typeof v === 'boolean' ? null : 'expected a boolean')\nconst str: Check = (v) => (typeof v === 'string' ? null : 'expected a string')\nconst int = (min: number): Check => (v) => (typeof v === 'number' && Number.isInteger(v) && v >= min ? null : `expected an integer >= ${min}`)\nconst range = (lo: number, hi: number, loOpen = false): Check => (v) =>\n typeof v === 'number' && (loOpen ? v > lo : v >= lo) && v <= hi ? null : `expected a number in ${loOpen ? '(' : '['}${lo}, ${hi}]`\nconst tuple = (n: number, item: Check = num): Check => (v) => {\n if (!Array.isArray(v) || v.length !== n) return `expected an array of ${n}`\n for (const x of v) if (item(x)) return `expected an array of ${n} numbers`\n return null\n}\nconst list = (item: Check, min = 0): Check => (v) => {\n if (!Array.isArray(v)) return 'expected an array'\n if (v.length < min) return `expected at least ${min} items`\n for (let i = 0; i < v.length; i++) {\n const e = item(v[i])\n if (e) return `[${i}]: ${e}`\n }\n return null\n}\nconst color: Check = (v) =>\n (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 0xffffff) || (typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v)) ? null : 'expected 0xRRGGBB or \"#rrggbb\"'\nconst oneOf = (values: readonly unknown[]): Check => (v) => (values.includes(v) ? null : `expected one of ${values.map((x) => JSON.stringify(x)).join(', ')}`)\nconst object = (fields: Readonly<Record<string, Check>>, required: readonly string[] = []): Check => (v) => {\n if (!v || typeof v !== 'object' || Array.isArray(v)) return 'expected an object'\n const record = v as Record<string, unknown>\n for (const key of required) if (record[key] === undefined) return `${key}: required`\n for (const key of Object.keys(record)) {\n if (record[key] === undefined) continue\n const check = fields[key]\n if (!check) return `${key}: unknown field`\n const e = check(record[key])\n if (e) return `${key}: ${e}`\n }\n return null\n}\n\nconst ORDERS = ['XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY'] as const\nconst TRANSFORM: Record<string, Check> = {\n position: tuple(3),\n rotation: tuple(3),\n rotationOrder: oneOf(ORDERS),\n scale: (v) => (typeof v === 'number' ? num(v) : tuple(3)(v)),\n heading: num,\n matrix: tuple(16),\n}\nconst UV = object({ u0: num, v0: num, u1: num, v1: num }, ['u0', 'v0', 'u1', 'v1'])\nconst INSTANCE = object({ ...TRANSFORM, color })\nconst COMMON: Record<string, Check> = {\n ...TRANSFORM,\n kind: str,\n name: str,\n part: str,\n material: str,\n color,\n uv: UV,\n instances: list(INSTANCE),\n minDetail: range(0, 1, true),\n tags: list(str),\n}\nconst vec2 = tuple(2)\nconst BEVEL: Check = (v) => (v === false ? null : object({ thickness: num, size: num, offset: num, segments: int(1) })(v))\nconst KINDS: Readonly<Record<string, { fields: Record<string, Check>; required?: string[] }>> = {\n group: { fields: {} },\n box: { fields: { size: tuple(3), segments: tuple(3, int(1)) } },\n cylinder: { fields: { radiusTop: num, radiusBottom: num, height: num, radialSegments: int(1), heightSegments: int(1), openEnded: bool, thetaStart: num, thetaLength: num } },\n cone: { fields: { radius: num, height: num, radialSegments: int(1), heightSegments: int(1), openEnded: bool, thetaStart: num, thetaLength: num } },\n sphere: { fields: { radius: num, widthSegments: int(3), heightSegments: int(2), phiStart: num, phiLength: num, thetaStart: num, thetaLength: num } },\n plane: { fields: { width: num, height: num, widthSegments: int(1), heightSegments: int(1) } },\n circle: { fields: { radius: num, segments: int(3), thetaStart: num, thetaLength: num } },\n ring: { fields: { innerRadius: num, outerRadius: num, thetaSegments: int(3), phiSegments: int(1), thetaStart: num, thetaLength: num } },\n lathe: { fields: { points: list(vec2, 2), segments: int(1), phiStart: num, phiLength: num }, required: ['points'] },\n torus: { fields: { radius: num, tube: num, radialSegments: int(1), tubularSegments: int(1), arc: num } },\n extrude: {\n fields: { shape: object({ outer: list(vec2, 3), holes: list(list(vec2, 3)) }, ['outer']), depth: num, steps: int(1), bevel: BEVEL },\n required: ['shape'],\n },\n difference: { fields: { size: tuple(3), subtract: list(object({ min: vec2, max: vec2 }, ['min', 'max'])) }, required: ['size', 'subtract'] },\n mesh: {\n fields: {\n positions: (v) => list(num)(v) ?? ((v as unknown[]).length % 3 === 0 ? null : 'expected a multiple of 3 numbers'),\n normals: list(num),\n uvs: list(num),\n indices: list(int(0)),\n },\n required: ['positions'],\n },\n point: { fields: { data: () => null } },\n custom: { fields: { generator: str, params: () => null }, required: ['generator'] },\n}\n\nfunction validateNode(node: unknown, path: string, errors: string[]): void {\n if (!node || typeof node !== 'object' || Array.isArray(node)) {\n errors.push(`${path}: expected a node object`)\n return\n }\n const record = node as Record<string, unknown>\n const spec = typeof record.kind === 'string' ? KINDS[record.kind] : undefined\n if (!spec) {\n errors.push(`${path}.kind: expected one of ${Object.keys(KINDS).join(', ')}`)\n return\n }\n for (const key of spec.required ?? []) if (record[key] === undefined) errors.push(`${path}.${key}: required`)\n for (const key of Object.keys(record)) {\n if (record[key] === undefined || key === 'children') continue\n const check = spec.fields[key] ?? COMMON[key]\n if (!check) {\n errors.push(`${path}.${key}: unknown field for a ${String(record.kind)}`)\n continue\n }\n const e = check(record[key])\n if (e) errors.push(`${path}.${key}: ${e}`)\n }\n const exclusive = ['matrix', 'heading'].filter((key) => record[key] !== undefined)\n if (record.matrix !== undefined && (record.position !== undefined || record.rotation !== undefined || record.scale !== undefined || record.heading !== undefined))\n errors.push(`${path}.matrix: cannot be combined with position, rotation, scale or heading`)\n else if (exclusive.includes('heading') && (record.rotation !== undefined || record.scale !== undefined)) errors.push(`${path}.heading: cannot be combined with rotation or scale`)\n if (record.children !== undefined) {\n if (record.kind !== 'group') errors.push(`${path}.children: only a group has children`)\n else if (!Array.isArray(record.children)) errors.push(`${path}.children: expected an array`)\n else record.children.forEach((child, index) => validateNode(child, `${path}.children[${index}]`, errors))\n }\n}\n\n/** Every rule of the JSON Schema, checked without a schema engine: one message per problem, with its path (`root.children[3].radialSegments: ...`). */\nexport function validateShape(schema: unknown): string[] {\n const errors: string[] = []\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return ['expected a shape object']\n const record = schema as Record<string, unknown>\n for (const key of Object.keys(record)) if (!['version', 'name', 'materials', 'root', 'lod', 'cullDistance'].includes(key) && record[key] !== undefined) errors.push(`${key}: unknown field`)\n if (record.version !== 1) errors.push('version: expected 1')\n if (record.name !== undefined && typeof record.name !== 'string') errors.push('name: expected a string')\n if (record.materials !== undefined) {\n if (!record.materials || typeof record.materials !== 'object' || Array.isArray(record.materials)) errors.push('materials: expected an object')\n else {\n const material = object({\n color,\n roughness: range(0, 1),\n metalness: range(0, 1),\n opacity: range(0, 1),\n transparent: bool,\n emissive: color,\n emissiveIntensity: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'),\n side: oneOf(['front', 'back', 'double']),\n flatShading: bool,\n vertexColors: bool,\n depthWrite: bool,\n })\n for (const [id, hint] of Object.entries(record.materials)) {\n const e = material(hint)\n if (e) errors.push(`materials.${id}: ${e}`)\n }\n }\n }\n if (record.lod !== undefined) {\n const e = list(object({ distance: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'), detail: range(0, 1, true), minSize: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'), minSegments: int(3) }, ['distance', 'detail']))(record.lod)\n if (e) errors.push(`lod${e.startsWith('[') ? '' : ': '}${e}`)\n }\n if (record.cullDistance !== undefined && !(typeof record.cullDistance === 'number' && record.cullDistance > 0)) errors.push('cullDistance: expected a number > 0')\n if (record.root === undefined) errors.push('root: required')\n else validateNode(record.root, 'root', errors)\n return errors\n}\n\n/** Throws with every problem when the schema is not valid. */\nexport function assertValidShape(schema: unknown): asserts schema is ShapeSchema {\n const errors = validateShape(schema)\n if (errors.length) throw new Error(`game-shapes: invalid shape\\n ${errors.slice(0, 20).join('\\n ')}${errors.length > 20 ? `\\n ... ${errors.length - 20} more` : ''}`)\n}\n","import { colorChannels, colorHex } from './color'\nimport { hashValue } from './hash'\nimport { asMat4, identity4, isAffine, matrixOf, multiply, normalMatrix, transformPoint } from './math'\nimport type { Matrix4 } from './math'\nimport { buildPrimitive, primitiveParameters } from './primitives'\nimport { canonicalJson } from './hash'\nimport { streamFor } from './random'\nimport { getGenerator } from './registry'\nimport { assertValidShape } from './schema'\nimport type {\n Bounds,\n GenerateOptions,\n InstancedBatch,\n NamedRange,\n PrimitiveBuffers,\n PrimitiveNode,\n ShapeBatch,\n ShapeBuffers,\n ShapeLevel,\n ShapeNode,\n ShapePart,\n ShapePoint,\n ShapeSchema,\n UvRect,\n} from './types'\n\nconst PRIMITIVE_KINDS = new Set(['box', 'cylinder', 'cone', 'sphere', 'plane', 'circle', 'ring', 'lathe', 'torus', 'extrude', 'difference', 'mesh'])\nexport const isPrimitiveNode = (node: ShapeNode): node is PrimitiveNode => PRIMITIVE_KINDS.has(node.kind)\n\n/** The options that change the output, as they enter the cache key. */\nexport function keyOptions(options: GenerateOptions = {}): Record<string, unknown> {\n return {\n seed: options.seed ?? 0,\n colors: options.colors ?? 'linear',\n indexed: options.indexed ?? true,\n materials: options.materials,\n fallbackMaterial: options.fallbackMaterial,\n materialAlias: options.materialAlias,\n instancing: options.instancing,\n levels: options.levels,\n }\n}\n\n/** The cache key of a shape under some options: 64-bit FNV-1a of the canonical schema text and the options that change the output. */\nexport const shapeKey = (schema: ShapeSchema, options: GenerateOptions = {}): string => hashValue({ schema, options: keyOptions(options) })\n\nconst IDENTITY_UV: UvRect = { u0: 0, v0: 0, u1: 1, v1: 1 }\n\nclass FloatList {\n array: Float32Array\n length = 0\n constructor(capacity = 256) {\n this.array = new Float32Array(capacity)\n }\n reserve(extra: number): void {\n if (this.length + extra <= this.array.length) return\n let capacity = this.array.length * 2\n while (capacity < this.length + extra) capacity *= 2\n const next = new Float32Array(capacity)\n next.set(this.array.subarray(0, this.length))\n this.array = next\n }\n done(): Float32Array {\n return this.array.slice(0, this.length)\n }\n}\nclass IndexList {\n array: Uint32Array\n length = 0\n constructor(capacity = 256) {\n this.array = new Uint32Array(capacity)\n }\n reserve(extra: number): void {\n if (this.length + extra <= this.array.length) return\n let capacity = this.array.length * 2\n while (capacity < this.length + extra) capacity *= 2\n const next = new Uint32Array(capacity)\n next.set(this.array.subarray(0, this.length))\n this.array = next\n }\n}\n\n/** Growing buffers of one (target, material). */\nclass Accumulator {\n readonly positions = new FloatList()\n readonly normals = new FloatList()\n readonly uvs = new FloatList(170)\n readonly colors = new FloatList()\n readonly indices = new IndexList()\n readonly ranges: NamedRange[] = []\n vertices = 0\n constructor(\n readonly material: string,\n readonly part: string | null,\n ) {}\n}\n\ninterface Target {\n readonly part: string | null\n readonly accs: Map<string, Accumulator>\n}\n\ninterface Settings {\n readonly colors: 'linear' | 'srgb' | 'none'\n readonly indexed: boolean\n readonly materials?: ReadonlySet<string>\n readonly fallback?: string\n readonly alias?: Readonly<Record<string, string>>\n readonly seed: number | string\n readonly generators?: GenerateOptions['generators']\n readonly isolatedGenerators?: boolean\n readonly autoMin?: number\n}\n\ninterface LevelSpec {\n readonly distance: number\n readonly detail: number\n readonly minSize?: number\n readonly minSegments?: number\n readonly index: number\n}\n\ninterface Inherited {\n readonly material: string\n readonly color: number\n readonly uv: UvRect\n readonly target: Target\n}\n\n/**\n * Bakes a template into an accumulator: positions by the world matrix, normals by its normal matrix and normalised, uvs into the atlas cell,\n * one colour for all, indices offset. The arithmetic is three's (`createMeshApi`, `BufferGeometry.applyMatrix4`), so the bits match.\n */\nfunction bake(acc: Accumulator, t: PrimitiveBuffers, world: readonly number[], rgb: readonly number[] | null, u: UvRect, indexed: boolean): void {\n const e = world\n const nm = normalMatrix(world)\n const affine = isAffine(world)\n const source = t.positions\n const count = source.length / 3\n const order: ArrayLike<number> | null = indexed ? null : t.indices ?? null\n const emitted = order ? order.length : count\n acc.positions.reserve(emitted * 3)\n acc.normals.reserve(emitted * 3)\n acc.uvs.reserve(emitted * 2)\n if (rgb) acc.colors.reserve(emitted * 3)\n const P = acc.positions.array\n const N = acc.normals.array\n const U = acc.uvs.array\n const C = acc.colors.array\n let pi = acc.positions.length\n let ni = acc.normals.length\n let ui = acc.uvs.length\n let ci = acc.colors.length\n const du = u.u1 - u.u0\n const dv = u.v1 - u.v0\n const tn = t.normals\n const tu = t.uvs\n for (let k = 0; k < emitted; k++) {\n const i = order ? (order[k] as number) : k\n const x = source[i * 3] as number\n const y = source[i * 3 + 1] as number\n const z = source[i * 3 + 2] as number\n if (affine) {\n P[pi++] = e[0]! * x + e[4]! * y + e[8]! * z + e[12]!\n P[pi++] = e[1]! * x + e[5]! * y + e[9]! * z + e[13]!\n P[pi++] = e[2]! * x + e[6]! * y + e[10]! * z + e[14]!\n } else {\n const p = transformPoint(e, x, y, z)\n P[pi++] = p[0]\n P[pi++] = p[1]\n P[pi++] = p[2]\n }\n const nx = tn[i * 3] as number\n const ny = tn[i * 3 + 1] as number\n const nz = tn[i * 3 + 2] as number\n const vx = nm[0]! * nx + nm[3]! * ny + nm[6]! * nz\n const vy = nm[1]! * nx + nm[4]! * ny + nm[7]! * nz\n const vz = nm[2]! * nx + nm[5]! * ny + nm[8]! * nz\n const s = 1 / (Math.sqrt(vx * vx + vy * vy + vz * vz) || 1)\n N[ni++] = vx * s\n N[ni++] = vy * s\n N[ni++] = vz * s\n U[ui++] = u.u0 + (tu[i * 2] as number) * du\n U[ui++] = u.v0 + (tu[i * 2 + 1] as number) * dv\n if (rgb) {\n C[ci++] = rgb[0]!\n C[ci++] = rgb[1]!\n C[ci++] = rgb[2]!\n }\n }\n acc.positions.length = pi\n acc.normals.length = ni\n acc.uvs.length = ui\n acc.colors.length = ci\n if (indexed) {\n const base = acc.vertices\n const idx = t.indices\n const n = idx ? idx.length : count\n acc.indices.reserve(n)\n const I = acc.indices.array\n let ii = acc.indices.length\n for (let k = 0; k < n; k++) I[ii++] = base + (idx ? (idx[k] as number) : k)\n acc.indices.length = ii\n }\n acc.vertices += emitted\n}\n\nfunction boundsOf(positions: Float32Array): Bounds {\n const min: [number, number, number] = [Infinity, Infinity, Infinity]\n const max: [number, number, number] = [-Infinity, -Infinity, -Infinity]\n for (let i = 0; i < positions.length; i += 3) {\n for (let axis = 0; axis < 3; axis++) {\n const v = positions[i + axis] as number\n if (v < min[axis]!) min[axis] = v\n if (v > max[axis]!) max[axis] = v\n }\n }\n return { min, max }\n}\n\nfunction finish(acc: Accumulator, indexed: boolean, withColors: boolean): ShapeBatch {\n const positions = acc.positions.done()\n const indices = indexed ? (acc.vertices > 65535 ? acc.indices.array.slice(0, acc.indices.length) : Uint16Array.from(acc.indices.array.subarray(0, acc.indices.length))) : undefined\n return {\n material: acc.material,\n part: acc.part,\n positions,\n normals: acc.normals.done(),\n uvs: acc.uvs.done(),\n ...(withColors ? { colors: acc.colors.done() } : {}),\n ...(indices ? { indices } : {}),\n ranges: acc.ranges,\n bounds: boundsOf(positions),\n }\n}\n\nconst radiusOf = (t: PrimitiveBuffers, world: readonly number[]): number => {\n let r = 0\n const p = t.positions\n for (let i = 0; i < p.length; i += 3) r = Math.max(r, Math.hypot(p[i] as number, p[i + 1] as number, p[i + 2] as number))\n const sx = Math.hypot(world[0]!, world[1]!, world[2]!)\n const sy = Math.hypot(world[4]!, world[5]!, world[6]!)\n const sz = Math.hypot(world[8]!, world[9]!, world[10]!)\n return r * Math.max(sx, sy, sz)\n}\n\ninterface LevelResult {\n readonly level: ShapeLevel\n readonly parts: ShapePart[]\n readonly points: ShapePoint[]\n readonly primitives: number\n}\n\n/** Expands a custom node into the node its generator returns (wrapped so that the custom node's own fields still apply). */\nfunction expandCustom(node: Extract<ShapeNode, { kind: 'custom' }>, settings: Settings, detail: number, path: string): ShapeNode {\n const generator = settings.generators?.[node.generator] ?? (settings.isolatedGenerators ? undefined : getGenerator(node.generator))\n if (!generator) throw new Error(`game-shapes: no generator \"${node.generator}\" (register it with registerGenerator, in the worker too) at ${path}`)\n const generated = generator(node.params, { random: streamFor(settings.seed, node.generator, path), seed: settings.seed, detail, path })\n const { kind: _kind, generator: _generator, params: _params, ...common } = node\n return { ...common, kind: 'group', children: [generated] }\n}\n\n/** The key two leaf primitives share when one can stand for the other as an instance. */\nconst leafKey = (node: PrimitiveNode, material: string, color: number, uv: UvRect, level: LevelSpec): string =>\n `${node.kind}|${canonicalJson(primitiveParameters(node, level))}|${material}|${color}|${uv.u0},${uv.v0},${uv.u1},${uv.v1}`\n\nfunction runLevel(schema: ShapeSchema, settings: Settings, level: LevelSpec): LevelResult {\n const bakeParts = level.index > 0\n const root: Target = { part: null, accs: new Map() }\n const targets: Target[] = [root]\n const partTargets = new Map<string, Target>()\n const parts: ShapePart[] = []\n const points: ShapePoint[] = []\n const instanced: InstancedBatch[] = []\n let primitives = 0\n const space = settings.colors === 'none' ? null : settings.colors\n const channels = new Map<number, readonly number[]>()\n const rgbOf = (hex: number): readonly number[] | null => {\n if (!space) return null\n let c = channels.get(hex)\n if (!c) {\n c = colorChannels(hex, space)\n channels.set(hex, c)\n }\n return c\n }\n const resolveMaterial = (id: string): string => {\n let out = id\n if (settings.materials && !settings.materials.has(out)) out = settings.fallback ?? out\n return settings.alias?.[out] ?? out\n }\n const accOf = (target: Target, material: string): Accumulator => {\n let acc = target.accs.get(material)\n if (!acc) {\n acc = new Accumulator(material, target.part)\n target.accs.set(material, acc)\n }\n return acc\n }\n\n // automatic instancing: count the leaves first\n const autoCounts = new Map<string, number>()\n const autoGroups = new Map<string, { node: PrimitiveNode; material: string; color: number; part: string | null; matrices: number[] }>()\n\n const count = (node: ShapeNode, inherited: { material: string; color: number; uv: UvRect; inPart: boolean }, path: string): void => {\n if (node.minDetail !== undefined && level.detail < node.minDetail) return\n if (node.kind === 'custom') return count(expandCustom(node, settings, level.detail, path), inherited, path)\n const next = {\n material: node.material !== undefined ? resolveMaterial(node.material) : inherited.material,\n color: node.color !== undefined ? colorHex(node.color) : inherited.color,\n uv: node.uv ?? inherited.uv,\n inPart: inherited.inPart || (node.part !== undefined && !bakeParts),\n }\n if (node.instances) return\n if (node.kind === 'group') {\n node.children?.forEach((child, index) => count(child, next, `${path}/${index}`))\n return\n }\n if (isPrimitiveNode(node) && node.name === undefined && !next.inPart) {\n const key = leafKey(node, next.material, next.color, next.uv, level)\n autoCounts.set(key, (autoCounts.get(key) ?? 0) + 1)\n }\n }\n const rootMaterial = resolveMaterial('default')\n if (settings.autoMin !== undefined) count(schema.root, { material: rootMaterial, color: 0xffffff, uv: IDENTITY_UV, inPart: false }, 'root')\n\n /** Draws a subtree into `collector` (a target) under `parent` (null: identity). */\n const visit = (node: ShapeNode, parent: Matrix4 | null, inherited: Inherited, path: string): void => {\n if (node.minDetail !== undefined && level.detail < node.minDetail) return\n if (node.kind === 'custom') return visit(expandCustom(node, settings, level.detail, path), parent, inherited, path)\n let target = inherited.target\n let parentWorld = parent\n if (node.part !== undefined) {\n if (bakeParts) {\n // far levels freeze the parts at rest: the part's pivot is relative to the root\n parentWorld = null\n } else {\n let partTarget = partTargets.get(node.part)\n if (!partTarget) {\n partTarget = { part: node.part, accs: new Map() }\n partTargets.set(node.part, partTarget)\n targets.push(partTarget)\n const { position, rotation, rotationOrder, scale, heading, matrix } = node\n parts.push({\n id: node.part,\n ...(position ? { position } : {}),\n ...(rotation ? { rotation } : {}),\n ...(rotationOrder ? { rotationOrder } : {}),\n ...(scale !== undefined ? { scale } : {}),\n ...(heading !== undefined ? { heading } : {}),\n ...(matrix ? { matrix } : { matrix: asMat4(matrixOf(node)) }),\n })\n }\n target = partTarget\n }\n }\n const isPart = node.part !== undefined && !bakeParts\n const local = isPart ? null : matrixOf(node)\n const world = isPart ? null : local ? (parentWorld ? multiply(parentWorld, local) : local) : parentWorld\n const next: Inherited = {\n material: node.material !== undefined ? resolveMaterial(node.material) : inherited.material,\n color: node.color !== undefined ? colorHex(node.color) : inherited.color,\n uv: node.uv ?? inherited.uv,\n target,\n }\n\n if (node.instances) {\n drawInstanced(node, parentWorld, next, path)\n return\n }\n\n const snapshot = node.name !== undefined ? new Map([...target.accs].map(([m, a]) => [m, { v: a.vertices, i: a.indices.length }])) : null\n\n if (node.kind === 'group') {\n node.children?.forEach((child, index) => visit(child, world, next, `${path}/${index}`))\n } else if (node.kind === 'point') {\n const p = node.position ?? [0, 0, 0]\n points.push({\n ...(node.name !== undefined ? { name: node.name } : {}),\n part: target.part,\n position: parent ? transformPoint(parent, p[0], p[1], p[2]) : [p[0], p[1], p[2]],\n ...(node.data !== undefined ? { data: node.data } : {}),\n ...(node.tags ? { tags: node.tags } : {}),\n })\n } else if (isPrimitiveNode(node)) {\n const template = buildPrimitive(node, level)\n const m = world ?? identity4()\n if (level.minSize !== undefined && radiusOf(template, m) < level.minSize) return\n primitives++\n if (settings.autoMin !== undefined && node.name === undefined && target.part === null) {\n const key = leafKey(node, next.material, next.color, next.uv, level)\n if ((autoCounts.get(key) ?? 0) >= settings.autoMin) {\n let group = autoGroups.get(key)\n if (!group) {\n group = { node, material: next.material, color: next.color, part: null, matrices: [] }\n autoGroups.set(key, group)\n }\n group.matrices.push(...m)\n return\n }\n }\n bake(accOf(target, next.material), template, m, rgbOf(next.color), next.uv, settings.indexed)\n }\n\n if (snapshot) {\n for (const [material, acc] of target.accs) {\n const before = snapshot.get(material) ?? { v: 0, i: 0 }\n if (acc.vertices === before.v) continue\n acc.ranges.push({\n name: node.name as string,\n ...(node.tags ? { tags: node.tags } : {}),\n vertexStart: before.v,\n vertexCount: acc.vertices - before.v,\n indexStart: before.i,\n indexCount: acc.indices.length - before.i,\n })\n }\n }\n }\n\n const drawInstanced = (node: ShapeNode, parentWorld: Matrix4 | null, inherited: Inherited, path: string): void => {\n const collector: Target = { part: inherited.target.part, accs: new Map() }\n const { instances, ...single } = node as ShapeNode & { instances: NonNullable<ShapeNode['instances']> }\n const before = parts.length\n visit(single as ShapeNode, null, { ...inherited, target: collector }, path)\n if (parts.length !== before) throw new Error(`game-shapes: an instanced node cannot hold parts (${path})`)\n const matrices = new Float32Array(instances.length * 16)\n const hasColors = instances.some((instance) => instance.color !== undefined)\n const colors = hasColors ? new Float32Array(instances.length * 3) : undefined\n instances.forEach((instance, index) => {\n const local = matrixOf(instance)\n const m = local ? (parentWorld ? multiply(parentWorld, local) : local) : parentWorld ?? identity4()\n matrices.set(m, index * 16)\n if (colors) colors.set(colorChannels(colorHex(instance.color), space ?? 'srgb'), index * 3)\n })\n for (const acc of collector.accs.values()) {\n const batch = finish(acc, settings.indexed, false)\n instanced.push({\n material: acc.material,\n part: collector.part,\n ...(node.name !== undefined ? { name: node.name } : {}),\n geometry: { type: 'BufferGeometry', parameters: {}, positions: batch.positions, normals: batch.normals, uvs: batch.uvs, ...(batch.indices ? { indices: batch.indices } : {}), groups: [] },\n matrices: matrices.slice(),\n ...(colors ? { colors: colors.slice() } : {}),\n count: instances.length,\n })\n }\n }\n\n visit(schema.root, null, { material: rootMaterial, color: 0xffffff, uv: IDENTITY_UV, target: root }, 'root')\n\n for (const group of autoGroups.values()) {\n const template = buildPrimitive(group.node, level)\n const n = group.matrices.length / 16\n const rgb = colorChannels(group.color, space ?? 'srgb')\n const colors = new Float32Array(n * 3)\n for (let i = 0; i < n; i++) colors.set(rgb, i * 3)\n instanced.push({\n material: group.material,\n part: null,\n geometry: { type: template.type, parameters: template.parameters, positions: template.positions.slice(), normals: template.normals.slice(), uvs: template.uvs.slice(), ...(template.indices ? { indices: template.indices.slice() } : {}), groups: template.groups.map((g) => ({ ...g })) },\n matrices: new Float32Array(group.matrices),\n ...(space ? { colors } : {}),\n count: n,\n })\n }\n\n const batches: ShapeBatch[] = []\n for (const target of targets) for (const acc of target.accs.values()) if (acc.vertices > 0 && (!settings.indexed || acc.indices.length > 0)) batches.push(finish(acc, settings.indexed, space !== null))\n return { level: { distance: level.distance, detail: level.detail, batches, instanced }, parts, points, primitives }\n}\n\n/**\n * Turns a shape into buffers: one batch per (part, material) per level, baked; instanced nodes as instance batches; parts with their pivots;\n * points. Pure: the same schema and options give the same bytes, here or in a worker.\n */\nexport function generate(schema: ShapeSchema, options: GenerateOptions = {}): ShapeBuffers {\n if (options.validate !== false) assertValidShape(schema)\n const settings: Settings = {\n colors: options.colors ?? 'linear',\n indexed: options.indexed ?? true,\n ...(options.materials ? { materials: new Set(options.materials) } : {}),\n ...(options.fallbackMaterial !== undefined ? { fallback: options.fallbackMaterial } : {}),\n ...(options.materialAlias ? { alias: options.materialAlias } : {}),\n seed: options.seed ?? 0,\n ...(options.generators ? { generators: options.generators } : {}),\n ...(options.isolatedGenerators ? { isolatedGenerators: true } : {}),\n ...(options.instancing ? { autoMin: Math.max(2, options.instancing.minCount) } : {}),\n }\n const specs: LevelSpec[] = [{ distance: 0, detail: 1, index: 0 }, ...(schema.lod ?? []).map((rule, index) => ({ ...rule, index: index + 1 }))]\n const wanted = options.levels ? specs.filter((spec) => options.levels!.includes(spec.index)) : specs\n let parts: ShapePart[] = []\n let points: ShapePoint[] = []\n let primitives = 0\n const levels: ShapeLevel[] = []\n for (const spec of wanted) {\n const result = runLevel(schema, settings, spec)\n if (spec.index === 0 || levels.length === 0) {\n parts = result.parts\n points = result.points\n primitives = result.primitives\n }\n levels.push(result.level)\n }\n const first = levels[0]\n const vertices = first ? first.batches.reduce((sum, batch) => sum + batch.positions.length / 3, 0) : 0\n const triangles = first\n ? first.batches.reduce((sum, batch) => sum + (batch.indices ? batch.indices.length : batch.positions.length / 3) / 3, 0) +\n first.instanced.reduce((sum, batch) => sum + ((batch.geometry.indices ? batch.geometry.indices.length : batch.geometry.positions.length / 3) / 3) * batch.count, 0)\n : 0\n return {\n key: options.key === false ? '' : options.key ?? shapeKey(schema, options),\n ...(schema.name !== undefined ? { name: schema.name } : {}),\n levels,\n parts,\n points,\n ...(schema.materials ? { materials: schema.materials } : {}),\n ...(schema.cullDistance !== undefined ? { cullDistance: schema.cullDistance } : {}),\n stats: { vertices, triangles, batches: first ? first.batches.length : 0, instances: first ? first.instanced.reduce((sum, batch) => sum + batch.count, 0) : 0, primitives },\n }\n}\n","import { normalMatrix, transformPoint } from './math'\nimport type { InstancedBatch, PrimitiveBuffers, ShapeBatch, ShapeBuffers } from './types'\n\n/** One piece for `mergeTransformed`: arrays (any may be missing) and the matrix that takes them into the merged space. */\nexport interface TransformedPiece {\n readonly positions: ArrayLike<number>\n readonly normals?: ArrayLike<number>\n readonly uvs?: ArrayLike<number>\n readonly indices?: ArrayLike<number> | null\n /** Column-major 4 x 4. */\n readonly matrix: readonly number[]\n}\n\nexport interface MergedArrays {\n readonly positions: Float32Array\n readonly normals: Float32Array\n readonly uvs: Float32Array\n}\n\n/**\n * Joins pieces into one non-indexed set of arrays, each piece de-indexed, its missing normals and uvs zero-filled, its positions by\n * `Vector3.applyMatrix4` and its normals by the normal matrix and normalised: what three's `toNonIndexed` + `applyMatrix4` + a join do,\n * bit for bit (the port of `mergeByMaterial`).\n */\nexport function mergeTransformed(pieces: readonly TransformedPiece[]): MergedArrays {\n let total = 0\n for (const piece of pieces) total += piece.indices ? piece.indices.length : piece.positions.length / 3\n const positions = new Float32Array(total * 3)\n const normals = new Float32Array(total * 3)\n const uvs = new Float32Array(total * 2)\n let at = 0\n for (const piece of pieces) {\n const e = piece.matrix\n const nm = normalMatrix(e)\n const count = piece.indices ? piece.indices.length : piece.positions.length / 3\n // de-index into Float32 first, as toNonIndexed does, then transform the stored values\n const p = new Float32Array(count * 3)\n const n = new Float32Array(count * 3)\n for (let k = 0; k < count; k++) {\n const i = piece.indices ? (piece.indices[k] as number) : k\n for (let c = 0; c < 3; c++) {\n p[k * 3 + c] = piece.positions[i * 3 + c] as number\n if (piece.normals) n[k * 3 + c] = piece.normals[i * 3 + c] as number\n }\n if (piece.uvs) {\n uvs[(at + k) * 2] = piece.uvs[i * 2] as number\n uvs[(at + k) * 2 + 1] = piece.uvs[i * 2 + 1] as number\n }\n }\n for (let k = 0; k < count; k++) {\n const q = transformPoint(e, p[k * 3] as number, p[k * 3 + 1] as number, p[k * 3 + 2] as number)\n positions[(at + k) * 3] = q[0]\n positions[(at + k) * 3 + 1] = q[1]\n positions[(at + k) * 3 + 2] = q[2]\n const x = n[k * 3] as number\n const y = n[k * 3 + 1] as number\n const z = n[k * 3 + 2] as number\n const vx = nm[0]! * x + nm[3]! * y + nm[6]! * z\n const vy = nm[1]! * x + nm[4]! * y + nm[7]! * z\n const vz = nm[2]! * x + nm[5]! * y + nm[8]! * z\n const s = 1 / (Math.sqrt(vx * vx + vy * vy + vz * vz) || 1)\n normals[(at + k) * 3] = vx * s\n normals[(at + k) * 3 + 1] = vy * s\n normals[(at + k) * 3 + 2] = vz * s\n }\n at += count\n }\n return { positions, normals, uvs }\n}\n\nconst primitiveArrays = (p: PrimitiveBuffers): ArrayBuffer[] => [p.positions, p.normals, p.uvs, ...(p.indices ? [p.indices] : [])].map((a) => a.buffer as ArrayBuffer)\nconst batchArrays = (b: ShapeBatch): ArrayBuffer[] => [b.positions, b.normals, b.uvs, ...(b.colors ? [b.colors] : []), ...(b.indices ? [b.indices] : [])].map((a) => a.buffer as ArrayBuffer)\nconst instancedArrays = (b: InstancedBatch): ArrayBuffer[] => [...primitiveArrays(b.geometry), b.matrices.buffer as ArrayBuffer, ...(b.colors ? [b.colors.buffer as ArrayBuffer] : [])]\n\n/** Every `ArrayBuffer` of a result, for `postMessage(buffers, transferablesOf(buffers))`. */\nexport function transferablesOf(buffers: ShapeBuffers): ArrayBuffer[] {\n const out = new Set<ArrayBuffer>()\n for (const level of buffers.levels) {\n for (const batch of level.batches) for (const a of batchArrays(batch)) out.add(a)\n for (const batch of level.instanced) for (const a of instancedArrays(batch)) out.add(a)\n }\n return [...out]\n}\n\nconst copyPrimitive = (p: PrimitiveBuffers): PrimitiveBuffers => ({\n ...p,\n positions: p.positions.slice(),\n normals: p.normals.slice(),\n uvs: p.uvs.slice(),\n ...(p.indices ? { indices: p.indices.slice() } : {}),\n groups: p.groups.map((g) => ({ ...g })),\n})\n\n/** A deep copy whose arrays are its own (cached results are shared and read-only; copy before deforming). */\nexport function cloneBuffers(buffers: ShapeBuffers): ShapeBuffers {\n return {\n ...buffers,\n levels: buffers.levels.map((level) => ({\n ...level,\n batches: level.batches.map((b) => ({\n ...b,\n positions: b.positions.slice(),\n normals: b.normals.slice(),\n uvs: b.uvs.slice(),\n ...(b.colors ? { colors: b.colors.slice() } : {}),\n ...(b.indices ? { indices: b.indices.slice() } : {}),\n ranges: b.ranges.map((r) => ({ ...r })),\n bounds: { min: [...b.bounds.min], max: [...b.bounds.max] },\n })),\n instanced: level.instanced.map((b) => ({ ...b, geometry: copyPrimitive(b.geometry), matrices: b.matrices.slice(), ...(b.colors ? { colors: b.colors.slice() } : {}) })),\n })),\n }\n}\n\n/** Bytes held by the arrays of a result (what the cache counts). */\nexport function byteSizeOf(buffers: ShapeBuffers): number {\n return transferablesOf(buffers).reduce((sum, buffer) => sum + buffer.byteLength, 0)\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\nconst clampShare = (share: number): number => Math.min(1, Math.max(0, share))\n\n/**\n * The shove a blast gives to a body of `mass` kg whose centre is at `position`: away from the centre, lifted a little, with the speed\n * `sqrt(reach) * min(maxSpeed, sqrt(2 * energy * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n // cover takes its share off the push itself, past the cap too: a light thing behind a cupboard is not thrown as fast as one in the open\n const reach = clampShare(blast.reach ?? 1)\n const speed = Math.sqrt(reach) * Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at: inside it the charge is in contact and the body is torn apart anyway. */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, NEAREST) / w3\n const scaled = (0.067 * Math.sqrt(1 + (z / 0.23) ** 4)) / (z * z * Math.cbrt(1 + (z / 1.55) ** 3))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n\n/** Where `launchBody` leaves the throw on the body's root until the module that animates it takes it. */\nconst LAUNCHED = 'launched'\n\n/**\n * Throws a body at `velocity` (m/s, world): an occupant leaving a car through the glass, a pedestrian run over. The module that animates the body\n * takes it on its next frame (`takeLaunch`) and moves it as it moves a body a blast knocked down: flying, landing, sliding, lying, getting up.\n */\nexport function launchBody(root: { userData: Record<string, unknown> }, velocity: Vec3): void {\n root.userData[LAUNCHED] = [velocity[0], velocity[1], velocity[2]]\n}\n\n/** The throw `launchBody` left on the root, as a knock (knocked down, in the air), once; undefined when nothing threw it. */\nexport function takeLaunch(root: { userData: Record<string, unknown> }): Knock | undefined {\n const velocity = root.userData[LAUNCHED] as Vec3 | undefined\n if (!velocity) return undefined\n delete root.userData[LAUNCHED]\n return { velocity: [velocity[0], velocity[1], velocity[2]], airborne: true, lying: 0, lieLeft: 0, down: true }\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present' },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n cobble: 'concrete',\n paver: 'concrete',\n plaster: 'concrete',\n asphalt: 'asphalt',\n wood_soft: 'wood',\n wood_hard: 'wood',\n green_wood: 'wood',\n plywood: 'wood',\n mdf: 'wood',\n ceramic: 'tile',\n plastic: 'tile',\n soil: 'dirt',\n mud: 'dirt',\n clay: 'dirt',\n wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n // no snow surface yet: packed snow crunches closest to sand underfoot\n snow: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n Dent,\n DestructibleSpec,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartShape,\n PartSpec,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, launchBody, stepKnock, takeLaunch } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, checkDeferredQueue } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, ModuleArea, ModuleHost, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\n\nimport { generate } from './generate'\nimport { generatorsOver } from './registry'\nimport type { ShapeGenerators } from './registry'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\n\nexport interface ShapesOptions {\n /** Generators by name, added to the set; later packs replace earlier ones with the same name. */\n readonly packs?: readonly Readonly<Record<string, ShapeGenerator>>[]\n /** A generator replaced by name (a function is replaced as a whole). */\n readonly patch?: Readonly<Record<string, ShapeGenerator>>\n /** Names taken out. */\n readonly remove?: readonly string[]\n}\n\nexport interface Shapes extends ShapeGenerators {\n /** `generate` that looks custom nodes up in this set only (a name only the global registry has throws). */\n generate(schema: ShapeSchema, options?: Omit<GenerateOptions, 'isolatedGenerators'>): ShapeBuffers\n}\n\ntype Entry = { readonly id: string; readonly generator: ShapeGenerator }\n\n/** A set of shape generators of its own. Nothing is shared with any other set or with the global registry. */\nexport function createShapes(options: ShapesOptions = {}): Shapes {\n const entryOf = ([id, generator]: [string, ShapeGenerator]): Entry => ({ id, generator })\n const entries = mergeById<Entry>([], (options.packs ?? []).flatMap((pack) => Object.entries(pack).map(entryOf)))\n const patches: Record<string, Partial<Entry>> = {}\n for (const [id, generator] of Object.entries(options.patch ?? {})) patches[id] = { generator }\n applyPatches(entries, patches)\n removeIds(entries, options.remove)\n const generators = generatorsOver(new Map([...entries].map(([id, entry]) => [id, entry.generator])))\n return { ...generators, generate: (schema, generateOptions = {}) => generate(schema, { ...generateOptions, generators: { ...generators.record(), ...generateOptions.generators }, isolatedGenerators: true }) }\n}\n","import { byteSizeOf } from './merge'\nimport type { ShapeBuffers } from './types'\n\nexport interface ShapeCacheOptions {\n /** Most results kept (default 256). */\n readonly maxEntries?: number\n /** Most bytes of arrays kept (default 64 MiB). A result larger than this alone is not kept. */\n readonly maxBytes?: number\n}\n\nexport interface ShapeCacheStats {\n readonly entries: number\n readonly bytes: number\n readonly hits: number\n readonly misses: number\n readonly evictions: number\n}\n\n/** An LRU of results by `shapeKey`. What it returns is shared: read-only (copy with `cloneBuffers` before deforming). */\nexport interface ShapeCache {\n get(key: string): ShapeBuffers | undefined\n set(key: string, buffers: ShapeBuffers): void\n has(key: string): boolean\n delete(key: string): boolean\n clear(): void\n stats(): ShapeCacheStats\n}\n\n/** An LRU of `ShapeBuffers` by key, bounded by entries and by bytes of the arrays. Pure memoisation: a hit gives the bytes a miss would. */\nexport function createShapeCache(options: ShapeCacheOptions = {}): ShapeCache {\n const maxEntries = options.maxEntries ?? 256\n const maxBytes = options.maxBytes ?? 64 * 1024 * 1024\n const entries = new Map<string, { buffers: ShapeBuffers; bytes: number }>()\n let bytes = 0\n let hits = 0\n let misses = 0\n let evictions = 0\n const drop = (key: string): boolean => {\n const entry = entries.get(key)\n if (!entry) return false\n entries.delete(key)\n bytes -= entry.bytes\n return true\n }\n return {\n get(key) {\n const entry = entries.get(key)\n if (!entry) {\n misses++\n return undefined\n }\n hits++\n // most recently used goes last\n entries.delete(key)\n entries.set(key, entry)\n return entry.buffers\n },\n set(key, buffers) {\n drop(key)\n const size = byteSizeOf(buffers)\n if (size > maxBytes || maxEntries <= 0) return\n entries.set(key, { buffers, bytes: size })\n bytes += size\n for (const oldest of entries.keys()) {\n if (entries.size <= maxEntries && bytes <= maxBytes) break\n drop(oldest)\n evictions++\n }\n },\n has: (key) => entries.has(key),\n delete: drop,\n clear() {\n entries.clear()\n bytes = 0\n },\n stats: () => ({ entries: entries.size, bytes, hits, misses, evictions }),\n }\n}\n","import type { ShapeCache } from './cache'\nimport { generate, shapeKey } from './generate'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\nimport type { ShapeJob, ShapeReply } from './worker'\n\n/** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, an in-thread fake. */\nexport interface WorkerLike {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror?: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void\n terminate(): unknown\n}\n\nexport interface ShapePoolOptions {\n /** Workers (default 0: generate in the calling thread). */\n readonly size?: number\n /** Makes one worker that runs `installShapeWorker`. Without it the pool generates in the calling thread. */\n readonly spawn?: () => WorkerLike\n /** Results by `shapeKey`: a hit resolves at once and never reaches a worker. */\n readonly cache?: ShapeCache\n /** Generators of the `custom` nodes for the jobs made in the calling thread (the workers register their own). */\n readonly generators?: Readonly<Record<string, ShapeGenerator>>\n /** Look custom nodes up in `generators` only (for example `shapes.record()` of `createShapes`), never in the global registry; the jobs then run in the calling thread, since a worker cannot receive functions. */\n readonly isolatedGenerators?: boolean\n}\n\nexport interface ShapeRequest {\n readonly schema: ShapeSchema\n readonly options?: GenerateOptions\n}\n\nexport interface ShapePoolStats {\n readonly workers: number\n readonly jobs: number\n readonly cacheHits: number\n readonly shared: number\n readonly inThread: number\n readonly busy: number\n}\n\nexport interface ShapePool {\n /** `generate(schema, options)` off the main thread. Same key, same promise while in flight; the result is shared (read-only). */\n generate(schema: ShapeSchema, options?: GenerateOptions): Promise<ShapeBuffers>\n /** A list spread over the workers, resolved in input order. */\n generateMany(list: readonly (ShapeSchema | ShapeRequest)[]): Promise<ShapeBuffers[]>\n stats(): ShapePoolStats\n /** Stops the workers; pending jobs reject. */\n terminate(): void\n}\n\ninterface Slot {\n worker: WorkerLike\n pending: Map<number, { resolve: (b: ShapeBuffers) => void; reject: (e: Error) => void }>\n}\n\nconst isRequest = (value: ShapeSchema | ShapeRequest): value is ShapeRequest => (value as ShapeRequest).schema !== undefined && (value as ShapeSchema).root === undefined\n\n/**\n * A pool of shape workers. The schema is cheap (plain data) and is built on the main thread; the buffers are generated in a worker and\n * transferred back. With `size: 0` or no `spawn` it generates in the calling thread, with the same cache and in-flight sharing.\n */\nexport function createShapePool(options: ShapePoolOptions = {}): ShapePool {\n const size = options.spawn ? Math.max(0, options.size ?? 0) : 0\n const cache = options.cache\n const slots: Slot[] = []\n const inFlight = new Map<string, Promise<ShapeBuffers>>()\n let nextId = 1\n let jobs = 0\n let cacheHits = 0\n let shared = 0\n let inThread = 0\n let terminated = false\n\n const failAll = (slot: Slot, error: Error): void => {\n for (const job of slot.pending.values()) job.reject(error)\n slot.pending.clear()\n }\n const spawnSlot = (): Slot => {\n const slot: Slot = { worker: (options.spawn as () => WorkerLike)(), pending: new Map() }\n slot.worker.onmessage = (event) => {\n const reply = event.data as ShapeReply\n const job = slot.pending.get(reply.id)\n if (!job) return\n slot.pending.delete(reply.id)\n if (reply.ok) job.resolve(reply.buffers)\n else job.reject(new Error(reply.error))\n }\n slot.worker.onerror = (event) => {\n // a worker that crashed takes its jobs with it; a fresh one takes its place\n failAll(slot, new Error(`game-shapes worker failed: ${(event as { message?: string })?.message ?? String(event)}`))\n slot.worker.terminate()\n const index = slots.indexOf(slot)\n if (index >= 0 && !terminated) slots[index] = spawnSlot()\n }\n return slot\n }\n for (let i = 0; i < size; i++) slots.push(spawnSlot())\n\n const run = (schema: ShapeSchema, generateOptions: GenerateOptions): Promise<ShapeBuffers> => {\n // custom generators passed per call are functions: they cannot reach a worker, so that job runs here\n if (slots.length === 0 || generateOptions.generators || options.isolatedGenerators) {\n inThread++\n try {\n const generators = { ...(options.generators ?? {}), ...(generateOptions.generators ?? {}) }\n return Promise.resolve(generate(schema, { ...generateOptions, ...(Object.keys(generators).length ? { generators } : {}), ...(options.isolatedGenerators ? { isolatedGenerators: true } : {}) }))\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let slot = slots[0] as Slot\n for (const s of slots) if (s.pending.size < slot.pending.size) slot = s\n const id = nextId++\n const job: ShapeJob = { id, schema, options: generateOptions }\n return new Promise<ShapeBuffers>((resolve, reject) => {\n slot.pending.set(id, { resolve, reject })\n slot.worker.postMessage(job)\n })\n }\n\n const pool: ShapePool = {\n generate(schema, generateOptions = {}) {\n if (terminated) return Promise.reject(new Error('createShapePool: the pool was terminated'))\n jobs++\n const key = shapeKey(schema, generateOptions)\n const hit = cache?.get(key)\n if (hit) {\n cacheHits++\n return Promise.resolve(hit)\n }\n const flying = inFlight.get(key)\n if (flying) {\n shared++\n return flying\n }\n const promise = run(schema, generateOptions).then(\n (buffers) => {\n inFlight.delete(key)\n cache?.set(key, buffers)\n return buffers\n },\n (error: unknown) => {\n inFlight.delete(key)\n throw error\n },\n )\n inFlight.set(key, promise)\n return promise\n },\n generateMany(list) {\n return Promise.all(list.map((item) => (isRequest(item) ? pool.generate(item.schema, item.options) : pool.generate(item))))\n },\n stats: () => ({ workers: slots.length, jobs, cacheHits, shared, inThread, busy: slots.reduce((n, s) => n + s.pending.size, 0) }),\n terminate() {\n terminated = true\n for (const slot of slots) {\n failAll(slot, new Error('createShapePool: the pool was terminated'))\n slot.worker.terminate()\n }\n slots.length = 0\n },\n }\n return pool\n}\n","import { generate } from './generate'\nimport { transferablesOf } from './merge'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\n\n/** A job the pool posts: `options` without `generators` (functions do not cross threads; register them in the worker script). */\nexport interface ShapeJob {\n readonly id: number\n readonly schema: ShapeSchema\n readonly options?: Omit<GenerateOptions, 'generators'>\n}\n\nexport type ShapeReply = { readonly id: number; readonly ok: true; readonly buffers: ShapeBuffers } | { readonly id: number; readonly ok: false; readonly error: string }\n\n/** What a worker scope looks like: `self` in a browser worker, a `worker_threads` `parentPort` wrapper in Node, or an in-thread fake. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void\n}\n\nexport interface ShapeWorkerOptions {\n /** Generators of the `custom` nodes, the same ones the main thread registers. */\n readonly generators?: Readonly<Record<string, ShapeGenerator>>\n /** Transfer the arrays back (default true: zero copy, the worker keeps nothing). */\n readonly transfer?: boolean\n}\n\n/**\n * The worker side of `createShapePool`: answers each job with `generate(schema, options)`, transferring every array.\n *\n * ```ts\n * // shape-worker.ts\n * import { installShapeWorker } from '@adatechnology/game-shapes/worker'\n * installShapeWorker(self as never, { generators: myGenerators })\n * ```\n */\nexport function installShapeWorker(scope: WorkerScopeLike, options: ShapeWorkerOptions = {}): void {\n const transfer = options.transfer !== false\n scope.onmessage = (event) => {\n const job = event.data as ShapeJob\n try {\n const buffers = generate(job.schema, { ...(job.options ?? {}), ...(options.generators ? { generators: options.generators } : {}) })\n const reply: ShapeReply = { id: job.id, ok: true, buffers }\n scope.postMessage(reply, transfer ? transferablesOf(buffers) : [])\n } catch (error) {\n const reply: ShapeReply = { id: job.id, ok: false, error: error instanceof Error ? error.message : String(error) }\n scope.postMessage(reply)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,WAAS,SAASA,QAA0B,WAAW,UAAkB;AAC9E,QAAIA,WAAU,OAAW,QAAO;AAChC,QAAI,OAAOA,WAAU,SAAU,QAAO,KA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MAAM,QAAQ,MAAM,WAAW,QAAQ,UAAU,MAAM,MAAM,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,MAAM,CAAC,EAAE;AAAA,MAC9H,YAAY;AACV,qBAAa;AACb,mBAAW,QAAQ,OAAO;AACxB,kBAAQ,MAAM,IAAI,MAAM,0CAA0C,CAAC;AACnE,eAAK,OAAO,UAAU;AAAA,QACxB;AACA,cAAM,SAAS;AAAA,MACjB;AAAA,IACF;AACA,WAAO;AAAA,EACT;;;AC/HO,WAAS,mBAAmB,OAAwB,UAA8B,CAAC,GAAS;AACjG,UAAM,WAAW,QAAQ,aAAa;AACtC,UAAM,YAAY,CAAC,UAAU;AAC3B,YAAM,MAAM,MAAM;AAClB,UAAI;AACF,cAAM,UAAU,SAAS,IAAI,QAAQ,EAAE,GAAI,IAAI,WAAW,CAAC,GAAI,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC,EAAG,CAAC;AAClI,cAAM,QAAoB,EAAE,IAAI,IAAI,IAAI,IAAI,MAAM,QAAQ;AAC1D,cAAM,YAAY,OAAO,WAAW,gBAAgB,OAAO,IAAI,CAAC,CAAC;AAAA,MACnE,SAAS,OAAO;AACd,cAAM,QAAoB,EAAE,IAAI,IAAI,IAAI,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AACjH,cAAM,YAAY,KAAK;AAAA,MACzB;AAAA,IACF;AAAA,EACF;","names":["color","p","width","height","depth","indexArray","sign","list","num","equals","area","ring","bs","layeroffset","color","pack","list"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/color.ts","../src/hash.ts","../src/math.ts","../src/primitives/three-generators.ts","../src/primitives/difference.ts","../src/primitives/earcut.ts","../src/primitives/extrude.ts","../src/primitives/index.ts","../src/random.ts","../src/registry.ts","../schema/shape.schema.json","../src/schema.ts","../src/generate.ts","../src/merge.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/hands.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/index.ts","../src/instance.ts","../src/cache.ts","../src/pool.ts","../src/worker.ts"],"sourcesContent":["export { generate, isPrimitiveNode, keyOptions, shapeKey } from './generate'\nexport {\n box,\n buildPrimitive,\n circle,\n clearTemplateCache,\n clonePrimitive,\n computeVertexNormals,\n cone,\n cylinder,\n difference,\n extrude,\n lathe,\n plane,\n primitiveParameters,\n ring,\n setTemplateCacheSize,\n sphere,\n templateCacheStats,\n torus,\n} from './primitives'\nexport type { DetailOptions } from './primitives'\nexport { byteSizeOf, cloneBuffers, mergeTransformed, transferablesOf } from './merge'\nexport type { MergedArrays, TransformedPiece } from './merge'\nexport { SHAPE_SCHEMA, assertValidShape, validateShape } from './schema'\nexport { defaultShapeGenerators, getGenerator, listGenerators, registerGenerator, unregisterGenerator } from './registry'\nexport type { ShapeGenerators } from './registry'\nexport { createShapes } from './instance'\nexport type { Shapes, ShapesOptions } from './instance'\nexport { canonicalJson, hash64, hashValue } from './hash'\nexport { mulberry32, streamFor } from './random'\nexport { colorChannels, colorHex, srgbToLinear } from './color'\nexport { compose, headingMatrix, identity4, isAffine, matrixOf, multiply, normalMatrix, quaternionFromEuler, transformPoint } from './math'\nexport type { Matrix3, Matrix4 } from './math'\nexport type * from './types'\nexport { createShapeCache } from './cache'\nexport type { ShapeCache, ShapeCacheOptions, ShapeCacheStats } from './cache'\nexport { createShapePool } from './pool'\nexport type { ShapePool, ShapePoolOptions, ShapePoolStats, ShapeRequest, WorkerLike } from './pool'\nexport { installShapeWorker } from './worker'\nexport type { ShapeJob, ShapeReply, ShapeWorkerOptions, WorkerScopeLike } from './worker'\n","import type { Color } from './types'\n\n/** A colour as `0xRRGGBB`: numbers as given (floored, as three's `setHex`), `'#rrggbb'` strings parsed. */\nexport function colorHex(color: Color | undefined, fallback = 0xffffff): number {\n if (color === undefined) return fallback\n if (typeof color === 'number') return Math.floor(color)\n const match = /^#([0-9a-fA-F]{6})$/.exec(color)\n if (!match) throw new Error(`game-shapes: colour \"${color}\" is not 0xRRGGBB or #rrggbb`)\n return parseInt(match[1] as string, 16)\n}\n\n/** three's `SRGBToLinear` (r160 `ColorManagement`), the same constants. */\nexport const srgbToLinear = (c: number): number => (c < 0.04045 ? c * 0.0773993808 : Math.pow(c * 0.9478672986 + 0.0521327014, 2.4))\n\n/**\n * The rgb floats of a hex colour as three's `Color.setHex` stores them: the channels over 255 (`'srgb'`), converted to the linear working space\n * when colour management is on (`'linear'`).\n */\nexport function colorChannels(hex: number, space: 'linear' | 'srgb'): [number, number, number] {\n const r = ((hex >> 16) & 255) / 255\n const g = ((hex >> 8) & 255) / 255\n const b = (hex & 255) / 255\n return space === 'linear' ? [srgbToLinear(r), srgbToLinear(g), srgbToLinear(b)] : [r, g, b]\n}\n","/**\n * Canonical JSON (keys sorted, `undefined` left out, `-0` kept as `-0`, typed arrays as plain lists) and a 64-bit FNV-1a of it in two 32-bit\n * lanes: the key a shape is cached and shared by.\n */\nexport function canonicalJson(value: unknown): string {\n if (value === null) return 'null'\n if (typeof value === 'number') return Object.is(value, -0) ? '-0' : Number.isFinite(value) ? String(value) : JSON.stringify(String(value))\n if (typeof value === 'string') return JSON.stringify(value)\n if (typeof value === 'boolean') return value ? 'true' : 'false'\n if (typeof value === 'function') throw new Error('game-shapes: a function cannot be part of a shape (register it as a generator)')\n if (ArrayBuffer.isView(value)) return canonicalJson(Array.from(value as unknown as ArrayLike<number>))\n if (Array.isArray(value)) return `[${value.map((item) => (item === undefined ? 'null' : canonicalJson(item))).join(',')}]`\n if (typeof value === 'object') {\n const record = value as Record<string, unknown>\n const keys = Object.keys(record).filter((key) => record[key] !== undefined).sort()\n return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(',')}}`\n }\n return 'null'\n}\n\nconst lane = (text: string, offset: number, prime: number): string => {\n let hash = offset\n for (let index = 0; index < text.length; index++) {\n hash ^= text.charCodeAt(index)\n hash = Math.imul(hash, prime)\n }\n return (hash >>> 0).toString(16).padStart(8, '0')\n}\n\n/** 64-bit FNV-1a of a text as 16 hex digits (two independent 32-bit lanes). */\nexport const hash64 = (text: string): string => lane(text, 0x811c9dc5, 0x01000193) + lane(text, 0x050c5d1f, 0x5bd1e995)\n\n/** `hash64(canonicalJson(value))`. */\nexport const hashValue = (value: unknown): string => hash64(canonicalJson(value))\n","/*\n * Matrix and quaternion arithmetic as three.js r160 does it (MIT, https://github.com/mrdoob/three.js): the same expressions in the same order, so a\n * vertex baked here has the same bits as one baked by `Matrix4.compose` / `multiplyMatrices` / `Matrix3.getNormalMatrix` / `Vector3.normalize`.\n * Matrices are column-major arrays of 16 (4 x 4) or 9 (3 x 3) numbers, the layout of three's `elements`.\n */\nimport type { Mat4, RotationOrder, Transform, Vec3 } from './types'\n\nexport type Matrix4 = number[]\nexport type Matrix3 = number[]\n\nexport const identity4 = (): Matrix4 => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]\n\n/** `Quaternion.setFromEuler` (x, y, z, w). */\nexport function quaternionFromEuler(x: number, y: number, z: number, order: RotationOrder = 'XYZ'): [number, number, number, number] {\n const cos = Math.cos\n const sin = Math.sin\n const c1 = cos(x / 2)\n const c2 = cos(y / 2)\n const c3 = cos(z / 2)\n const s1 = sin(x / 2)\n const s2 = sin(y / 2)\n const s3 = sin(z / 2)\n switch (order) {\n case 'XYZ':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'YXZ':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n case 'ZXY':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'ZYX':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n case 'YZX':\n return [s1 * c2 * c3 + c1 * s2 * s3, c1 * s2 * c3 + s1 * c2 * s3, c1 * c2 * s3 - s1 * s2 * c3, c1 * c2 * c3 - s1 * s2 * s3]\n case 'XZY':\n return [s1 * c2 * c3 - c1 * s2 * s3, c1 * s2 * c3 - s1 * c2 * s3, c1 * c2 * s3 + s1 * s2 * c3, c1 * c2 * c3 + s1 * s2 * s3]\n default:\n throw new Error(`game-shapes: unknown rotation order \"${String(order)}\"`)\n }\n}\n\n/** `Matrix4.compose(position, quaternion, scale)`. */\nexport function compose(px: number, py: number, pz: number, q: readonly [number, number, number, number], sx: number, sy: number, sz: number): Matrix4 {\n const [x, y, z, w] = q\n const x2 = x + x\n const y2 = y + y\n const z2 = z + z\n const xx = x * x2\n const xy = x * y2\n const xz = x * z2\n const yy = y * y2\n const yz = y * z2\n const zz = z * z2\n const wx = w * x2\n const wy = w * y2\n const wz = w * z2\n return [\n (1 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n (xy - wz) * sy, (1 - (xx + zz)) * sy, (yz + wx) * sy, 0,\n (xz + wy) * sz, (yz - wx) * sz, (1 - (xx + yy)) * sz, 0,\n px, py, pz, 1,\n ]\n}\n\n/** `Matrix4.makeRotationY(theta)` followed by `setPosition(x, y, z)`. */\nexport function headingMatrix(theta: number, x = 0, y = 0, z = 0): Matrix4 {\n const c = Math.cos(theta)\n const s = Math.sin(theta)\n return [c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, x, y, z, 1]\n}\n\n/** `Matrix4.multiplyMatrices(a, b)`: a x b. */\nexport function multiply(ae: readonly number[], be: readonly number[]): Matrix4 {\n const a11 = ae[0]!, a12 = ae[4]!, a13 = ae[8]!, a14 = ae[12]!\n const a21 = ae[1]!, a22 = ae[5]!, a23 = ae[9]!, a24 = ae[13]!\n const a31 = ae[2]!, a32 = ae[6]!, a33 = ae[10]!, a34 = ae[14]!\n const a41 = ae[3]!, a42 = ae[7]!, a43 = ae[11]!, a44 = ae[15]!\n const b11 = be[0]!, b12 = be[4]!, b13 = be[8]!, b14 = be[12]!\n const b21 = be[1]!, b22 = be[5]!, b23 = be[9]!, b24 = be[13]!\n const b31 = be[2]!, b32 = be[6]!, b33 = be[10]!, b34 = be[14]!\n const b41 = be[3]!, b42 = be[7]!, b43 = be[11]!, b44 = be[15]!\n return [\n a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41,\n a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41,\n a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41,\n a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41,\n a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42,\n a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42,\n a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42,\n a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42,\n a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43,\n a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43,\n a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43,\n a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43,\n a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44,\n a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44,\n a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44,\n a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44,\n ]\n}\n\n/** `Matrix3.getNormalMatrix(m)`: the inverse transpose of the upper 3 x 3 (all zeros when singular, as three). */\nexport function normalMatrix(me: readonly number[]): Matrix3 {\n // setFromMatrix4\n const n11 = me[0]!, n21 = me[1]!, n31 = me[2]!\n const n12 = me[4]!, n22 = me[5]!, n32 = me[6]!\n const n13 = me[8]!, n23 = me[9]!, n33 = me[10]!\n // invert\n const t11 = n33 * n22 - n32 * n23\n const t12 = n32 * n13 - n33 * n12\n const t13 = n23 * n12 - n22 * n13\n const det = n11 * t11 + n21 * t12 + n31 * t13\n if (det === 0) return [0, 0, 0, 0, 0, 0, 0, 0, 0]\n const detInv = 1 / det\n const te = [\n t11 * detInv,\n (n31 * n23 - n33 * n21) * detInv,\n (n32 * n21 - n31 * n22) * detInv,\n t12 * detInv,\n (n33 * n11 - n31 * n13) * detInv,\n (n31 * n12 - n32 * n11) * detInv,\n t13 * detInv,\n (n21 * n13 - n23 * n11) * detInv,\n (n22 * n11 - n21 * n12) * detInv,\n ]\n // transpose\n let tmp = te[1]!\n te[1] = te[3]!\n te[3] = tmp\n tmp = te[2]!\n te[2] = te[6]!\n te[6] = tmp\n tmp = te[5]!\n te[5] = te[7]!\n te[7] = tmp\n return te\n}\n\n/** True when the last row is (0, 0, 0, 1): `applyMatrix4`'s divide by w is then a multiply by exactly 1. */\nexport const isAffine = (e: readonly number[]): boolean => e[3] === 0 && e[7] === 0 && e[11] === 0 && e[15] === 1\n\n/** `Vector3.applyMatrix4`. */\nexport function transformPoint(e: readonly number[], x: number, y: number, z: number): [number, number, number] {\n const w = 1 / (e[3]! * x + e[7]! * y + e[11]! * z + e[15]!)\n return [(e[0]! * x + e[4]! * y + e[8]! * z + e[12]!) * w, (e[1]! * x + e[5]! * y + e[9]! * z + e[13]!) * w, (e[2]! * x + e[6]! * y + e[10]! * z + e[14]!) * w]\n}\n\nconst toVec3 = (scale: number | Vec3 | undefined): Vec3 => (scale === undefined ? [1, 1, 1] : typeof scale === 'number' ? [scale, scale, scale] : scale)\n\n/** True when the transform has no field set. */\nexport const isIdentityTransform = (t: Transform): boolean =>\n t.matrix === undefined && t.heading === undefined && t.position === undefined && t.rotation === undefined && t.scale === undefined\n\n/** The local matrix of a transform, or `null` when it has none. */\nexport function matrixOf(t: Transform): Matrix4 | null {\n if (t.matrix !== undefined) return [...t.matrix]\n if (t.heading !== undefined) {\n const p = t.position ?? [0, 0, 0]\n return headingMatrix(t.heading, p[0], p[1], p[2])\n }\n if (t.position === undefined && t.rotation === undefined && t.scale === undefined) return null\n const p = t.position ?? [0, 0, 0]\n const r = t.rotation ?? [0, 0, 0]\n const s = toVec3(t.scale)\n return compose(p[0], p[1], p[2], quaternionFromEuler(r[0], r[1], r[2], t.rotationOrder ?? 'XYZ'), s[0], s[1], s[2])\n}\n\n/** The matrix as given, as a plain array (for `ShapePart.matrix`). */\nexport const asMat4 = (m: Matrix4 | null): Mat4 => (m ? [...m] : identity4())\n","/*\n * The geometry generators of three.js r160 (MIT, https://github.com/mrdoob/three.js, src/geometries/*.js), ported line by line: the same loops,\n * the same expressions in the same order, numbers pushed into plain arrays and stored as Float32 at the end, exactly as `Float32BufferAttribute`\n * does. A test compares every array of every generator with three's, bit for bit, over a grid of parameters.\n */\nimport type { GeometryGroup, PrimitiveBuffers } from '../types'\n\nexport interface Arrays {\n vertices: number[]\n normals: number[]\n uvs: number[]\n indices: number[] | null\n groups: GeometryGroup[]\n}\n\n/** three's `arrayNeedsUint32`: 32-bit indices once any index reaches 65535. */\nexport function needsUint32(array: ArrayLike<number>): boolean {\n for (let i = array.length - 1; i >= 0; --i) if ((array[i] as number) >= 65535) return true\n return false\n}\n\nexport const indexArray = (indices: ArrayLike<number>): Uint16Array | Uint32Array => (needsUint32(indices) ? new Uint32Array(indices) : new Uint16Array(indices))\n\nexport function pack(type: string, parameters: Record<string, unknown>, a: Arrays): PrimitiveBuffers {\n return {\n type,\n parameters,\n positions: new Float32Array(a.vertices),\n normals: new Float32Array(a.normals),\n uvs: new Float32Array(a.uvs),\n ...(a.indices ? { indices: indexArray(a.indices) } : {}),\n groups: a.groups,\n }\n}\n\nconst normalize3 = (x: number, y: number, z: number): [number, number, number] => {\n const length = Math.sqrt(x * x + y * y + z * z)\n const s = 1 / (length || 1)\n return [x * s, y * s, z * s]\n}\n\nexport function box(width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1): PrimitiveBuffers {\n const parameters = { width, height, depth, widthSegments, heightSegments, depthSegments }\n widthSegments = Math.floor(widthSegments)\n heightSegments = Math.floor(heightSegments)\n depthSegments = Math.floor(depthSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const groups: GeometryGroup[] = []\n let numberOfVertices = 0\n let groupStart = 0\n type Axis = 'x' | 'y' | 'z'\n const buildPlane = (u: Axis, v: Axis, w: Axis, udir: number, vdir: number, width: number, height: number, depth: number, gridX: number, gridY: number, materialIndex: number): void => {\n const segmentWidth = width / gridX\n const segmentHeight = height / gridY\n const widthHalf = width / 2\n const heightHalf = height / 2\n const depthHalf = depth / 2\n const gridX1 = gridX + 1\n const gridY1 = gridY + 1\n let vertexCounter = 0\n let groupCount = 0\n const vector = { x: 0, y: 0, z: 0 }\n for (let iy = 0; iy < gridY1; iy++) {\n const y = iy * segmentHeight - heightHalf\n for (let ix = 0; ix < gridX1; ix++) {\n const x = ix * segmentWidth - widthHalf\n vector[u] = x * udir\n vector[v] = y * vdir\n vector[w] = depthHalf\n vertices.push(vector.x, vector.y, vector.z)\n vector[u] = 0\n vector[v] = 0\n vector[w] = depth > 0 ? 1 : -1\n normals.push(vector.x, vector.y, vector.z)\n uvs.push(ix / gridX)\n uvs.push(1 - iy / gridY)\n vertexCounter += 1\n }\n }\n for (let iy = 0; iy < gridY; iy++) {\n for (let ix = 0; ix < gridX; ix++) {\n const a = numberOfVertices + ix + gridX1 * iy\n const b = numberOfVertices + ix + gridX1 * (iy + 1)\n const c = numberOfVertices + (ix + 1) + gridX1 * (iy + 1)\n const d = numberOfVertices + (ix + 1) + gridX1 * iy\n indices.push(a, b, d)\n indices.push(b, c, d)\n groupCount += 6\n }\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex })\n groupStart += groupCount\n numberOfVertices += vertexCounter\n }\n buildPlane('z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0)\n buildPlane('z', 'y', 'x', 1, -1, depth, height, -width, depthSegments, heightSegments, 1)\n buildPlane('x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2)\n buildPlane('x', 'z', 'y', 1, -1, width, depth, -height, widthSegments, depthSegments, 3)\n buildPlane('x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4)\n buildPlane('x', 'y', 'z', -1, -1, width, height, -depth, widthSegments, heightSegments, 5)\n return pack('BoxGeometry', parameters, { vertices, normals, uvs, indices, groups })\n}\n\nfunction cylinderArrays(radiusTop: number, radiusBottom: number, height: number, radialSegments: number, heightSegments: number, openEnded: boolean, thetaStart: number, thetaLength: number): Arrays {\n radialSegments = Math.floor(radialSegments)\n heightSegments = Math.floor(heightSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const groups: GeometryGroup[] = []\n let index = 0\n const indexArray: number[][] = []\n const halfHeight = height / 2\n let groupStart = 0\n\n const generateTorso = (): void => {\n let groupCount = 0\n const slope = (radiusBottom - radiusTop) / height\n for (let y = 0; y <= heightSegments; y++) {\n const indexRow: number[] = []\n const v = y / heightSegments\n const radius = v * (radiusBottom - radiusTop) + radiusTop\n for (let x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments\n const theta = u * thetaLength + thetaStart\n const sinTheta = Math.sin(theta)\n const cosTheta = Math.cos(theta)\n vertices.push(radius * sinTheta, -v * height + halfHeight, radius * cosTheta)\n const n = normalize3(sinTheta, slope, cosTheta)\n normals.push(n[0], n[1], n[2])\n uvs.push(u, 1 - v)\n indexRow.push(index++)\n }\n indexArray.push(indexRow)\n }\n for (let x = 0; x < radialSegments; x++) {\n for (let y = 0; y < heightSegments; y++) {\n const a = indexArray[y]![x]!\n const b = indexArray[y + 1]![x]!\n const c = indexArray[y + 1]![x + 1]!\n const d = indexArray[y]![x + 1]!\n indices.push(a, b, d)\n indices.push(b, c, d)\n groupCount += 6\n }\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex: 0 })\n groupStart += groupCount\n }\n\n const generateCap = (top: boolean): void => {\n const centerIndexStart = index\n let groupCount = 0\n const radius = top === true ? radiusTop : radiusBottom\n const sign = top === true ? 1 : -1\n for (let x = 1; x <= radialSegments; x++) {\n vertices.push(0, halfHeight * sign, 0)\n normals.push(0, sign, 0)\n uvs.push(0.5, 0.5)\n index++\n }\n const centerIndexEnd = index\n for (let x = 0; x <= radialSegments; x++) {\n const u = x / radialSegments\n const theta = u * thetaLength + thetaStart\n const cosTheta = Math.cos(theta)\n const sinTheta = Math.sin(theta)\n vertices.push(radius * sinTheta, halfHeight * sign, radius * cosTheta)\n normals.push(0, sign, 0)\n uvs.push(cosTheta * 0.5 + 0.5, sinTheta * 0.5 * sign + 0.5)\n index++\n }\n for (let x = 0; x < radialSegments; x++) {\n const c = centerIndexStart + x\n const i = centerIndexEnd + x\n if (top === true) indices.push(i, i + 1, c)\n else indices.push(i + 1, i, c)\n groupCount += 3\n }\n groups.push({ start: groupStart, count: groupCount, materialIndex: top === true ? 1 : 2 })\n groupStart += groupCount\n }\n\n generateTorso()\n if (openEnded === false) {\n if (radiusTop > 0) generateCap(true)\n if (radiusBottom > 0) generateCap(false)\n }\n return { vertices, normals, uvs, indices, groups }\n}\n\nexport function cylinder(radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }\n return pack('CylinderGeometry', parameters, cylinderArrays(radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength))\n}\n\nexport function cone(radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength }\n return pack('ConeGeometry', parameters, cylinderArrays(0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength))\n}\n\nexport function sphere(radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI): PrimitiveBuffers {\n const parameters = { radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength }\n widthSegments = Math.max(3, Math.floor(widthSegments))\n heightSegments = Math.max(2, Math.floor(heightSegments))\n const thetaEnd = Math.min(thetaStart + thetaLength, Math.PI)\n let index = 0\n const grid: number[][] = []\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let iy = 0; iy <= heightSegments; iy++) {\n const verticesRow: number[] = []\n const v = iy / heightSegments\n let uOffset = 0\n if (iy === 0 && thetaStart === 0) uOffset = 0.5 / widthSegments\n else if (iy === heightSegments && thetaEnd === Math.PI) uOffset = -0.5 / widthSegments\n for (let ix = 0; ix <= widthSegments; ix++) {\n const u = ix / widthSegments\n const x = -radius * Math.cos(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)\n const y = radius * Math.cos(thetaStart + v * thetaLength)\n const z = radius * Math.sin(phiStart + u * phiLength) * Math.sin(thetaStart + v * thetaLength)\n vertices.push(x, y, z)\n const n = normalize3(x, y, z)\n normals.push(n[0], n[1], n[2])\n uvs.push(u + uOffset, 1 - v)\n verticesRow.push(index++)\n }\n grid.push(verticesRow)\n }\n for (let iy = 0; iy < heightSegments; iy++) {\n for (let ix = 0; ix < widthSegments; ix++) {\n const a = grid[iy]![ix + 1]!\n const b = grid[iy]![ix]!\n const c = grid[iy + 1]![ix]!\n const d = grid[iy + 1]![ix + 1]!\n if (iy !== 0 || thetaStart > 0) indices.push(a, b, d)\n if (iy !== heightSegments - 1 || thetaEnd < Math.PI) indices.push(b, c, d)\n }\n }\n return pack('SphereGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function plane(width = 1, height = 1, widthSegments = 1, heightSegments = 1): PrimitiveBuffers {\n const parameters = { width, height, widthSegments, heightSegments }\n const widthHalf = width / 2\n const heightHalf = height / 2\n const gridX = Math.floor(widthSegments)\n const gridY = Math.floor(heightSegments)\n const gridX1 = gridX + 1\n const gridY1 = gridY + 1\n const segmentWidth = width / gridX\n const segmentHeight = height / gridY\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let iy = 0; iy < gridY1; iy++) {\n const y = iy * segmentHeight - heightHalf\n for (let ix = 0; ix < gridX1; ix++) {\n const x = ix * segmentWidth - widthHalf\n vertices.push(x, -y, 0)\n normals.push(0, 0, 1)\n uvs.push(ix / gridX)\n uvs.push(1 - iy / gridY)\n }\n }\n for (let iy = 0; iy < gridY; iy++) {\n for (let ix = 0; ix < gridX; ix++) {\n const a = ix + gridX1 * iy\n const b = ix + gridX1 * (iy + 1)\n const c = ix + 1 + gridX1 * (iy + 1)\n const d = ix + 1 + gridX1 * iy\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('PlaneGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function circle(radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, segments, thetaStart, thetaLength }\n segments = Math.max(3, segments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n vertices.push(0, 0, 0)\n normals.push(0, 0, 1)\n uvs.push(0.5, 0.5)\n for (let s = 0, i = 3; s <= segments; s++, i += 3) {\n const segment = thetaStart + (s / segments) * thetaLength\n // the vector's z stays 0, as three's Vector3\n vertices.push(radius * Math.cos(segment), radius * Math.sin(segment), 0)\n normals.push(0, 0, 1)\n uvs.push(((vertices[i] as number) / radius + 1) / 2, ((vertices[i + 1] as number) / radius + 1) / 2)\n }\n for (let i = 1; i <= segments; i++) indices.push(i, i + 1, 0)\n return pack('CircleGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function ring(innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength }\n thetaSegments = Math.max(3, thetaSegments)\n phiSegments = Math.max(1, phiSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n let radius = innerRadius\n const radiusStep = (outerRadius - innerRadius) / phiSegments\n for (let j = 0; j <= phiSegments; j++) {\n for (let i = 0; i <= thetaSegments; i++) {\n const segment = thetaStart + (i / thetaSegments) * thetaLength\n const x = radius * Math.cos(segment)\n const y = radius * Math.sin(segment)\n vertices.push(x, y, 0)\n normals.push(0, 0, 1)\n uvs.push((x / outerRadius + 1) / 2, (y / outerRadius + 1) / 2)\n }\n radius += radiusStep\n }\n for (let j = 0; j < phiSegments; j++) {\n const thetaSegmentLevel = j * (thetaSegments + 1)\n for (let i = 0; i < thetaSegments; i++) {\n const segment = i + thetaSegmentLevel\n const a = segment\n const b = segment + thetaSegments + 1\n const c = segment + thetaSegments + 2\n const d = segment + 1\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('RingGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function lathe(points: ReadonlyArray<readonly [number, number]>, segments = 12, phiStart = 0, phiLength = Math.PI * 2): PrimitiveBuffers {\n const parameters = { points: points.map(([x, y]) => ({ x, y })), segments, phiStart, phiLength }\n segments = Math.floor(segments)\n phiLength = Math.max(0, Math.min(Math.PI * 2, phiLength))\n const indices: number[] = []\n const vertices: number[] = []\n const uvs: number[] = []\n const initNormals: number[] = []\n const normals: number[] = []\n const inverseSegments = 1.0 / segments\n const normal = { x: 0, y: 0, z: 0 }\n const curNormal = { x: 0, y: 0, z: 0 }\n const prevNormal = { x: 0, y: 0, z: 0 }\n let dx = 0\n let dy = 0\n const last = points.length - 1\n const px = (j: number): number => (points[j] as readonly [number, number])[0]\n const py = (j: number): number => (points[j] as readonly [number, number])[1]\n const setNormalized = (): void => {\n const n = normalize3(normal.x, normal.y, normal.z)\n normal.x = n[0]\n normal.y = n[1]\n normal.z = n[2]\n }\n for (let j = 0; j <= last; j++) {\n if (j === 0) {\n dx = px(j + 1) - px(j)\n dy = py(j + 1) - py(j)\n normal.x = dy * 1.0\n normal.y = -dx\n normal.z = dy * 0.0\n prevNormal.x = normal.x\n prevNormal.y = normal.y\n prevNormal.z = normal.z\n setNormalized()\n initNormals.push(normal.x, normal.y, normal.z)\n } else if (j === last) {\n initNormals.push(prevNormal.x, prevNormal.y, prevNormal.z)\n } else {\n dx = px(j + 1) - px(j)\n dy = py(j + 1) - py(j)\n normal.x = dy * 1.0\n normal.y = -dx\n normal.z = dy * 0.0\n curNormal.x = normal.x\n curNormal.y = normal.y\n curNormal.z = normal.z\n normal.x += prevNormal.x\n normal.y += prevNormal.y\n normal.z += prevNormal.z\n setNormalized()\n initNormals.push(normal.x, normal.y, normal.z)\n prevNormal.x = curNormal.x\n prevNormal.y = curNormal.y\n prevNormal.z = curNormal.z\n }\n }\n for (let i = 0; i <= segments; i++) {\n const phi = phiStart + i * inverseSegments * phiLength\n const sin = Math.sin(phi)\n const cos = Math.cos(phi)\n for (let j = 0; j <= last; j++) {\n vertices.push(px(j) * sin, py(j), px(j) * cos)\n uvs.push(i / segments, j / (points.length - 1))\n const x = (initNormals[3 * j + 0] as number) * sin\n const y = initNormals[3 * j + 1] as number\n const z = (initNormals[3 * j + 0] as number) * cos\n normals.push(x, y, z)\n }\n }\n for (let i = 0; i < segments; i++) {\n for (let j = 0; j < points.length - 1; j++) {\n const base = j + i * points.length\n const a = base\n const b = base + points.length\n const c = base + points.length + 1\n const d = base + 1\n indices.push(a, b, d)\n indices.push(c, d, b)\n }\n }\n return pack('LatheGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n\nexport function torus(radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2): PrimitiveBuffers {\n const parameters = { radius, tube, radialSegments, tubularSegments, arc }\n radialSegments = Math.floor(radialSegments)\n tubularSegments = Math.floor(tubularSegments)\n const indices: number[] = []\n const vertices: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n for (let j = 0; j <= radialSegments; j++) {\n for (let i = 0; i <= tubularSegments; i++) {\n const u = (i / tubularSegments) * arc\n const v = (j / radialSegments) * Math.PI * 2\n const x = (radius + tube * Math.cos(v)) * Math.cos(u)\n const y = (radius + tube * Math.cos(v)) * Math.sin(u)\n const z = tube * Math.sin(v)\n vertices.push(x, y, z)\n const cx = radius * Math.cos(u)\n const cy = radius * Math.sin(u)\n const n = normalize3(x - cx, y - cy, z - 0)\n normals.push(n[0], n[1], n[2])\n uvs.push(i / tubularSegments)\n uvs.push(j / radialSegments)\n }\n }\n for (let j = 1; j <= radialSegments; j++) {\n for (let i = 1; i <= tubularSegments; i++) {\n const a = (tubularSegments + 1) * j + i - 1\n const b = (tubularSegments + 1) * (j - 1) + i - 1\n const c = (tubularSegments + 1) * (j - 1) + i\n const d = (tubularSegments + 1) * j + i\n indices.push(a, b, d)\n indices.push(b, c, d)\n }\n }\n return pack('TorusGeometry', parameters, { vertices, normals, uvs, indices, groups: [] })\n}\n","import type { HoleSpec, PrimitiveBuffers, Vec3 } from '../types'\nimport { indexArray } from './three-generators'\n\n/**\n * A box (centred, `size = [w, h, d]`) minus rectangular prisms that go all the way through it along z: the cheap, exact boolean (walls with\n * windows and doors). The face is cut into a grid at every hole edge; each solid cell gets its front and back quads, and every cell edge between\n * solid and empty (a hole or the outside) gets a quad over the depth facing the empty side, so the outer sides and the reveals come out of the\n * same rule. Front uvs map the face to [0, 1]; side uvs run along the edge and the depth.\n */\nexport function difference(size: Vec3, subtract: readonly HoleSpec[]): PrimitiveBuffers {\n const [w, h, d] = size\n const hw = w / 2\n const hh = h / 2\n const hd = d / 2\n const holes = subtract\n .map((hole) => ({ x0: Math.max(-hw, Math.min(hole.min[0], hole.max[0])), x1: Math.min(hw, Math.max(hole.min[0], hole.max[0])), y0: Math.max(-hh, Math.min(hole.min[1], hole.max[1])), y1: Math.min(hh, Math.max(hole.min[1], hole.max[1])) }))\n .filter((hole) => hole.x1 > hole.x0 && hole.y1 > hole.y0)\n const cuts = (lo: number, hi: number, values: number[]): number[] => [...new Set([lo, hi, ...values.filter((v) => v > lo && v < hi)])].sort((a, b) => a - b)\n const xs = cuts(-hw, hw, holes.flatMap((hole) => [hole.x0, hole.x1]))\n const ys = cuts(-hh, hh, holes.flatMap((hole) => [hole.y0, hole.y1]))\n const nx = xs.length - 1\n const ny = ys.length - 1\n const solid = (i: number, j: number): boolean => {\n if (i < 0 || j < 0 || i >= nx || j >= ny) return false\n const cx = ((xs[i] as number) + (xs[i + 1] as number)) / 2\n const cy = ((ys[j] as number) + (ys[j + 1] as number)) / 2\n return !holes.some((hole) => cx > hole.x0 && cx < hole.x1 && cy > hole.y0 && cy < hole.y1)\n }\n const positions: number[] = []\n const normals: number[] = []\n const uvs: number[] = []\n const indices: number[] = []\n const quad = (corners: readonly (readonly [number, number, number])[], normal: readonly [number, number, number], uv: readonly (readonly [number, number])[]): void => {\n const base = positions.length / 3\n for (let k = 0; k < 4; k++) {\n positions.push(...(corners[k] as [number, number, number]))\n normals.push(...normal)\n uvs.push(...(uv[k] as [number, number]))\n }\n indices.push(base, base + 1, base + 2, base, base + 2, base + 3)\n }\n const fu = (x: number): number => (x + hw) / w\n const fv = (y: number): number => (y + hh) / h\n for (let j = 0; j < ny; j++) {\n for (let i = 0; i < nx; i++) {\n if (!solid(i, j)) continue\n const x0 = xs[i] as number\n const x1 = xs[i + 1] as number\n const y0 = ys[j] as number\n const y1 = ys[j + 1] as number\n quad([[x0, y0, hd], [x1, y0, hd], [x1, y1, hd], [x0, y1, hd]], [0, 0, 1], [[fu(x0), fv(y0)], [fu(x1), fv(y0)], [fu(x1), fv(y1)], [fu(x0), fv(y1)]])\n quad([[x1, y0, -hd], [x0, y0, -hd], [x0, y1, -hd], [x1, y1, -hd]], [0, 0, -1], [[1 - fu(x1), fv(y0)], [1 - fu(x0), fv(y0)], [1 - fu(x0), fv(y1)], [1 - fu(x1), fv(y1)]])\n const zu = (z: number): number => (z + hd) / d\n if (!solid(i - 1, j)) quad([[x0, y0, -hd], [x0, y0, hd], [x0, y1, hd], [x0, y1, -hd]], [-1, 0, 0], [[zu(-hd), fv(y0)], [zu(hd), fv(y0)], [zu(hd), fv(y1)], [zu(-hd), fv(y1)]])\n if (!solid(i + 1, j)) quad([[x1, y0, hd], [x1, y0, -hd], [x1, y1, -hd], [x1, y1, hd]], [1, 0, 0], [[zu(hd), fv(y0)], [zu(-hd), fv(y0)], [zu(-hd), fv(y1)], [zu(hd), fv(y1)]])\n if (!solid(i, j - 1)) quad([[x0, y0, -hd], [x1, y0, -hd], [x1, y0, hd], [x0, y0, hd]], [0, -1, 0], [[fu(x0), zu(-hd)], [fu(x1), zu(-hd)], [fu(x1), zu(hd)], [fu(x0), zu(hd)]])\n if (!solid(i, j + 1)) quad([[x0, y1, hd], [x1, y1, hd], [x1, y1, -hd], [x0, y1, -hd]], [0, 1, 0], [[fu(x0), zu(hd)], [fu(x1), zu(hd)], [fu(x1), zu(-hd)], [fu(x0), zu(-hd)]])\n }\n }\n return {\n type: 'BufferGeometry',\n parameters: { size: [w, h, d], subtract: holes.map((hole) => ({ min: [hole.x0, hole.y0], max: [hole.x1, hole.y1] })) },\n positions: new Float32Array(positions),\n normals: new Float32Array(normals),\n uvs: new Float32Array(uvs),\n indices: indexArray(indices),\n groups: [],\n }\n}\n","// Copy of three.js r160 src/extras/Earcut.js (MIT), itself a port of mapbox/earcut v2.2.4 (ISC), with types added and the logic kept as is so triangulation matches three\n/**\n * Port from https://github.com/mapbox/earcut (v2.2.4)\n */\n\nconst Earcut = {\n\n\ttriangulate: function ( data: ArrayLike<number>, holeIndices?: ArrayLike<number> | null, dim = 2 ): number[] {\n\n\t\tconst hasHoles = holeIndices && holeIndices.length;\n\t\tconst outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;\n\t\tlet outerNode = linkedList( data, 0, outerLen, dim, true );\n\t\tconst triangles: number[] = [];\n\n\t\tif ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;\n\n\t\tlet minX, minY, maxX, maxY, x, y, invSize;\n\n\t\tif ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );\n\n\t\t// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n\t\tif ( data.length > 80 * dim ) {\n\n\t\t\tminX = maxX = data[ 0 ];\n\t\t\tminY = maxY = data[ 1 ];\n\n\t\t\tfor ( let i = dim; i < outerLen; i += dim ) {\n\n\t\t\t\tx = data[ i ];\n\t\t\t\ty = data[ i + 1 ];\n\t\t\t\tif ( x < minX ) minX = x;\n\t\t\t\tif ( y < minY ) minY = y;\n\t\t\t\tif ( x > maxX ) maxX = x;\n\t\t\t\tif ( y > maxY ) maxY = y;\n\n\t\t\t}\n\n\t\t\t// minX, minY and invSize are later used to transform coords into integers for z-order calculation\n\t\t\tinvSize = Math.max( maxX - minX, maxY - minY );\n\t\t\tinvSize = invSize !== 0 ? 32767 / invSize : 0;\n\n\t\t}\n\n\t\tearcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );\n\n\t\treturn triangles;\n\n\t}\n\n};\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList( data: ArrayLike<number>, start: number, end: number, dim: number, clockwise: boolean ): EarNode | undefined {\n\n\tlet i: number, last: EarNode | undefined;\n\n\tif ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {\n\n\t\tfor ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t} else {\n\n\t\tfor ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );\n\n\t}\n\n\tif ( last && equals( last, last.next ) ) {\n\n\t\tremoveNode( last );\n\t\tlast = last.next;\n\n\t}\n\n\treturn last;\n\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints( start: EarNode | null | undefined, end?: EarNode | null ): EarNode | null | undefined {\n\n\tif ( ! start ) return start;\n\tif ( ! end ) end = start;\n\n\tlet p = start,\n\t\tagain;\n\tdo {\n\n\t\tagain = false;\n\n\t\tif ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {\n\n\t\t\tremoveNode( p );\n\t\t\tp = end = p.prev;\n\t\t\tif ( p === p.next ) break;\n\t\t\tagain = true;\n\n\t\t} else {\n\n\t\t\tp = p.next;\n\n\t\t}\n\n\t} while ( again || p !== end );\n\n\treturn end;\n\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked( ear: EarNode | null | undefined, triangles: number[], dim: number, minX: number | undefined, minY: number | undefined, invSize: number | undefined, pass: number ): void {\n\n\tif ( ! ear ) return;\n\n\t// interlink polygon nodes in z-order\n\tif ( ! pass && invSize ) indexCurve( ear, minX as number, minY as number, invSize ); // set with invSize\n\n\tlet stop = ear,\n\t\tprev, next;\n\n\t// iterate through ears, slicing them one by one\n\twhile ( ear.prev !== ear.next ) {\n\n\t\tprev = ear.prev;\n\t\tnext = ear.next;\n\n\t\tif ( invSize ? isEarHashed( ear, minX as number, minY as number, invSize ) : isEar( ear ) ) {\n\n\t\t\t// cut off the triangle\n\t\t\ttriangles.push( prev.i / dim | 0 );\n\t\t\ttriangles.push( ear.i / dim | 0 );\n\t\t\ttriangles.push( next.i / dim | 0 );\n\n\t\t\tremoveNode( ear );\n\n\t\t\t// skipping the next vertex leads to less sliver triangles\n\t\t\tear = next.next;\n\t\t\tstop = next.next;\n\n\t\t\tcontinue;\n\n\t\t}\n\n\t\tear = next;\n\n\t\t// if we looped through the whole remaining polygon and can't find any more ears\n\t\tif ( ear === stop ) {\n\n\t\t\t// try filtering points and slicing again\n\t\t\tif ( ! pass ) {\n\n\t\t\t\tearcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );\n\n\t\t\t\t// if this didn't work, try curing all small self-intersections locally\n\n\t\t\t} else if ( pass === 1 ) {\n\n\t\t\t\tear = cureLocalIntersections( filterPoints( ear )!, triangles, dim );\n\t\t\t\tearcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );\n\n\t\t\t\t// as a last resort, try splitting the remaining polygon into two\n\n\t\t\t} else if ( pass === 2 ) {\n\n\t\t\t\tsplitEarcut( ear, triangles, dim, minX, minY, invSize );\n\n\t\t\t}\n\n\t\t\tbreak;\n\n\t\t}\n\n\t}\n\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar( ear: EarNode ): boolean {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\t// now make sure we don't have other points inside the potential ear\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\tlet p = c.next;\n\twhile ( p !== a ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&\n\t\t\tarea( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.next;\n\n\t}\n\n\treturn true;\n\n}\n\nfunction isEarHashed( ear: EarNode, minX: number, minY: number, invSize: number ): boolean {\n\n\tconst a = ear.prev,\n\t\tb = ear,\n\t\tc = ear.next;\n\n\tif ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear\n\n\tconst ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n\t// triangle bbox; min & max are calculated like this for speed\n\tconst x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),\n\t\ty0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),\n\t\tx1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),\n\t\ty1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );\n\n\t// z-order range for the current triangle bbox;\n\tconst minZ = zOrder( x0, y0, minX, minY, invSize ),\n\t\tmaxZ = zOrder( x1, y1, minX, minY, invSize );\n\n\tlet p = ear.prevZ,\n\t\tn = ear.nextZ;\n\n\t// look for points inside the triangle in both directions\n\twhile ( p && p.z >= minZ && n && n.z <= maxZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\t// look for remaining points in decreasing z-order\n\twhile ( p && p.z >= minZ ) {\n\n\t\tif ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;\n\t\tp = p.prevZ;\n\n\t}\n\n\t// look for remaining points in increasing z-order\n\twhile ( n && n.z <= maxZ ) {\n\n\t\tif ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n\t\t\tpointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;\n\t\tn = n.nextZ;\n\n\t}\n\n\treturn true;\n\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections( start: EarNode, triangles: number[], dim: number ): EarNode {\n\n\tlet p = start;\n\tdo {\n\n\t\tconst a = p.prev,\n\t\t\tb = p.next.next;\n\n\t\tif ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {\n\n\t\t\ttriangles.push( a.i / dim | 0 );\n\t\t\ttriangles.push( p.i / dim | 0 );\n\t\t\ttriangles.push( b.i / dim | 0 );\n\n\t\t\t// remove two nodes involved\n\t\t\tremoveNode( p );\n\t\t\tremoveNode( p.next );\n\n\t\t\tp = start = b;\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn filterPoints( p )!;\n\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut( start: EarNode, triangles: number[], dim: number, minX: number | undefined, minY: number | undefined, invSize: number | undefined ): void {\n\n\t// look for a valid diagonal that divides the polygon into two\n\tlet a = start;\n\tdo {\n\n\t\tlet b = a.next.next;\n\t\twhile ( b !== a.prev ) {\n\n\t\t\tif ( a.i !== b.i && isValidDiagonal( a, b ) ) {\n\n\t\t\t\t// split the polygon in two by the diagonal\n\t\t\t\tlet c = splitPolygon( a, b );\n\n\t\t\t\t// filter colinear points around the cuts\n\t\t\t\ta = filterPoints( a, a.next )!;\n\t\t\t\tc = filterPoints( c, c.next )!;\n\n\t\t\t\t// run earcut on each half\n\t\t\t\tearcutLinked( a, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\tearcutLinked( c, triangles, dim, minX, minY, invSize, 0 );\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tb = b.next;\n\n\t\t}\n\n\t\ta = a.next;\n\n\t} while ( a !== start );\n\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles( data: ArrayLike<number>, holeIndices: ArrayLike<number>, outerNode: EarNode, dim: number ): EarNode {\n\n\tconst queue: EarNode[] = [];\n\tlet i, len, start, end, list;\n\n\tfor ( i = 0, len = holeIndices.length; i < len; i ++ ) {\n\n\t\tstart = holeIndices[ i ] * dim;\n\t\tend = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;\n\t\tlist = linkedList( data, start, end, dim, false )!;\n\t\tif ( list === list.next ) list.steiner = true;\n\t\tqueue.push( getLeftmost( list ) );\n\n\t}\n\n\tqueue.sort( compareX );\n\n\t// process holes from left to right\n\tfor ( i = 0; i < queue.length; i ++ ) {\n\n\t\touterNode = eliminateHole( queue[ i ], outerNode );\n\n\t}\n\n\treturn outerNode;\n\n}\n\nfunction compareX( a: EarNode, b: EarNode ): number {\n\n\treturn a.x - b.x;\n\n}\n\n// find a bridge between vertices that connects hole with an outer ring and link it\nfunction eliminateHole( hole: EarNode, outerNode: EarNode ): EarNode {\n\n\tconst bridge = findHoleBridge( hole, outerNode );\n\tif ( ! bridge ) {\n\n\t\treturn outerNode;\n\n\t}\n\n\tconst bridgeReverse = splitPolygon( bridge, hole );\n\n\t// filter collinear points around the cuts\n\tfilterPoints( bridgeReverse, bridgeReverse.next );\n\treturn filterPoints( bridge, bridge.next )!;\n\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge( hole: EarNode, outerNode: EarNode ): EarNode | null {\n\n\tlet p = outerNode,\n\t\tqx = - Infinity,\n\t\tm;\n\n\tconst hx = hole.x, hy = hole.y;\n\n\t// find a segment intersected by a ray from the hole's leftmost point to the left;\n\t// segment's endpoint with lesser x will be potential connection point\n\tdo {\n\n\t\tif ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {\n\n\t\t\tconst x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );\n\t\t\tif ( x <= hx && x > qx ) {\n\n\t\t\t\tqx = x;\n\t\t\t\tm = p.x < p.next.x ? p : p.next;\n\t\t\t\tif ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== outerNode );\n\n\tif ( ! m ) return null;\n\n\t// look for points inside the triangle of hole point, segment intersection and endpoint;\n\t// if there are no points found, we have a valid connection;\n\t// otherwise choose the point of the minimum angle with the ray as connection point\n\n\tconst stop = m,\n\t\tmx = m.x,\n\t\tmy = m.y;\n\tlet tanMin = Infinity, tan;\n\n\tp = m;\n\n\tdo {\n\n\t\tif ( hx >= p.x && p.x >= mx && hx !== p.x &&\n\t\t\t\tpointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {\n\n\t\t\ttan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential\n\n\t\t\tif ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {\n\n\t\t\t\tm = p;\n\t\t\t\ttanMin = tan;\n\n\t\t\t}\n\n\t\t}\n\n\t\tp = p.next;\n\n\t} while ( p !== stop );\n\n\treturn m;\n\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector( m: EarNode, p: EarNode ): boolean {\n\n\treturn area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;\n\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve( start: EarNode, minX: number, minY: number, invSize: number ): void {\n\n\tlet p = start;\n\tdo {\n\n\t\tif ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );\n\t\tp.prevZ = p.prev;\n\t\tp.nextZ = p.next;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\tp.prevZ!.nextZ = null;\n\tp.prevZ = null;\n\n\tsortLinked( p );\n\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked( list: EarNode | null ): EarNode | null {\n\n\tlet i, p: EarNode | null, q: EarNode | null, e: EarNode, tail: EarNode | null, numMerges, pSize, qSize,\n\t\tinSize = 1;\n\n\tdo {\n\n\t\tp = list;\n\t\tlist = null;\n\t\ttail = null;\n\t\tnumMerges = 0;\n\n\t\twhile ( p ) {\n\n\t\t\tnumMerges ++;\n\t\t\tq = p;\n\t\t\tpSize = 0;\n\t\t\tfor ( i = 0; i < inSize; i ++ ) {\n\n\t\t\t\tpSize ++;\n\t\t\t\tq = q!.nextZ;\n\t\t\t\tif ( ! q ) break;\n\n\t\t\t}\n\n\t\t\tqSize = inSize;\n\n\t\t\twhile ( pSize > 0 || ( qSize > 0 && q ) ) {\n\n\t\t\t\tif ( pSize !== 0 && ( qSize === 0 || ! q || p!.z <= q.z ) ) {\n\n\t\t\t\t\te = p!;\n\t\t\t\t\tp = p!.nextZ;\n\t\t\t\t\tpSize --;\n\n\t\t\t\t} else {\n\n\t\t\t\t\te = q!;\n\t\t\t\t\tq = q!.nextZ;\n\t\t\t\t\tqSize --;\n\n\t\t\t\t}\n\n\t\t\t\tif ( tail ) tail.nextZ = e;\n\t\t\t\telse list = e;\n\n\t\t\t\te.prevZ = tail;\n\t\t\t\ttail = e;\n\n\t\t\t}\n\n\t\t\tp = q;\n\n\t\t}\n\n\t\ttail!.nextZ = null;\n\t\tinSize *= 2;\n\n\t} while ( numMerges > 1 );\n\n\treturn list;\n\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder( x: number, y: number, minX: number, minY: number, invSize: number ): number {\n\n\t// coords are transformed into non-negative 15-bit integer range\n\tx = ( x - minX ) * invSize | 0;\n\ty = ( y - minY ) * invSize | 0;\n\n\tx = ( x | ( x << 8 ) ) & 0x00FF00FF;\n\tx = ( x | ( x << 4 ) ) & 0x0F0F0F0F;\n\tx = ( x | ( x << 2 ) ) & 0x33333333;\n\tx = ( x | ( x << 1 ) ) & 0x55555555;\n\n\ty = ( y | ( y << 8 ) ) & 0x00FF00FF;\n\ty = ( y | ( y << 4 ) ) & 0x0F0F0F0F;\n\ty = ( y | ( y << 2 ) ) & 0x33333333;\n\ty = ( y | ( y << 1 ) ) & 0x55555555;\n\n\treturn x | ( y << 1 );\n\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost( start: EarNode ): EarNode {\n\n\tlet p = start,\n\t\tleftmost = start;\n\tdo {\n\n\t\tif ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;\n\t\tp = p.next;\n\n\t} while ( p !== start );\n\n\treturn leftmost;\n\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle( ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number ): boolean {\n\n\treturn ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&\n ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&\n ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );\n\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal( a: EarNode, b: EarNode ): boolean | number { // truthy: `area` can be the answer\n\n\treturn a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges\n ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible\n ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors\n equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case\n\n}\n\n// signed area of a triangle\nfunction area( p: EarNode, q: EarNode, r: EarNode ): number {\n\n\treturn ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );\n\n}\n\n// check if two points are equal\nfunction equals( p1: EarNode, p2: EarNode ): boolean {\n\n\treturn p1.x === p2.x && p1.y === p2.y;\n\n}\n\n// check if two segments intersect\nfunction intersects( p1: EarNode, q1: EarNode, p2: EarNode, q2: EarNode ): boolean {\n\n\tconst o1 = sign( area( p1, q1, p2 ) );\n\tconst o2 = sign( area( p1, q1, q2 ) );\n\tconst o3 = sign( area( p2, q2, p1 ) );\n\tconst o4 = sign( area( p2, q2, q1 ) );\n\n\tif ( o1 !== o2 && o3 !== o4 ) return true; // general case\n\n\tif ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n\tif ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n\tif ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n\tif ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n\treturn false;\n\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment( p: EarNode, q: EarNode, r: EarNode ): boolean {\n\n\treturn q.x <= Math.max( p.x, r.x ) && q.x >= Math.min( p.x, r.x ) && q.y <= Math.max( p.y, r.y ) && q.y >= Math.min( p.y, r.y );\n\n}\n\nfunction sign( num: number ): number {\n\n\treturn num > 0 ? 1 : num < 0 ? - 1 : 0;\n\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon( a: EarNode, b: EarNode ): boolean {\n\n\tlet p = a;\n\tdo {\n\n\t\tif ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n\t\t\tintersects( p, p.next, a, b ) ) return true;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn false;\n\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside( a: EarNode, b: EarNode ): boolean {\n\n\treturn area( a.prev, a, a.next ) < 0 ?\n\t\tarea( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :\n\t\tarea( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;\n\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside( a: EarNode, b: EarNode ): boolean {\n\n\tlet p = a,\n\t\tinside = false;\n\tconst px = ( a.x + b.x ) / 2,\n\t\tpy = ( a.y + b.y ) / 2;\n\tdo {\n\n\t\tif ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&\n\t\t\t( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )\n\t\t\tinside = ! inside;\n\t\tp = p.next;\n\n\t} while ( p !== a );\n\n\treturn inside;\n\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon( a: EarNode, b: EarNode ): EarNode {\n\n\tconst a2 = new Node( a.i, a.x, a.y ),\n\t\tb2 = new Node( b.i, b.x, b.y ),\n\t\tan = a.next,\n\t\tbp = b.prev;\n\n\ta.next = b;\n\tb.prev = a;\n\n\ta2.next = an;\n\tan.prev = a2;\n\n\tb2.next = a2;\n\ta2.prev = b2;\n\n\tbp.next = b2;\n\tb2.prev = bp;\n\n\treturn b2;\n\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode( i: number, x: number, y: number, last: EarNode | null | undefined ): EarNode {\n\n\tconst p = new Node( i, x, y );\n\n\tif ( ! last ) {\n\n\t\tp.prev = p;\n\t\tp.next = p;\n\n\t} else {\n\n\t\tp.next = last.next;\n\t\tp.prev = last;\n\t\tlast.next.prev = p;\n\t\tlast.next = p;\n\n\t}\n\n\treturn p;\n\n}\n\nfunction removeNode( p: EarNode ): void {\n\n\tp.next.prev = p.prev;\n\tp.prev.next = p.next;\n\n\tif ( p.prevZ ) p.prevZ.nextZ = p.nextZ;\n\tif ( p.nextZ ) p.nextZ.prevZ = p.prevZ;\n\n}\n\nclass Node {\n\n\t// vertex index in coordinates array\n\tdeclare i: number;\n\t// vertex coordinates\n\tdeclare x: number;\n\tdeclare y: number;\n\t// previous and next vertex nodes in a polygon ring (set as soon as the node is linked: a node in a ring always has both)\n\tdeclare prev: EarNode;\n\tdeclare next: EarNode;\n\t// z-order curve value\n\tdeclare z: number;\n\t// previous and next nodes in z-order\n\tdeclare prevZ: EarNode | null;\n\tdeclare nextZ: EarNode | null;\n\t// indicates whether this is a steiner point\n\tdeclare steiner: boolean;\n\n\tconstructor( i: number, x: number, y: number ) {\n\n\t\t// vertex index in coordinates array\n\t\tthis.i = i;\n\n\t\t// vertex coordinates\n\t\tthis.x = x;\n\t\tthis.y = y;\n\n\t\t// previous and next vertex nodes in a polygon ring\n\t\tthis.prev = null as unknown as EarNode;\n\t\tthis.next = null as unknown as EarNode;\n\n\t\t// z-order curve value\n\t\tthis.z = 0;\n\n\t\t// previous and next nodes in z-order\n\t\tthis.prevZ = null;\n\t\tthis.nextZ = null;\n\n\t\t// indicates whether this is a steiner point\n\t\tthis.steiner = false;\n\n\t}\n\n}\n\n/** A vertex of the polygon ring. */\ntype EarNode = Node;\n\nfunction signedArea( data: ArrayLike<number>, start: number, end: number, dim: number ): number {\n\n\tlet sum = 0;\n\tfor ( let i = start, j = end - dim; i < end; i += dim ) {\n\n\t\tsum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );\n\t\tj = i;\n\n\t}\n\n\treturn sum;\n\n}\n\nexport { Earcut };\n","/*\n * three.js r160 `ExtrudeGeometry` (MIT) for straight-edged shapes, ported line by line: the outline is sampled as `Shape.extractPoints` samples a\n * path of `LineCurve`s, triangulated by three's `ShapeUtils.triangulateShape` (Earcut), bevelled and walled in the same order, with the\n * `WorldUVGenerator` uvs and `computeVertexNormals` on the Float32 positions. Path extrusion (`extrudePath`) is not supported.\n */\nimport type { BevelSpec, GeometryGroup, PrimitiveBuffers, ShapeOutline, Vec2 } from '../types'\nimport { Earcut } from './earcut'\n\ninterface P {\n x: number\n y: number\n}\n\nconst equals = (a: P, b: P): boolean => a.x === b.x && a.y === b.y\n\n/** `LineCurve.getPoint(t)`. */\nconst linePoint = (v1: P, v2: P, t: number): P => (t === 1 ? { x: v2.x, y: v2.y } : { x: (v2.x - v1.x) * t + v1.x, y: (v2.y - v1.y) * t + v1.y })\n\n/** `Path.setFromPoints(points).getPoints()`: one `LineCurve` per edge, resolution 1, consecutive duplicates dropped, not closed. */\nfunction pathPoints(points: readonly Vec2[]): P[] {\n const out: P[] = []\n let last: P | undefined\n for (let i = 1; i < points.length; i++) {\n const v1 = { x: (points[i - 1] as Vec2)[0], y: (points[i - 1] as Vec2)[1] }\n const v2 = { x: (points[i] as Vec2)[0], y: (points[i] as Vec2)[1] }\n for (let d = 0; d <= 1; d++) {\n const point = linePoint(v1, v2, d / 1)\n if (last && equals(last, point)) continue\n out.push(point)\n last = point\n }\n }\n return out\n}\n\nfunction area(contour: readonly P[]): number {\n const n = contour.length\n let a = 0.0\n for (let p = n - 1, q = 0; q < n; p = q++) a += (contour[p] as P).x * (contour[q] as P).y - (contour[q] as P).x * (contour[p] as P).y\n return a * 0.5\n}\nconst isClockWise = (pts: readonly P[]): boolean => area(pts) < 0\n\nfunction removeDupEndPts(points: P[]): void {\n const l = points.length\n if (l > 2 && equals(points[l - 1] as P, points[0] as P)) points.pop()\n}\n\nfunction triangulateShape(contour: P[], holes: P[][]): number[][] {\n const vertices: number[] = []\n const holeIndices: number[] = []\n const faces: number[][] = []\n removeDupEndPts(contour)\n for (const p of contour) vertices.push(p.x, p.y)\n let holeIndex = contour.length\n holes.forEach(removeDupEndPts)\n for (let i = 0; i < holes.length; i++) {\n holeIndices.push(holeIndex)\n holeIndex += (holes[i] as P[]).length\n for (const p of holes[i] as P[]) vertices.push(p.x, p.y)\n }\n const triangles: number[] = Earcut.triangulate(vertices, holeIndices)\n for (let i = 0; i < triangles.length; i += 3) faces.push(triangles.slice(i, i + 3))\n return faces\n}\n\n/** `BufferGeometry.computeVertexNormals` for non-indexed Float32 positions, then `normalizeNormals`, both stored as Float32. */\nexport function computeVertexNormals(positions: Float32Array, indices?: ArrayLike<number>): Float32Array {\n const normals = new Float32Array(positions.length)\n const get = (array: Float32Array, i: number): [number, number, number] => [array[i * 3] as number, array[i * 3 + 1] as number, array[i * 3 + 2] as number]\n const face = (vA: number, vB: number, vC: number): [number, number, number] => {\n const pA = get(positions, vA)\n const pB = get(positions, vB)\n const pC = get(positions, vC)\n const cb = [pC[0] - pB[0], pC[1] - pB[1], pC[2] - pB[2]] as const\n const ab = [pA[0] - pB[0], pA[1] - pB[1], pA[2] - pB[2]] as const\n // Vector3.cross\n return [cb[1] * ab[2] - cb[2] * ab[1], cb[2] * ab[0] - cb[0] * ab[2], cb[0] * ab[1] - cb[1] * ab[0]]\n }\n const set = (i: number, x: number, y: number, z: number): void => {\n normals[i * 3] = x\n normals[i * 3 + 1] = y\n normals[i * 3 + 2] = z\n }\n if (indices) {\n for (let i = 0; i < indices.length; i += 3) {\n const vA = indices[i] as number\n const vB = indices[i + 1] as number\n const vC = indices[i + 2] as number\n const cb = face(vA, vB, vC)\n for (const v of [vA, vB, vC]) {\n const n = get(normals, v)\n set(v, n[0] + cb[0], n[1] + cb[1], n[2] + cb[2])\n }\n }\n } else {\n for (let i = 0; i < positions.length / 3; i += 3) {\n const cb = face(i, i + 1, i + 2)\n set(i, cb[0], cb[1], cb[2])\n set(i + 1, cb[0], cb[1], cb[2])\n set(i + 2, cb[0], cb[1], cb[2])\n }\n }\n for (let i = 0; i < normals.length / 3; i++) {\n const [x, y, z] = get(normals, i)\n const s = 1 / (Math.sqrt(x * x + y * y + z * z) || 1)\n set(i, x * s, y * s, z * s)\n }\n return normals\n}\n\nexport function extrude(outline: ShapeOutline, depth = 1, steps = 1, bevel: false | BevelSpec | undefined = undefined): PrimitiveBuffers {\n const parameters = { shape: outline, depth, steps, bevel: bevel ?? {} }\n const verticesArray: number[] = []\n const uvArray: number[] = []\n const groups: GeometryGroup[] = []\n const placeholder: number[] = []\n\n const bevelEnabled = bevel !== false\n const spec: BevelSpec = bevel === false || bevel === undefined ? {} : bevel\n let bevelThickness = spec.thickness !== undefined ? spec.thickness : 0.2\n let bevelSize = spec.size !== undefined ? spec.size : bevelThickness - 0.1\n let bevelOffset = spec.offset !== undefined ? spec.offset : 0\n let bevelSegments = spec.segments !== undefined ? spec.segments : 3\n if (!bevelEnabled) {\n bevelSegments = 0\n bevelThickness = 0\n bevelSize = 0\n bevelOffset = 0\n }\n\n let vertices = pathPoints(outline.outer)\n const holes = (outline.holes ?? []).map(pathPoints)\n const reverse = !isClockWise(vertices)\n if (reverse) {\n vertices = vertices.reverse()\n for (let h = 0; h < holes.length; h++) {\n const ahole = holes[h] as P[]\n if (isClockWise(ahole)) holes[h] = ahole.reverse()\n }\n }\n const faces = triangulateShape(vertices, holes)\n const contour = vertices\n for (const ahole of holes) vertices = vertices.concat(ahole)\n\n const scalePt2 = (pt: P, vec: P, size: number): P => ({ x: pt.x + vec.x * size, y: pt.y + vec.y * size })\n const vlen = vertices.length\n const flen = faces.length\n\n const getBevelVec = (inPt: P, inPrev: P, inNext: P): P => {\n let vTransX: number\n let vTransY: number\n let shrinkBy: number\n const vPrevX = inPt.x - inPrev.x\n const vPrevY = inPt.y - inPrev.y\n const vNextX = inNext.x - inPt.x\n const vNextY = inNext.y - inPt.y\n const vPrevLensq = vPrevX * vPrevX + vPrevY * vPrevY\n const collinear0 = vPrevX * vNextY - vPrevY * vNextX\n if (Math.abs(collinear0) > Number.EPSILON) {\n const vPrevLen = Math.sqrt(vPrevLensq)\n const vNextLen = Math.sqrt(vNextX * vNextX + vNextY * vNextY)\n const ptPrevShiftX = inPrev.x - vPrevY / vPrevLen\n const ptPrevShiftY = inPrev.y + vPrevX / vPrevLen\n const ptNextShiftX = inNext.x - vNextY / vNextLen\n const ptNextShiftY = inNext.y + vNextX / vNextLen\n const sf = ((ptNextShiftX - ptPrevShiftX) * vNextY - (ptNextShiftY - ptPrevShiftY) * vNextX) / (vPrevX * vNextY - vPrevY * vNextX)\n vTransX = ptPrevShiftX + vPrevX * sf - inPt.x\n vTransY = ptPrevShiftY + vPrevY * sf - inPt.y\n const vTransLensq = vTransX * vTransX + vTransY * vTransY\n if (vTransLensq <= 2) return { x: vTransX, y: vTransY }\n shrinkBy = Math.sqrt(vTransLensq / 2)\n } else {\n let directionEq = false\n if (vPrevX > Number.EPSILON) {\n if (vNextX > Number.EPSILON) directionEq = true\n } else if (vPrevX < -Number.EPSILON) {\n if (vNextX < -Number.EPSILON) directionEq = true\n } else if (Math.sign(vPrevY) === Math.sign(vNextY)) {\n directionEq = true\n }\n if (directionEq) {\n vTransX = -vPrevY\n vTransY = vPrevX\n shrinkBy = Math.sqrt(vPrevLensq)\n } else {\n vTransX = vPrevX\n vTransY = vPrevY\n shrinkBy = Math.sqrt(vPrevLensq / 2)\n }\n }\n return { x: vTransX / shrinkBy, y: vTransY / shrinkBy }\n }\n\n const movements = (ring: readonly P[]): P[] => {\n const out: P[] = []\n for (let i = 0, il = ring.length, j = il - 1, k = i + 1; i < il; i++, j++, k++) {\n if (j === il) j = 0\n if (k === il) k = 0\n out[i] = getBevelVec(ring[i] as P, ring[j] as P, ring[k] as P)\n }\n return out\n }\n const contourMovements = movements(contour)\n const holesMovements: P[][] = []\n let verticesMovements = contourMovements.concat()\n for (const ahole of holes) {\n const oneHoleMovements = movements(ahole)\n holesMovements.push(oneHoleMovements)\n verticesMovements = verticesMovements.concat(oneHoleMovements)\n }\n\n const v = (x: number, y: number, z: number): void => {\n placeholder.push(x)\n placeholder.push(y)\n placeholder.push(z)\n }\n const bevelLayer = (b: number, zOf: (z: number) => number): void => {\n const t = b / bevelSegments\n const z = bevelThickness * Math.cos((t * Math.PI) / 2)\n const bs = bevelSize * Math.sin((t * Math.PI) / 2) + bevelOffset\n for (let i = 0; i < contour.length; i++) {\n const vert = scalePt2(contour[i] as P, contourMovements[i] as P, bs)\n v(vert.x, vert.y, zOf(z))\n }\n for (let h = 0; h < holes.length; h++) {\n const ahole = holes[h] as P[]\n const oneHoleMovements = holesMovements[h] as P[]\n for (let i = 0; i < ahole.length; i++) {\n const vert = scalePt2(ahole[i] as P, oneHoleMovements[i] as P, bs)\n v(vert.x, vert.y, zOf(z))\n }\n }\n }\n for (let b = 0; b < bevelSegments; b++) bevelLayer(b, (z) => -z)\n const bs = bevelSize + bevelOffset\n for (let i = 0; i < vlen; i++) {\n const vert = bevelEnabled ? scalePt2(vertices[i] as P, verticesMovements[i] as P, bs) : (vertices[i] as P)\n v(vert.x, vert.y, 0)\n }\n for (let s = 1; s <= steps; s++) {\n for (let i = 0; i < vlen; i++) {\n const vert = bevelEnabled ? scalePt2(vertices[i] as P, verticesMovements[i] as P, bs) : (vertices[i] as P)\n v(vert.x, vert.y, (depth / steps) * s)\n }\n }\n for (let b = bevelSegments - 1; b >= 0; b--) bevelLayer(b, (z) => depth + z)\n\n const addVertex = (index: number): void => {\n verticesArray.push(placeholder[index * 3 + 0] as number)\n verticesArray.push(placeholder[index * 3 + 1] as number)\n verticesArray.push(placeholder[index * 3 + 2] as number)\n }\n const addUV = (x: number, y: number): void => {\n uvArray.push(x)\n uvArray.push(y)\n }\n const at = (index: number, axis: number): number => verticesArray[index * 3 + axis] as number\n const f3 = (a: number, b: number, c: number): void => {\n addVertex(a)\n addVertex(b)\n addVertex(c)\n const nextIndex = verticesArray.length / 3\n for (const index of [nextIndex - 3, nextIndex - 2, nextIndex - 1]) addUV(at(index, 0), at(index, 1))\n }\n const f4 = (a: number, b: number, c: number, d: number): void => {\n addVertex(a)\n addVertex(b)\n addVertex(d)\n addVertex(b)\n addVertex(c)\n addVertex(d)\n const nextIndex = verticesArray.length / 3\n const iA = nextIndex - 6\n const iB = nextIndex - 3\n const iC = nextIndex - 2\n const iD = nextIndex - 1\n const byX = Math.abs(at(iA, 1) - at(iB, 1)) < Math.abs(at(iA, 0) - at(iB, 0))\n const uv = (index: number): [number, number] => [byX ? at(index, 0) : at(index, 1), 1 - at(index, 2)]\n const uvs = [uv(iA), uv(iB), uv(iC), uv(iD)]\n for (const k of [0, 1, 3, 1, 2, 3]) addUV(...(uvs[k] as [number, number]))\n }\n\n // lid faces\n let start = verticesArray.length / 3\n if (bevelEnabled) {\n let offset = 0\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[2] as number) + offset, (face[1] as number) + offset, (face[0] as number) + offset)\n }\n const layer = steps + bevelSegments * 2\n offset = vlen * layer\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[0] as number) + offset, (face[1] as number) + offset, (face[2] as number) + offset)\n }\n } else {\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3(face[2] as number, face[1] as number, face[0] as number)\n }\n for (let i = 0; i < flen; i++) {\n const face = faces[i] as number[]\n f3((face[0] as number) + vlen * steps, (face[1] as number) + vlen * steps, (face[2] as number) + vlen * steps)\n }\n }\n groups.push({ start, count: verticesArray.length / 3 - start, materialIndex: 0 })\n\n // side faces\n start = verticesArray.length / 3\n const sidewalls = (ring: readonly P[], layeroffset: number): void => {\n let i = ring.length\n while (--i >= 0) {\n const j = i\n let k = i - 1\n if (k < 0) k = ring.length - 1\n for (let s = 0, sl = steps + bevelSegments * 2; s < sl; s++) {\n const slen1 = vlen * s\n const slen2 = vlen * (s + 1)\n f4(layeroffset + j + slen1, layeroffset + k + slen1, layeroffset + k + slen2, layeroffset + j + slen2)\n }\n }\n }\n let layeroffset = 0\n sidewalls(contour, layeroffset)\n layeroffset += contour.length\n for (const ahole of holes) {\n sidewalls(ahole, layeroffset)\n layeroffset += ahole.length\n }\n groups.push({ start, count: verticesArray.length / 3 - start, materialIndex: 1 })\n\n const positions = new Float32Array(verticesArray)\n return { type: 'ExtrudeGeometry', parameters, positions, normals: computeVertexNormals(positions), uvs: new Float32Array(uvArray), groups }\n}\n","import { canonicalJson } from '../hash'\nimport type { MeshNode, PrimitiveBuffers, PrimitiveNode } from '../types'\nimport { difference } from './difference'\nimport { computeVertexNormals, extrude } from './extrude'\nimport { box, circle, cone, cylinder, indexArray, lathe, plane, ring, sphere, torus } from './three-generators'\n\nexport { box, circle, cone, cylinder, lathe, plane, ring, sphere, torus } from './three-generators'\nexport { computeVertexNormals, extrude } from './extrude'\nexport { difference } from './difference'\n\n/** How a level of detail changes a primitive. */\nexport interface DetailOptions {\n /** Multiplies the segment counts of round primitives (1 leaves them as given). */\n readonly detail?: number\n /** Floor of the scaled segment counts (default 3). */\n readonly minSegments?: number\n}\n\nconst PARAMETER_KEYS: Readonly<Record<PrimitiveNode['kind'], readonly string[]>> = {\n box: ['size', 'segments'],\n cylinder: ['radiusTop', 'radiusBottom', 'height', 'radialSegments', 'heightSegments', 'openEnded', 'thetaStart', 'thetaLength'],\n cone: ['radius', 'height', 'radialSegments', 'heightSegments', 'openEnded', 'thetaStart', 'thetaLength'],\n sphere: ['radius', 'widthSegments', 'heightSegments', 'phiStart', 'phiLength', 'thetaStart', 'thetaLength'],\n plane: ['width', 'height', 'widthSegments', 'heightSegments'],\n circle: ['radius', 'segments', 'thetaStart', 'thetaLength'],\n ring: ['innerRadius', 'outerRadius', 'thetaSegments', 'phiSegments', 'thetaStart', 'thetaLength'],\n lathe: ['points', 'segments', 'phiStart', 'phiLength'],\n torus: ['radius', 'tube', 'radialSegments', 'tubularSegments', 'arc'],\n extrude: ['shape', 'depth', 'steps', 'bevel'],\n difference: ['size', 'subtract'],\n mesh: ['positions', 'normals', 'uvs', 'indices'],\n}\n\n/** The segment fields `detail` scales, per kind. */\nconst SEGMENT_KEYS: Readonly<Partial<Record<PrimitiveNode['kind'], readonly string[]>>> = {\n cylinder: ['radialSegments'],\n cone: ['radialSegments'],\n sphere: ['widthSegments', 'heightSegments'],\n circle: ['segments'],\n ring: ['thetaSegments'],\n lathe: ['segments'],\n torus: ['radialSegments', 'tubularSegments'],\n}\n/** three's defaults of the segment fields, so a scaled default is scaled from the right number. */\nconst SEGMENT_DEFAULTS: Readonly<Record<string, number>> = { radialSegments: 32, widthSegments: 32, heightSegments: 16, segments: 12, thetaSegments: 32, tubularSegments: 48 }\nconst segmentDefault = (kind: string, key: string): number => (kind === 'circle' && key === 'segments' ? 32 : kind === 'torus' && key === 'radialSegments' ? 12 : (SEGMENT_DEFAULTS[key] as number))\n\n/** The parameters of a primitive node (no transform, colour or name), with the level of detail applied: what its geometry depends on. */\nexport function primitiveParameters(node: PrimitiveNode, options: DetailOptions = {}): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n const source = node as unknown as Record<string, unknown>\n for (const key of PARAMETER_KEYS[node.kind]) if (source[key] !== undefined) out[key] = source[key]\n const detail = options.detail ?? 1\n if (detail !== 1) {\n const floor = options.minSegments ?? 3\n for (const key of SEGMENT_KEYS[node.kind] ?? []) {\n const given = (out[key] as number | undefined) ?? segmentDefault(node.kind, key)\n out[key] = Math.max(floor, Math.round(given * detail))\n }\n }\n return out\n}\n\nfunction mesh(p: MeshNode): PrimitiveBuffers {\n const positions = new Float32Array(p.positions as number[])\n const indices = p.indices ? indexArray(p.indices as number[]) : undefined\n return {\n type: 'BufferGeometry',\n parameters: {},\n positions,\n normals: p.normals ? new Float32Array(p.normals as number[]) : computeVertexNormals(positions, indices),\n uvs: p.uvs ? new Float32Array(p.uvs as number[]) : new Float32Array((positions.length / 3) * 2),\n ...(indices ? { indices } : {}),\n groups: [],\n }\n}\n\n/** Builds a node whose parameters were already resolved (`primitiveParameters` merged over it, so the detail level is applied). */\nfunction make(p: PrimitiveNode): PrimitiveBuffers {\n switch (p.kind) {\n case 'box': {\n const size = p.size ?? [1, 1, 1]\n const segments = p.segments ?? [1, 1, 1]\n return box(size[0], size[1], size[2], segments[0], segments[1], segments[2])\n }\n case 'cylinder':\n return cylinder(p.radiusTop, p.radiusBottom, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength)\n case 'cone':\n return cone(p.radius, p.height, p.radialSegments, p.heightSegments, p.openEnded, p.thetaStart, p.thetaLength)\n case 'sphere':\n return sphere(p.radius, p.widthSegments, p.heightSegments, p.phiStart, p.phiLength, p.thetaStart, p.thetaLength)\n case 'plane':\n return plane(p.width, p.height, p.widthSegments, p.heightSegments)\n case 'circle':\n return circle(p.radius, p.segments, p.thetaStart, p.thetaLength)\n case 'ring':\n return ring(p.innerRadius, p.outerRadius, p.thetaSegments, p.phiSegments, p.thetaStart, p.thetaLength)\n case 'lathe':\n return lathe(p.points, p.segments, p.phiStart, p.phiLength)\n case 'torus':\n return torus(p.radius, p.tube, p.radialSegments, p.tubularSegments, p.arc)\n case 'extrude':\n return extrude(p.shape, p.depth, p.steps, p.bevel)\n case 'difference':\n return difference(p.size, p.subtract ?? [])\n case 'mesh':\n return mesh(p)\n default:\n throw new Error(`game-shapes: unknown primitive kind \"${String((p as { kind: unknown }).kind)}\"`)\n }\n}\n\n/** Templates by their parameter text: the same cylinder is generated once per process. Read-only by contract. */\nconst templates = new Map<string, PrimitiveBuffers>()\nlet templateLimit = 4096\nconst stats = { hits: 0, misses: 0 }\n\n/** Sets how many primitive templates are kept (least recently used out; 0 turns the cache off). */\nexport function setTemplateCacheSize(size: number): void {\n templateLimit = Math.max(0, Math.floor(size))\n while (templates.size > templateLimit) templates.delete(templates.keys().next().value as string)\n}\nexport function clearTemplateCache(): void {\n templates.clear()\n stats.hits = 0\n stats.misses = 0\n}\nexport const templateCacheStats = (): { size: number; hits: number; misses: number } => ({ size: templates.size, ...stats })\n\n/**\n * The geometry of one primitive on its own, not baked: the arrays three's generator of the same kind builds, bit for bit (meshes and differences\n * are `BufferGeometry`). The result comes from a shared template cache and must not be written to (copy it with `clonePrimitive`).\n */\nexport function buildPrimitive(node: PrimitiveNode, options: DetailOptions = {}): PrimitiveBuffers {\n const parameters = primitiveParameters(node, options)\n // raw meshes are not worth a key of their whole arrays; they are cheap to wrap\n if (node.kind === 'mesh' || templateLimit === 0) return make({ ...node, ...parameters } as PrimitiveNode)\n const key = `${node.kind}:${canonicalJson(parameters)}`\n const cached = templates.get(key)\n if (cached) {\n stats.hits++\n templates.delete(key)\n templates.set(key, cached)\n return cached\n }\n stats.misses++\n const built = make({ ...node, ...parameters } as PrimitiveNode)\n templates.set(key, built)\n if (templates.size > templateLimit) templates.delete(templates.keys().next().value as string)\n return built\n}\n\n/** A copy that owns its arrays. */\nexport function clonePrimitive(p: PrimitiveBuffers): PrimitiveBuffers {\n return {\n type: p.type,\n parameters: p.parameters,\n positions: p.positions.slice(),\n normals: p.normals.slice(),\n uvs: p.uvs.slice(),\n ...(p.indices ? { indices: p.indices.slice() } : {}),\n groups: p.groups.map((group) => ({ ...group })),\n }\n}\n","import { hash64 } from './hash'\n\n/** mulberry32: a small, fast 32-bit seeded stream in [0, 1). */\nexport function mulberry32(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let t = state\n t = Math.imul(t ^ (t >>> 15), t | 1)\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61)\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** The stream of one node: its own per (seed, generator, path), so adding a node never shifts another node's draws. */\nexport const streamFor = (seed: number | string, generator: string, path: string): (() => number) =>\n mulberry32(parseInt(hash64(`${String(seed)}\\u0000${generator}\\u0000${path}`).slice(0, 8), 16))\n","import type { ShapeGenerator } from './types'\n\nconst GENERATOR_NAME = /^[a-zA-Z][\\w.:-]*$/\n\n/** The generators of one set: what `{ kind: 'custom', generator: name, params }` nodes look up. */\nexport interface ShapeGenerators {\n /**\n * Registers a generator: a pure function of its params and a seeded stream that returns a node. A worker that generates shapes with custom nodes must\n * register the same generators (import the same module in the worker script).\n */\n register(name: string, generator: ShapeGenerator): void\n unregister(name: string): boolean\n get(name: string): ShapeGenerator | undefined\n list(): string[]\n /** The generators by name, as `GenerateOptions.generators` takes them. */\n record(): Readonly<Record<string, ShapeGenerator>>\n}\n\nexport const generatorsOver = (generators: Map<string, ShapeGenerator>): ShapeGenerators => ({\n register(name, generator) {\n if (!GENERATOR_NAME.test(name)) throw new Error(`game-shapes: generator name \"${name}\" must start with a letter and use letters, digits, \".\", \":\", \"-\" or \"_\"`)\n generators.set(name, generator)\n },\n unregister: (name) => generators.delete(name),\n get: (name) => generators.get(name),\n list: () => [...generators.keys()].sort(),\n record: () => Object.fromEntries(generators),\n})\n\nlet defaultGenerators: ShapeGenerators | undefined\n\n/** The set behind `registerGenerator`, `getGenerator` and the rest of the global functions, created on first use. */\nexport const defaultShapeGenerators = (): ShapeGenerators => (defaultGenerators ??= generatorsOver(new Map()))\n\n/** @deprecated use `createShapes(...).register`. */\nexport const registerGenerator = (name: string, generator: ShapeGenerator): void => defaultShapeGenerators().register(name, generator)\n/** @deprecated use `createShapes(...).unregister`. */\nexport const unregisterGenerator = (name: string): boolean => defaultShapeGenerators().unregister(name)\n/** @deprecated use `createShapes(...).get`. */\nexport const getGenerator = (name: string): ShapeGenerator | undefined => defaultShapeGenerators().get(name)\n/** @deprecated use `createShapes(...).list`. */\nexport const listGenerators = (): string[] => defaultShapeGenerators().list()\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://github.com/Andersonfrfilho/adatechnology-game-kit/packages/game-shapes/schema/shape.schema.json\",\n \"title\": \"game-shapes shape\",\n \"type\": \"object\",\n \"required\": [\n \"version\",\n \"root\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"version\": {\n \"const\": 1\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"materials\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/material\"\n }\n },\n \"root\": {\n \"$ref\": \"#/$defs/node\"\n },\n \"lod\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/lodLevel\"\n }\n },\n \"cullDistance\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n }\n },\n \"$defs\": {\n \"number\": {\n \"type\": \"number\"\n },\n \"count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"vec2\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 2,\n \"maxItems\": 2\n },\n \"vec3\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 3,\n \"maxItems\": 3\n },\n \"mat4\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n },\n \"minItems\": 16,\n \"maxItems\": 16\n },\n \"color\": {\n \"oneOf\": [\n {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 16777215\n },\n {\n \"type\": \"string\",\n \"pattern\": \"^#[0-9a-fA-F]{6}$\"\n }\n ]\n },\n \"uvRect\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"u0\",\n \"v0\",\n \"u1\",\n \"v1\"\n ],\n \"properties\": {\n \"u0\": {\n \"type\": \"number\"\n },\n \"v0\": {\n \"type\": \"number\"\n },\n \"u1\": {\n \"type\": \"number\"\n },\n \"v1\": {\n \"type\": \"number\"\n }\n }\n },\n \"rotationOrder\": {\n \"enum\": [\n \"XYZ\",\n \"YXZ\",\n \"ZXY\",\n \"ZYX\",\n \"YZX\",\n \"XZY\"\n ]\n },\n \"transform\": {\n \"type\": \"object\",\n \"properties\": {\n \"position\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"rotation\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"rotationOrder\": {\n \"$ref\": \"#/$defs/rotationOrder\"\n },\n \"scale\": {\n \"oneOf\": [\n {\n \"type\": \"number\"\n },\n {\n \"$ref\": \"#/$defs/vec3\"\n }\n ]\n },\n \"heading\": {\n \"type\": \"number\"\n },\n \"matrix\": {\n \"$ref\": \"#/$defs/mat4\"\n }\n }\n },\n \"instance\": {\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/transform\"\n }\n ],\n \"properties\": {\n \"position\": true,\n \"rotation\": true,\n \"rotationOrder\": true,\n \"scale\": true,\n \"heading\": true,\n \"matrix\": true,\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n }\n },\n \"unevaluatedProperties\": false\n },\n \"material\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"roughness\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"metalness\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"opacity\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"transparent\": {\n \"type\": \"boolean\"\n },\n \"emissive\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"emissiveIntensity\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"side\": {\n \"enum\": [\n \"front\",\n \"back\",\n \"double\"\n ]\n },\n \"flatShading\": {\n \"type\": \"boolean\"\n },\n \"vertexColors\": {\n \"type\": \"boolean\"\n },\n \"depthWrite\": {\n \"type\": \"boolean\"\n }\n }\n },\n \"lodLevel\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"required\": [\n \"distance\",\n \"detail\"\n ],\n \"properties\": {\n \"distance\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"detail\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0,\n \"maximum\": 1\n },\n \"minSize\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"minSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n }\n }\n },\n \"common\": {\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/transform\"\n }\n ],\n \"properties\": {\n \"kind\": {\n \"type\": \"string\"\n },\n \"name\": {\n \"type\": \"string\"\n },\n \"part\": {\n \"type\": \"string\"\n },\n \"material\": {\n \"type\": \"string\"\n },\n \"color\": {\n \"$ref\": \"#/$defs/color\"\n },\n \"uv\": {\n \"$ref\": \"#/$defs/uvRect\"\n },\n \"instances\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/instance\"\n }\n },\n \"minDetail\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0,\n \"maximum\": 1\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n }\n }\n },\n \"node\": {\n \"type\": \"object\",\n \"required\": [\n \"kind\"\n ],\n \"allOf\": [\n {\n \"$ref\": \"#/$defs/common\"\n }\n ],\n \"oneOf\": [\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"group\"\n },\n \"children\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/node\"\n }\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"box\"\n },\n \"size\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"segments\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"minItems\": 3,\n \"maxItems\": 3\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"cylinder\"\n },\n \"radiusTop\": {\n \"type\": \"number\"\n },\n \"radiusBottom\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"openEnded\": {\n \"type\": \"boolean\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"cone\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"openEnded\": {\n \"type\": \"boolean\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"sphere\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"widthSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 2\n },\n \"phiStart\": {\n \"type\": \"number\"\n },\n \"phiLength\": {\n \"type\": \"number\"\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"plane\"\n },\n \"width\": {\n \"type\": \"number\"\n },\n \"height\": {\n \"type\": \"number\"\n },\n \"widthSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"heightSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"circle\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"ring\"\n },\n \"innerRadius\": {\n \"type\": \"number\"\n },\n \"outerRadius\": {\n \"type\": \"number\"\n },\n \"thetaSegments\": {\n \"type\": \"integer\",\n \"minimum\": 3\n },\n \"phiSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"thetaStart\": {\n \"type\": \"number\"\n },\n \"thetaLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"required\": [\n \"points\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"lathe\"\n },\n \"points\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 2\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"phiStart\": {\n \"type\": \"number\"\n },\n \"phiLength\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"torus\"\n },\n \"radius\": {\n \"type\": \"number\"\n },\n \"tube\": {\n \"type\": \"number\"\n },\n \"radialSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"tubularSegments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"arc\": {\n \"type\": \"number\"\n }\n }\n },\n {\n \"required\": [\n \"shape\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"extrude\"\n },\n \"shape\": {\n \"type\": \"object\",\n \"required\": [\n \"outer\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"outer\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 3\n },\n \"holes\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"minItems\": 3\n }\n }\n }\n },\n \"depth\": {\n \"type\": \"number\"\n },\n \"steps\": {\n \"type\": \"integer\",\n \"minimum\": 1\n },\n \"bevel\": {\n \"oneOf\": [\n {\n \"const\": false\n },\n {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"thickness\": {\n \"type\": \"number\"\n },\n \"size\": {\n \"type\": \"number\"\n },\n \"offset\": {\n \"type\": \"number\"\n },\n \"segments\": {\n \"type\": \"integer\",\n \"minimum\": 1\n }\n }\n }\n ]\n }\n }\n },\n {\n \"required\": [\n \"size\",\n \"subtract\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"difference\"\n },\n \"size\": {\n \"$ref\": \"#/$defs/vec3\"\n },\n \"subtract\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"required\": [\n \"min\",\n \"max\"\n ],\n \"additionalProperties\": false,\n \"properties\": {\n \"min\": {\n \"$ref\": \"#/$defs/vec2\"\n },\n \"max\": {\n \"$ref\": \"#/$defs/vec2\"\n }\n }\n }\n }\n }\n },\n {\n \"required\": [\n \"positions\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"mesh\"\n },\n \"positions\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"normals\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"uvs\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"number\"\n }\n },\n \"indices\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/count\"\n }\n }\n }\n },\n {\n \"properties\": {\n \"kind\": {\n \"const\": \"point\"\n },\n \"data\": {}\n }\n },\n {\n \"required\": [\n \"generator\"\n ],\n \"properties\": {\n \"kind\": {\n \"const\": \"custom\"\n },\n \"generator\": {\n \"type\": \"string\"\n },\n \"params\": {}\n }\n }\n ]\n }\n }\n}\n","import schemaJson from '../schema/shape.schema.json'\nimport type { ShapeSchema } from './types'\n\n/** The JSON Schema (draft 2020-12) of a shape document; the same file ships as `@adatechnology/game-shapes/schema.json`. */\nexport const SHAPE_SCHEMA: Readonly<Record<string, unknown>> = schemaJson\n\ntype Check = (value: unknown) => string | null\n\nconst num: Check = (v) => (typeof v === 'number' && Number.isFinite(v) ? null : 'expected a finite number')\nconst bool: Check = (v) => (typeof v === 'boolean' ? null : 'expected a boolean')\nconst str: Check = (v) => (typeof v === 'string' ? null : 'expected a string')\nconst int = (min: number): Check => (v) => (typeof v === 'number' && Number.isInteger(v) && v >= min ? null : `expected an integer >= ${min}`)\nconst range = (lo: number, hi: number, loOpen = false): Check => (v) =>\n typeof v === 'number' && (loOpen ? v > lo : v >= lo) && v <= hi ? null : `expected a number in ${loOpen ? '(' : '['}${lo}, ${hi}]`\nconst tuple = (n: number, item: Check = num): Check => (v) => {\n if (!Array.isArray(v) || v.length !== n) return `expected an array of ${n}`\n for (const x of v) if (item(x)) return `expected an array of ${n} numbers`\n return null\n}\nconst list = (item: Check, min = 0): Check => (v) => {\n if (!Array.isArray(v)) return 'expected an array'\n if (v.length < min) return `expected at least ${min} items`\n for (let i = 0; i < v.length; i++) {\n const e = item(v[i])\n if (e) return `[${i}]: ${e}`\n }\n return null\n}\nconst color: Check = (v) =>\n (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 0xffffff) || (typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v)) ? null : 'expected 0xRRGGBB or \"#rrggbb\"'\nconst oneOf = (values: readonly unknown[]): Check => (v) => (values.includes(v) ? null : `expected one of ${values.map((x) => JSON.stringify(x)).join(', ')}`)\nconst object = (fields: Readonly<Record<string, Check>>, required: readonly string[] = []): Check => (v) => {\n if (!v || typeof v !== 'object' || Array.isArray(v)) return 'expected an object'\n const record = v as Record<string, unknown>\n for (const key of required) if (record[key] === undefined) return `${key}: required`\n for (const key of Object.keys(record)) {\n if (record[key] === undefined) continue\n const check = fields[key]\n if (!check) return `${key}: unknown field`\n const e = check(record[key])\n if (e) return `${key}: ${e}`\n }\n return null\n}\n\nconst ORDERS = ['XYZ', 'YXZ', 'ZXY', 'ZYX', 'YZX', 'XZY'] as const\nconst TRANSFORM: Record<string, Check> = {\n position: tuple(3),\n rotation: tuple(3),\n rotationOrder: oneOf(ORDERS),\n scale: (v) => (typeof v === 'number' ? num(v) : tuple(3)(v)),\n heading: num,\n matrix: tuple(16),\n}\nconst UV = object({ u0: num, v0: num, u1: num, v1: num }, ['u0', 'v0', 'u1', 'v1'])\nconst INSTANCE = object({ ...TRANSFORM, color })\nconst COMMON: Record<string, Check> = {\n ...TRANSFORM,\n kind: str,\n name: str,\n part: str,\n material: str,\n color,\n uv: UV,\n instances: list(INSTANCE),\n minDetail: range(0, 1, true),\n tags: list(str),\n}\nconst vec2 = tuple(2)\nconst BEVEL: Check = (v) => (v === false ? null : object({ thickness: num, size: num, offset: num, segments: int(1) })(v))\nconst KINDS: Readonly<Record<string, { fields: Record<string, Check>; required?: string[] }>> = {\n group: { fields: {} },\n box: { fields: { size: tuple(3), segments: tuple(3, int(1)) } },\n cylinder: { fields: { radiusTop: num, radiusBottom: num, height: num, radialSegments: int(1), heightSegments: int(1), openEnded: bool, thetaStart: num, thetaLength: num } },\n cone: { fields: { radius: num, height: num, radialSegments: int(1), heightSegments: int(1), openEnded: bool, thetaStart: num, thetaLength: num } },\n sphere: { fields: { radius: num, widthSegments: int(3), heightSegments: int(2), phiStart: num, phiLength: num, thetaStart: num, thetaLength: num } },\n plane: { fields: { width: num, height: num, widthSegments: int(1), heightSegments: int(1) } },\n circle: { fields: { radius: num, segments: int(3), thetaStart: num, thetaLength: num } },\n ring: { fields: { innerRadius: num, outerRadius: num, thetaSegments: int(3), phiSegments: int(1), thetaStart: num, thetaLength: num } },\n lathe: { fields: { points: list(vec2, 2), segments: int(1), phiStart: num, phiLength: num }, required: ['points'] },\n torus: { fields: { radius: num, tube: num, radialSegments: int(1), tubularSegments: int(1), arc: num } },\n extrude: {\n fields: { shape: object({ outer: list(vec2, 3), holes: list(list(vec2, 3)) }, ['outer']), depth: num, steps: int(1), bevel: BEVEL },\n required: ['shape'],\n },\n difference: { fields: { size: tuple(3), subtract: list(object({ min: vec2, max: vec2 }, ['min', 'max'])) }, required: ['size', 'subtract'] },\n mesh: {\n fields: {\n positions: (v) => list(num)(v) ?? ((v as unknown[]).length % 3 === 0 ? null : 'expected a multiple of 3 numbers'),\n normals: list(num),\n uvs: list(num),\n indices: list(int(0)),\n },\n required: ['positions'],\n },\n point: { fields: { data: () => null } },\n custom: { fields: { generator: str, params: () => null }, required: ['generator'] },\n}\n\nfunction validateNode(node: unknown, path: string, errors: string[]): void {\n if (!node || typeof node !== 'object' || Array.isArray(node)) {\n errors.push(`${path}: expected a node object`)\n return\n }\n const record = node as Record<string, unknown>\n const spec = typeof record.kind === 'string' ? KINDS[record.kind] : undefined\n if (!spec) {\n errors.push(`${path}.kind: expected one of ${Object.keys(KINDS).join(', ')}`)\n return\n }\n for (const key of spec.required ?? []) if (record[key] === undefined) errors.push(`${path}.${key}: required`)\n for (const key of Object.keys(record)) {\n if (record[key] === undefined || key === 'children') continue\n const check = spec.fields[key] ?? COMMON[key]\n if (!check) {\n errors.push(`${path}.${key}: unknown field for a ${String(record.kind)}`)\n continue\n }\n const e = check(record[key])\n if (e) errors.push(`${path}.${key}: ${e}`)\n }\n const exclusive = ['matrix', 'heading'].filter((key) => record[key] !== undefined)\n if (record.matrix !== undefined && (record.position !== undefined || record.rotation !== undefined || record.scale !== undefined || record.heading !== undefined))\n errors.push(`${path}.matrix: cannot be combined with position, rotation, scale or heading`)\n else if (exclusive.includes('heading') && (record.rotation !== undefined || record.scale !== undefined)) errors.push(`${path}.heading: cannot be combined with rotation or scale`)\n if (record.children !== undefined) {\n if (record.kind !== 'group') errors.push(`${path}.children: only a group has children`)\n else if (!Array.isArray(record.children)) errors.push(`${path}.children: expected an array`)\n else record.children.forEach((child, index) => validateNode(child, `${path}.children[${index}]`, errors))\n }\n}\n\n/** Every rule of the JSON Schema, checked without a schema engine: one message per problem, with its path (`root.children[3].radialSegments: ...`). */\nexport function validateShape(schema: unknown): string[] {\n const errors: string[] = []\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return ['expected a shape object']\n const record = schema as Record<string, unknown>\n for (const key of Object.keys(record)) if (!['version', 'name', 'materials', 'root', 'lod', 'cullDistance'].includes(key) && record[key] !== undefined) errors.push(`${key}: unknown field`)\n if (record.version !== 1) errors.push('version: expected 1')\n if (record.name !== undefined && typeof record.name !== 'string') errors.push('name: expected a string')\n if (record.materials !== undefined) {\n if (!record.materials || typeof record.materials !== 'object' || Array.isArray(record.materials)) errors.push('materials: expected an object')\n else {\n const material = object({\n color,\n roughness: range(0, 1),\n metalness: range(0, 1),\n opacity: range(0, 1),\n transparent: bool,\n emissive: color,\n emissiveIntensity: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'),\n side: oneOf(['front', 'back', 'double']),\n flatShading: bool,\n vertexColors: bool,\n depthWrite: bool,\n })\n for (const [id, hint] of Object.entries(record.materials)) {\n const e = material(hint)\n if (e) errors.push(`materials.${id}: ${e}`)\n }\n }\n }\n if (record.lod !== undefined) {\n const e = list(object({ distance: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'), detail: range(0, 1, true), minSize: (v) => (typeof v === 'number' && v >= 0 ? null : 'expected a number >= 0'), minSegments: int(3) }, ['distance', 'detail']))(record.lod)\n if (e) errors.push(`lod${e.startsWith('[') ? '' : ': '}${e}`)\n }\n if (record.cullDistance !== undefined && !(typeof record.cullDistance === 'number' && record.cullDistance > 0)) errors.push('cullDistance: expected a number > 0')\n if (record.root === undefined) errors.push('root: required')\n else validateNode(record.root, 'root', errors)\n return errors\n}\n\n/** Throws with every problem when the schema is not valid. */\nexport function assertValidShape(schema: unknown): asserts schema is ShapeSchema {\n const errors = validateShape(schema)\n if (errors.length) throw new Error(`game-shapes: invalid shape\\n ${errors.slice(0, 20).join('\\n ')}${errors.length > 20 ? `\\n ... ${errors.length - 20} more` : ''}`)\n}\n","import { colorChannels, colorHex } from './color'\nimport { hashValue } from './hash'\nimport { asMat4, identity4, isAffine, matrixOf, multiply, normalMatrix, transformPoint } from './math'\nimport type { Matrix4 } from './math'\nimport { buildPrimitive, primitiveParameters } from './primitives'\nimport { canonicalJson } from './hash'\nimport { streamFor } from './random'\nimport { getGenerator } from './registry'\nimport { assertValidShape } from './schema'\nimport type {\n Bounds,\n GenerateOptions,\n InstancedBatch,\n NamedRange,\n PrimitiveBuffers,\n PrimitiveNode,\n ShapeBatch,\n ShapeBuffers,\n ShapeLevel,\n ShapeNode,\n ShapePart,\n ShapePoint,\n ShapeSchema,\n UvRect,\n} from './types'\n\nconst PRIMITIVE_KINDS = new Set(['box', 'cylinder', 'cone', 'sphere', 'plane', 'circle', 'ring', 'lathe', 'torus', 'extrude', 'difference', 'mesh'])\nexport const isPrimitiveNode = (node: ShapeNode): node is PrimitiveNode => PRIMITIVE_KINDS.has(node.kind)\n\n/** The options that change the output, as they enter the cache key. */\nexport function keyOptions(options: GenerateOptions = {}): Record<string, unknown> {\n return {\n seed: options.seed ?? 0,\n colors: options.colors ?? 'linear',\n indexed: options.indexed ?? true,\n materials: options.materials,\n fallbackMaterial: options.fallbackMaterial,\n materialAlias: options.materialAlias,\n instancing: options.instancing,\n levels: options.levels,\n }\n}\n\n/** The cache key of a shape under some options: 64-bit FNV-1a of the canonical schema text and the options that change the output. */\nexport const shapeKey = (schema: ShapeSchema, options: GenerateOptions = {}): string => hashValue({ schema, options: keyOptions(options) })\n\nconst IDENTITY_UV: UvRect = { u0: 0, v0: 0, u1: 1, v1: 1 }\n\nclass FloatList {\n array: Float32Array\n length = 0\n constructor(capacity = 256) {\n this.array = new Float32Array(capacity)\n }\n reserve(extra: number): void {\n if (this.length + extra <= this.array.length) return\n let capacity = this.array.length * 2\n while (capacity < this.length + extra) capacity *= 2\n const next = new Float32Array(capacity)\n next.set(this.array.subarray(0, this.length))\n this.array = next\n }\n done(): Float32Array {\n return this.array.slice(0, this.length)\n }\n}\nclass IndexList {\n array: Uint32Array\n length = 0\n constructor(capacity = 256) {\n this.array = new Uint32Array(capacity)\n }\n reserve(extra: number): void {\n if (this.length + extra <= this.array.length) return\n let capacity = this.array.length * 2\n while (capacity < this.length + extra) capacity *= 2\n const next = new Uint32Array(capacity)\n next.set(this.array.subarray(0, this.length))\n this.array = next\n }\n}\n\n/** Growing buffers of one (target, material). */\nclass Accumulator {\n readonly positions = new FloatList()\n readonly normals = new FloatList()\n readonly uvs = new FloatList(170)\n readonly colors = new FloatList()\n readonly indices = new IndexList()\n readonly ranges: NamedRange[] = []\n vertices = 0\n constructor(\n readonly material: string,\n readonly part: string | null,\n ) {}\n}\n\ninterface Target {\n readonly part: string | null\n readonly accs: Map<string, Accumulator>\n}\n\ninterface Settings {\n readonly colors: 'linear' | 'srgb' | 'none'\n readonly indexed: boolean\n readonly materials?: ReadonlySet<string>\n readonly fallback?: string\n readonly alias?: Readonly<Record<string, string>>\n readonly seed: number | string\n readonly generators?: GenerateOptions['generators']\n readonly isolatedGenerators?: boolean\n readonly autoMin?: number\n}\n\ninterface LevelSpec {\n readonly distance: number\n readonly detail: number\n readonly minSize?: number\n readonly minSegments?: number\n readonly index: number\n}\n\ninterface Inherited {\n readonly material: string\n readonly color: number\n readonly uv: UvRect\n readonly target: Target\n}\n\n/**\n * Bakes a template into an accumulator: positions by the world matrix, normals by its normal matrix and normalised, uvs into the atlas cell,\n * one colour for all, indices offset. The arithmetic is three's (`createMeshApi`, `BufferGeometry.applyMatrix4`), so the bits match.\n */\nfunction bake(acc: Accumulator, t: PrimitiveBuffers, world: readonly number[], rgb: readonly number[] | null, u: UvRect, indexed: boolean): void {\n const e = world\n const nm = normalMatrix(world)\n const affine = isAffine(world)\n const source = t.positions\n const count = source.length / 3\n const order: ArrayLike<number> | null = indexed ? null : t.indices ?? null\n const emitted = order ? order.length : count\n acc.positions.reserve(emitted * 3)\n acc.normals.reserve(emitted * 3)\n acc.uvs.reserve(emitted * 2)\n if (rgb) acc.colors.reserve(emitted * 3)\n const P = acc.positions.array\n const N = acc.normals.array\n const U = acc.uvs.array\n const C = acc.colors.array\n let pi = acc.positions.length\n let ni = acc.normals.length\n let ui = acc.uvs.length\n let ci = acc.colors.length\n const du = u.u1 - u.u0\n const dv = u.v1 - u.v0\n const tn = t.normals\n const tu = t.uvs\n for (let k = 0; k < emitted; k++) {\n const i = order ? (order[k] as number) : k\n const x = source[i * 3] as number\n const y = source[i * 3 + 1] as number\n const z = source[i * 3 + 2] as number\n if (affine) {\n P[pi++] = e[0]! * x + e[4]! * y + e[8]! * z + e[12]!\n P[pi++] = e[1]! * x + e[5]! * y + e[9]! * z + e[13]!\n P[pi++] = e[2]! * x + e[6]! * y + e[10]! * z + e[14]!\n } else {\n const p = transformPoint(e, x, y, z)\n P[pi++] = p[0]\n P[pi++] = p[1]\n P[pi++] = p[2]\n }\n const nx = tn[i * 3] as number\n const ny = tn[i * 3 + 1] as number\n const nz = tn[i * 3 + 2] as number\n const vx = nm[0]! * nx + nm[3]! * ny + nm[6]! * nz\n const vy = nm[1]! * nx + nm[4]! * ny + nm[7]! * nz\n const vz = nm[2]! * nx + nm[5]! * ny + nm[8]! * nz\n const s = 1 / (Math.sqrt(vx * vx + vy * vy + vz * vz) || 1)\n N[ni++] = vx * s\n N[ni++] = vy * s\n N[ni++] = vz * s\n U[ui++] = u.u0 + (tu[i * 2] as number) * du\n U[ui++] = u.v0 + (tu[i * 2 + 1] as number) * dv\n if (rgb) {\n C[ci++] = rgb[0]!\n C[ci++] = rgb[1]!\n C[ci++] = rgb[2]!\n }\n }\n acc.positions.length = pi\n acc.normals.length = ni\n acc.uvs.length = ui\n acc.colors.length = ci\n if (indexed) {\n const base = acc.vertices\n const idx = t.indices\n const n = idx ? idx.length : count\n acc.indices.reserve(n)\n const I = acc.indices.array\n let ii = acc.indices.length\n for (let k = 0; k < n; k++) I[ii++] = base + (idx ? (idx[k] as number) : k)\n acc.indices.length = ii\n }\n acc.vertices += emitted\n}\n\nfunction boundsOf(positions: Float32Array): Bounds {\n const min: [number, number, number] = [Infinity, Infinity, Infinity]\n const max: [number, number, number] = [-Infinity, -Infinity, -Infinity]\n for (let i = 0; i < positions.length; i += 3) {\n for (let axis = 0; axis < 3; axis++) {\n const v = positions[i + axis] as number\n if (v < min[axis]!) min[axis] = v\n if (v > max[axis]!) max[axis] = v\n }\n }\n return { min, max }\n}\n\nfunction finish(acc: Accumulator, indexed: boolean, withColors: boolean): ShapeBatch {\n const positions = acc.positions.done()\n const indices = indexed ? (acc.vertices > 65535 ? acc.indices.array.slice(0, acc.indices.length) : Uint16Array.from(acc.indices.array.subarray(0, acc.indices.length))) : undefined\n return {\n material: acc.material,\n part: acc.part,\n positions,\n normals: acc.normals.done(),\n uvs: acc.uvs.done(),\n ...(withColors ? { colors: acc.colors.done() } : {}),\n ...(indices ? { indices } : {}),\n ranges: acc.ranges,\n bounds: boundsOf(positions),\n }\n}\n\nconst radiusOf = (t: PrimitiveBuffers, world: readonly number[]): number => {\n let r = 0\n const p = t.positions\n for (let i = 0; i < p.length; i += 3) r = Math.max(r, Math.hypot(p[i] as number, p[i + 1] as number, p[i + 2] as number))\n const sx = Math.hypot(world[0]!, world[1]!, world[2]!)\n const sy = Math.hypot(world[4]!, world[5]!, world[6]!)\n const sz = Math.hypot(world[8]!, world[9]!, world[10]!)\n return r * Math.max(sx, sy, sz)\n}\n\ninterface LevelResult {\n readonly level: ShapeLevel\n readonly parts: ShapePart[]\n readonly points: ShapePoint[]\n readonly primitives: number\n}\n\n/** Expands a custom node into the node its generator returns (wrapped so that the custom node's own fields still apply). */\nfunction expandCustom(node: Extract<ShapeNode, { kind: 'custom' }>, settings: Settings, detail: number, path: string): ShapeNode {\n const generator = settings.generators?.[node.generator] ?? (settings.isolatedGenerators ? undefined : getGenerator(node.generator))\n if (!generator) throw new Error(`game-shapes: no generator \"${node.generator}\" (register it with registerGenerator, in the worker too) at ${path}`)\n const generated = generator(node.params, { random: streamFor(settings.seed, node.generator, path), seed: settings.seed, detail, path })\n const { kind: _kind, generator: _generator, params: _params, ...common } = node\n return { ...common, kind: 'group', children: [generated] }\n}\n\n/** The key two leaf primitives share when one can stand for the other as an instance. */\nconst leafKey = (node: PrimitiveNode, material: string, color: number, uv: UvRect, level: LevelSpec): string =>\n `${node.kind}|${canonicalJson(primitiveParameters(node, level))}|${material}|${color}|${uv.u0},${uv.v0},${uv.u1},${uv.v1}`\n\nfunction runLevel(schema: ShapeSchema, settings: Settings, level: LevelSpec): LevelResult {\n const bakeParts = level.index > 0\n const root: Target = { part: null, accs: new Map() }\n const targets: Target[] = [root]\n const partTargets = new Map<string, Target>()\n const parts: ShapePart[] = []\n const points: ShapePoint[] = []\n const instanced: InstancedBatch[] = []\n let primitives = 0\n const space = settings.colors === 'none' ? null : settings.colors\n const channels = new Map<number, readonly number[]>()\n const rgbOf = (hex: number): readonly number[] | null => {\n if (!space) return null\n let c = channels.get(hex)\n if (!c) {\n c = colorChannels(hex, space)\n channels.set(hex, c)\n }\n return c\n }\n const resolveMaterial = (id: string): string => {\n let out = id\n if (settings.materials && !settings.materials.has(out)) out = settings.fallback ?? out\n return settings.alias?.[out] ?? out\n }\n const accOf = (target: Target, material: string): Accumulator => {\n let acc = target.accs.get(material)\n if (!acc) {\n acc = new Accumulator(material, target.part)\n target.accs.set(material, acc)\n }\n return acc\n }\n\n // automatic instancing: count the leaves first\n const autoCounts = new Map<string, number>()\n const autoGroups = new Map<string, { node: PrimitiveNode; material: string; color: number; part: string | null; matrices: number[] }>()\n\n const count = (node: ShapeNode, inherited: { material: string; color: number; uv: UvRect; inPart: boolean }, path: string): void => {\n if (node.minDetail !== undefined && level.detail < node.minDetail) return\n if (node.kind === 'custom') return count(expandCustom(node, settings, level.detail, path), inherited, path)\n const next = {\n material: node.material !== undefined ? resolveMaterial(node.material) : inherited.material,\n color: node.color !== undefined ? colorHex(node.color) : inherited.color,\n uv: node.uv ?? inherited.uv,\n inPart: inherited.inPart || (node.part !== undefined && !bakeParts),\n }\n if (node.instances) return\n if (node.kind === 'group') {\n node.children?.forEach((child, index) => count(child, next, `${path}/${index}`))\n return\n }\n if (isPrimitiveNode(node) && node.name === undefined && !next.inPart) {\n const key = leafKey(node, next.material, next.color, next.uv, level)\n autoCounts.set(key, (autoCounts.get(key) ?? 0) + 1)\n }\n }\n const rootMaterial = resolveMaterial('default')\n if (settings.autoMin !== undefined) count(schema.root, { material: rootMaterial, color: 0xffffff, uv: IDENTITY_UV, inPart: false }, 'root')\n\n /** Draws a subtree into `collector` (a target) under `parent` (null: identity). */\n const visit = (node: ShapeNode, parent: Matrix4 | null, inherited: Inherited, path: string): void => {\n if (node.minDetail !== undefined && level.detail < node.minDetail) return\n if (node.kind === 'custom') return visit(expandCustom(node, settings, level.detail, path), parent, inherited, path)\n let target = inherited.target\n let parentWorld = parent\n if (node.part !== undefined) {\n if (bakeParts) {\n // far levels freeze the parts at rest: the part's pivot is relative to the root\n parentWorld = null\n } else {\n let partTarget = partTargets.get(node.part)\n if (!partTarget) {\n partTarget = { part: node.part, accs: new Map() }\n partTargets.set(node.part, partTarget)\n targets.push(partTarget)\n const { position, rotation, rotationOrder, scale, heading, matrix } = node\n parts.push({\n id: node.part,\n ...(position ? { position } : {}),\n ...(rotation ? { rotation } : {}),\n ...(rotationOrder ? { rotationOrder } : {}),\n ...(scale !== undefined ? { scale } : {}),\n ...(heading !== undefined ? { heading } : {}),\n ...(matrix ? { matrix } : { matrix: asMat4(matrixOf(node)) }),\n })\n }\n target = partTarget\n }\n }\n const isPart = node.part !== undefined && !bakeParts\n const local = isPart ? null : matrixOf(node)\n const world = isPart ? null : local ? (parentWorld ? multiply(parentWorld, local) : local) : parentWorld\n const next: Inherited = {\n material: node.material !== undefined ? resolveMaterial(node.material) : inherited.material,\n color: node.color !== undefined ? colorHex(node.color) : inherited.color,\n uv: node.uv ?? inherited.uv,\n target,\n }\n\n if (node.instances) {\n drawInstanced(node, parentWorld, next, path)\n return\n }\n\n const snapshot = node.name !== undefined ? new Map([...target.accs].map(([m, a]) => [m, { v: a.vertices, i: a.indices.length }])) : null\n\n if (node.kind === 'group') {\n node.children?.forEach((child, index) => visit(child, world, next, `${path}/${index}`))\n } else if (node.kind === 'point') {\n const p = node.position ?? [0, 0, 0]\n points.push({\n ...(node.name !== undefined ? { name: node.name } : {}),\n part: target.part,\n position: parent ? transformPoint(parent, p[0], p[1], p[2]) : [p[0], p[1], p[2]],\n ...(node.data !== undefined ? { data: node.data } : {}),\n ...(node.tags ? { tags: node.tags } : {}),\n })\n } else if (isPrimitiveNode(node)) {\n const template = buildPrimitive(node, level)\n const m = world ?? identity4()\n if (level.minSize !== undefined && radiusOf(template, m) < level.minSize) return\n primitives++\n if (settings.autoMin !== undefined && node.name === undefined && target.part === null) {\n const key = leafKey(node, next.material, next.color, next.uv, level)\n if ((autoCounts.get(key) ?? 0) >= settings.autoMin) {\n let group = autoGroups.get(key)\n if (!group) {\n group = { node, material: next.material, color: next.color, part: null, matrices: [] }\n autoGroups.set(key, group)\n }\n group.matrices.push(...m)\n return\n }\n }\n bake(accOf(target, next.material), template, m, rgbOf(next.color), next.uv, settings.indexed)\n }\n\n if (snapshot) {\n for (const [material, acc] of target.accs) {\n const before = snapshot.get(material) ?? { v: 0, i: 0 }\n if (acc.vertices === before.v) continue\n acc.ranges.push({\n name: node.name as string,\n ...(node.tags ? { tags: node.tags } : {}),\n vertexStart: before.v,\n vertexCount: acc.vertices - before.v,\n indexStart: before.i,\n indexCount: acc.indices.length - before.i,\n })\n }\n }\n }\n\n const drawInstanced = (node: ShapeNode, parentWorld: Matrix4 | null, inherited: Inherited, path: string): void => {\n const collector: Target = { part: inherited.target.part, accs: new Map() }\n const { instances, ...single } = node as ShapeNode & { instances: NonNullable<ShapeNode['instances']> }\n const before = parts.length\n visit(single as ShapeNode, null, { ...inherited, target: collector }, path)\n if (parts.length !== before) throw new Error(`game-shapes: an instanced node cannot hold parts (${path})`)\n const matrices = new Float32Array(instances.length * 16)\n const hasColors = instances.some((instance) => instance.color !== undefined)\n const colors = hasColors ? new Float32Array(instances.length * 3) : undefined\n instances.forEach((instance, index) => {\n const local = matrixOf(instance)\n const m = local ? (parentWorld ? multiply(parentWorld, local) : local) : parentWorld ?? identity4()\n matrices.set(m, index * 16)\n if (colors) colors.set(colorChannels(colorHex(instance.color), space ?? 'srgb'), index * 3)\n })\n for (const acc of collector.accs.values()) {\n const batch = finish(acc, settings.indexed, false)\n instanced.push({\n material: acc.material,\n part: collector.part,\n ...(node.name !== undefined ? { name: node.name } : {}),\n geometry: { type: 'BufferGeometry', parameters: {}, positions: batch.positions, normals: batch.normals, uvs: batch.uvs, ...(batch.indices ? { indices: batch.indices } : {}), groups: [] },\n matrices: matrices.slice(),\n ...(colors ? { colors: colors.slice() } : {}),\n count: instances.length,\n })\n }\n }\n\n visit(schema.root, null, { material: rootMaterial, color: 0xffffff, uv: IDENTITY_UV, target: root }, 'root')\n\n for (const group of autoGroups.values()) {\n const template = buildPrimitive(group.node, level)\n const n = group.matrices.length / 16\n const rgb = colorChannels(group.color, space ?? 'srgb')\n const colors = new Float32Array(n * 3)\n for (let i = 0; i < n; i++) colors.set(rgb, i * 3)\n instanced.push({\n material: group.material,\n part: null,\n geometry: { type: template.type, parameters: template.parameters, positions: template.positions.slice(), normals: template.normals.slice(), uvs: template.uvs.slice(), ...(template.indices ? { indices: template.indices.slice() } : {}), groups: template.groups.map((g) => ({ ...g })) },\n matrices: new Float32Array(group.matrices),\n ...(space ? { colors } : {}),\n count: n,\n })\n }\n\n const batches: ShapeBatch[] = []\n for (const target of targets) for (const acc of target.accs.values()) if (acc.vertices > 0 && (!settings.indexed || acc.indices.length > 0)) batches.push(finish(acc, settings.indexed, space !== null))\n return { level: { distance: level.distance, detail: level.detail, batches, instanced }, parts, points, primitives }\n}\n\n/**\n * Turns a shape into buffers: one batch per (part, material) per level, baked; instanced nodes as instance batches; parts with their pivots;\n * points. Pure: the same schema and options give the same bytes, here or in a worker.\n */\nexport function generate(schema: ShapeSchema, options: GenerateOptions = {}): ShapeBuffers {\n if (options.validate !== false) assertValidShape(schema)\n const settings: Settings = {\n colors: options.colors ?? 'linear',\n indexed: options.indexed ?? true,\n ...(options.materials ? { materials: new Set(options.materials) } : {}),\n ...(options.fallbackMaterial !== undefined ? { fallback: options.fallbackMaterial } : {}),\n ...(options.materialAlias ? { alias: options.materialAlias } : {}),\n seed: options.seed ?? 0,\n ...(options.generators ? { generators: options.generators } : {}),\n ...(options.isolatedGenerators ? { isolatedGenerators: true } : {}),\n ...(options.instancing ? { autoMin: Math.max(2, options.instancing.minCount) } : {}),\n }\n const specs: LevelSpec[] = [{ distance: 0, detail: 1, index: 0 }, ...(schema.lod ?? []).map((rule, index) => ({ ...rule, index: index + 1 }))]\n const wanted = options.levels ? specs.filter((spec) => options.levels!.includes(spec.index)) : specs\n let parts: ShapePart[] = []\n let points: ShapePoint[] = []\n let primitives = 0\n const levels: ShapeLevel[] = []\n for (const spec of wanted) {\n const result = runLevel(schema, settings, spec)\n if (spec.index === 0 || levels.length === 0) {\n parts = result.parts\n points = result.points\n primitives = result.primitives\n }\n levels.push(result.level)\n }\n const first = levels[0]\n const vertices = first ? first.batches.reduce((sum, batch) => sum + batch.positions.length / 3, 0) : 0\n const triangles = first\n ? first.batches.reduce((sum, batch) => sum + (batch.indices ? batch.indices.length : batch.positions.length / 3) / 3, 0) +\n first.instanced.reduce((sum, batch) => sum + ((batch.geometry.indices ? batch.geometry.indices.length : batch.geometry.positions.length / 3) / 3) * batch.count, 0)\n : 0\n return {\n key: options.key === false ? '' : options.key ?? shapeKey(schema, options),\n ...(schema.name !== undefined ? { name: schema.name } : {}),\n levels,\n parts,\n points,\n ...(schema.materials ? { materials: schema.materials } : {}),\n ...(schema.cullDistance !== undefined ? { cullDistance: schema.cullDistance } : {}),\n stats: { vertices, triangles, batches: first ? first.batches.length : 0, instances: first ? first.instanced.reduce((sum, batch) => sum + batch.count, 0) : 0, primitives },\n }\n}\n","import { normalMatrix, transformPoint } from './math'\nimport type { InstancedBatch, PrimitiveBuffers, ShapeBatch, ShapeBuffers } from './types'\n\n/** One piece for `mergeTransformed`: arrays (any may be missing) and the matrix that takes them into the merged space. */\nexport interface TransformedPiece {\n readonly positions: ArrayLike<number>\n readonly normals?: ArrayLike<number>\n readonly uvs?: ArrayLike<number>\n readonly indices?: ArrayLike<number> | null\n /** Column-major 4 x 4. */\n readonly matrix: readonly number[]\n}\n\nexport interface MergedArrays {\n readonly positions: Float32Array\n readonly normals: Float32Array\n readonly uvs: Float32Array\n}\n\n/**\n * Joins pieces into one non-indexed set of arrays, each piece de-indexed, its missing normals and uvs zero-filled, its positions by\n * `Vector3.applyMatrix4` and its normals by the normal matrix and normalised: what three's `toNonIndexed` + `applyMatrix4` + a join do,\n * bit for bit (the port of `mergeByMaterial`).\n */\nexport function mergeTransformed(pieces: readonly TransformedPiece[]): MergedArrays {\n let total = 0\n for (const piece of pieces) total += piece.indices ? piece.indices.length : piece.positions.length / 3\n const positions = new Float32Array(total * 3)\n const normals = new Float32Array(total * 3)\n const uvs = new Float32Array(total * 2)\n let at = 0\n for (const piece of pieces) {\n const e = piece.matrix\n const nm = normalMatrix(e)\n const count = piece.indices ? piece.indices.length : piece.positions.length / 3\n // de-index into Float32 first, as toNonIndexed does, then transform the stored values\n const p = new Float32Array(count * 3)\n const n = new Float32Array(count * 3)\n for (let k = 0; k < count; k++) {\n const i = piece.indices ? (piece.indices[k] as number) : k\n for (let c = 0; c < 3; c++) {\n p[k * 3 + c] = piece.positions[i * 3 + c] as number\n if (piece.normals) n[k * 3 + c] = piece.normals[i * 3 + c] as number\n }\n if (piece.uvs) {\n uvs[(at + k) * 2] = piece.uvs[i * 2] as number\n uvs[(at + k) * 2 + 1] = piece.uvs[i * 2 + 1] as number\n }\n }\n for (let k = 0; k < count; k++) {\n const q = transformPoint(e, p[k * 3] as number, p[k * 3 + 1] as number, p[k * 3 + 2] as number)\n positions[(at + k) * 3] = q[0]\n positions[(at + k) * 3 + 1] = q[1]\n positions[(at + k) * 3 + 2] = q[2]\n const x = n[k * 3] as number\n const y = n[k * 3 + 1] as number\n const z = n[k * 3 + 2] as number\n const vx = nm[0]! * x + nm[3]! * y + nm[6]! * z\n const vy = nm[1]! * x + nm[4]! * y + nm[7]! * z\n const vz = nm[2]! * x + nm[5]! * y + nm[8]! * z\n const s = 1 / (Math.sqrt(vx * vx + vy * vy + vz * vz) || 1)\n normals[(at + k) * 3] = vx * s\n normals[(at + k) * 3 + 1] = vy * s\n normals[(at + k) * 3 + 2] = vz * s\n }\n at += count\n }\n return { positions, normals, uvs }\n}\n\nconst primitiveArrays = (p: PrimitiveBuffers): ArrayBuffer[] => [p.positions, p.normals, p.uvs, ...(p.indices ? [p.indices] : [])].map((a) => a.buffer as ArrayBuffer)\nconst batchArrays = (b: ShapeBatch): ArrayBuffer[] => [b.positions, b.normals, b.uvs, ...(b.colors ? [b.colors] : []), ...(b.indices ? [b.indices] : [])].map((a) => a.buffer as ArrayBuffer)\nconst instancedArrays = (b: InstancedBatch): ArrayBuffer[] => [...primitiveArrays(b.geometry), b.matrices.buffer as ArrayBuffer, ...(b.colors ? [b.colors.buffer as ArrayBuffer] : [])]\n\n/** Every `ArrayBuffer` of a result, for `postMessage(buffers, transferablesOf(buffers))`. */\nexport function transferablesOf(buffers: ShapeBuffers): ArrayBuffer[] {\n const out = new Set<ArrayBuffer>()\n for (const level of buffers.levels) {\n for (const batch of level.batches) for (const a of batchArrays(batch)) out.add(a)\n for (const batch of level.instanced) for (const a of instancedArrays(batch)) out.add(a)\n }\n return [...out]\n}\n\nconst copyPrimitive = (p: PrimitiveBuffers): PrimitiveBuffers => ({\n ...p,\n positions: p.positions.slice(),\n normals: p.normals.slice(),\n uvs: p.uvs.slice(),\n ...(p.indices ? { indices: p.indices.slice() } : {}),\n groups: p.groups.map((g) => ({ ...g })),\n})\n\n/** A deep copy whose arrays are its own (cached results are shared and read-only; copy before deforming). */\nexport function cloneBuffers(buffers: ShapeBuffers): ShapeBuffers {\n return {\n ...buffers,\n levels: buffers.levels.map((level) => ({\n ...level,\n batches: level.batches.map((b) => ({\n ...b,\n positions: b.positions.slice(),\n normals: b.normals.slice(),\n uvs: b.uvs.slice(),\n ...(b.colors ? { colors: b.colors.slice() } : {}),\n ...(b.indices ? { indices: b.indices.slice() } : {}),\n ranges: b.ranges.map((r) => ({ ...r })),\n bounds: { min: [...b.bounds.min], max: [...b.bounds.max] },\n })),\n instanced: level.instanced.map((b) => ({ ...b, geometry: copyPrimitive(b.geometry), matrices: b.matrices.slice(), ...(b.colors ? { colors: b.colors.slice() } : {}) })),\n })),\n }\n}\n\n/** Bytes held by the arrays of a result (what the cache counts). */\nexport function byteSizeOf(buffers: ShapeBuffers): number {\n return transferablesOf(buffers).reduce((sum, buffer) => sum + buffer.byteLength, 0)\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\nconst clampShare = (share: number): number => Math.min(1, Math.max(0, share))\n\n/**\n * The shove a blast gives to a body of `mass` kg whose centre is at `position`: away from the centre, lifted a little, with the speed\n * `sqrt(reach) * min(maxSpeed, sqrt(2 * energy * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n // cover takes its share off the push itself, past the cap too: a light thing behind a cupboard is not thrown as fast as one in the open\n const reach = clampShare(blast.reach ?? 1)\n const speed = Math.sqrt(reach) * Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at: inside it the charge is in contact and the body is torn apart anyway. */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, NEAREST) / w3\n const scaled = (0.067 * Math.sqrt(1 + (z / 0.23) ** 4)) / (z * z * Math.cbrt(1 + (z / 1.55) ** 3))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n\n/** Where `launchBody` leaves the throw on the body's root until the module that animates it takes it. */\nconst LAUNCHED = 'launched'\n\n/**\n * Throws a body at `velocity` (m/s, world): an occupant leaving a car through the glass, a pedestrian run over. The module that animates the body\n * takes it on its next frame (`takeLaunch`) and moves it as it moves a body a blast knocked down: flying, landing, sliding, lying, getting up.\n */\nexport function launchBody(root: { userData: Record<string, unknown> }, velocity: Vec3): void {\n root.userData[LAUNCHED] = [velocity[0], velocity[1], velocity[2]]\n}\n\n/** The throw `launchBody` left on the root, as a knock (knocked down, in the air), once; undefined when nothing threw it. */\nexport function takeLaunch(root: { userData: Record<string, unknown> }): Knock | undefined {\n const velocity = root.userData[LAUNCHED] as Vec3 | undefined\n if (!velocity) return undefined\n delete root.userData[LAUNCHED]\n return { velocity: [velocity[0], velocity[1], velocity[2]], airborne: true, lying: 0, lieLeft: 0, down: true }\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * Where a hand should be, in world space. `position` is the middle of the palm; the orientation follows one convention for every hand: the hand-local +x runs from the wrist to the\n * knuckles (the way the fingers point when open), +y is the back of the hand and +z completes the frame (for a right hand the little finger side; the thumb is at -z). A left hand is the\n * mirror image of a right one, so the same numbers describe the same grip: its thumb is at +z.\n */\nexport interface HandPose {\n position: Vec3\n /** Unit quaternion `[x, y, z, w]`, hand-local to world. */\n quaternion: [number, number, number, number]\n}\n\n/**\n * What a tool in the hands asks of the hands that hold it (a weapon asks for a grip on its grip and handguard, a carried item for a hand under it). A side left out or null is not held:\n * the hand stays in its rest stance. Nothing here knows what the tool is.\n */\nexport interface HandTargets {\n R?: HandPose | null\n L?: HandPose | null\n /** How closed the fingers are, 0 open to 1 closed on a grip. Default 1. */\n grip?: number\n /** The same for the left hand, when it differs from `grip` (a hand laid on a forend is looser than the one on the trigger). */\n gripL?: number\n /** The size of the hands against life size (a tool drawn smaller than real takes smaller hands). Default 1. */\n scale?: number\n /** Fingers of the right hand that curl by themselves, 0 extended to 1 fully curled (the index finger of a trigger hand); the others follow `grip`. */\n fingers?: { index?: number }\n /**\n * Where the elbows go: `view` puts them on screen beside the hand, out to the side, as a tool held out in front (default); `body` lets them hang down and back by the body, as an item\n * carried close (a can, a bottle), where an elbow out to the side would lift it above the shoulder.\n */\n elbows?: 'view' | 'body'\n}\n\n/** Read every frame by whoever draws the arms; answers null while nothing is held. */\nexport type HandTargetSource = () => HandTargets | null\n\n/** The muzzle of the tool in the hands as it is drawn now (world space): where a shot's flash and tracer leave, and which way the barrel points. */\nexport interface MuzzlePose {\n readonly position: Vec3\n /** Unit vector along the barrel, out of the muzzle. */\n readonly direction: Vec3\n /** The module draws the muzzle flash itself: the host draws none of its own. */\n readonly drawsFlash: boolean\n}\n\n/** Read by the host at each shot; null while the tool in the hands has no muzzle (a knife, a bare hand). */\nexport type MuzzleSource = () => MuzzlePose | null\n\n/**\n * The layer of what the first-person view draws over the world (three.js `Object3D.layers`): the tool in the hands and the arms that hold it. A host with a first-person view draws\n * the world without this layer, then this layer alone over it with the depth cleared and its own field of view (`ModuleHost.setViewmodelFov`), as shooters draw the weapon in the hands:\n * it never goes into a wall, and the gun and the arms are framed by the lens chosen for them. Seen from outside (third person) nothing is on it.\n */\nexport const FIRST_PERSON_LAYER = 9\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present' },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n cobble: 'concrete',\n paver: 'concrete',\n plaster: 'concrete',\n asphalt: 'asphalt',\n wood_soft: 'wood',\n wood_hard: 'wood',\n green_wood: 'wood',\n plywood: 'wood',\n mdf: 'wood',\n ceramic: 'tile',\n plastic: 'tile',\n soil: 'dirt',\n mud: 'dirt',\n clay: 'dirt',\n wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n // no snow surface yet: packed snow crunches closest to sand underfoot\n snow: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n Dent,\n DestructibleSpec,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartShape,\n PartSpec,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, launchBody, stepKnock, takeLaunch } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets, MuzzlePose, MuzzleSource } from './hands'\nexport { FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, checkDeferredQueue } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, ModuleArea, ModuleHost, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\n","import { applyPatches, mergeById, removeIds } from '@adatechnology/game-contracts'\n\nimport { generate } from './generate'\nimport { generatorsOver } from './registry'\nimport type { ShapeGenerators } from './registry'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\n\nexport interface ShapesOptions {\n /** Generators by name, added to the set; later packs replace earlier ones with the same name. */\n readonly packs?: readonly Readonly<Record<string, ShapeGenerator>>[]\n /** A generator replaced by name (a function is replaced as a whole). */\n readonly patch?: Readonly<Record<string, ShapeGenerator>>\n /** Names taken out. */\n readonly remove?: readonly string[]\n}\n\nexport interface Shapes extends ShapeGenerators {\n /** `generate` that looks custom nodes up in this set only (a name only the global registry has throws). */\n generate(schema: ShapeSchema, options?: Omit<GenerateOptions, 'isolatedGenerators'>): ShapeBuffers\n}\n\ntype Entry = { readonly id: string; readonly generator: ShapeGenerator }\n\n/** A set of shape generators of its own. Nothing is shared with any other set or with the global registry. */\nexport function createShapes(options: ShapesOptions = {}): Shapes {\n const entryOf = ([id, generator]: [string, ShapeGenerator]): Entry => ({ id, generator })\n const entries = mergeById<Entry>([], (options.packs ?? []).flatMap((pack) => Object.entries(pack).map(entryOf)))\n const patches: Record<string, Partial<Entry>> = {}\n for (const [id, generator] of Object.entries(options.patch ?? {})) patches[id] = { generator }\n applyPatches(entries, patches)\n removeIds(entries, options.remove)\n const generators = generatorsOver(new Map([...entries].map(([id, entry]) => [id, entry.generator])))\n return { ...generators, generate: (schema, generateOptions = {}) => generate(schema, { ...generateOptions, generators: { ...generators.record(), ...generateOptions.generators }, isolatedGenerators: true }) }\n}\n","import { byteSizeOf } from './merge'\nimport type { ShapeBuffers } from './types'\n\nexport interface ShapeCacheOptions {\n /** Most results kept (default 256). */\n readonly maxEntries?: number\n /** Most bytes of arrays kept (default 64 MiB). A result larger than this alone is not kept. */\n readonly maxBytes?: number\n}\n\nexport interface ShapeCacheStats {\n readonly entries: number\n readonly bytes: number\n readonly hits: number\n readonly misses: number\n readonly evictions: number\n}\n\n/** An LRU of results by `shapeKey`. What it returns is shared: read-only (copy with `cloneBuffers` before deforming). */\nexport interface ShapeCache {\n get(key: string): ShapeBuffers | undefined\n set(key: string, buffers: ShapeBuffers): void\n has(key: string): boolean\n delete(key: string): boolean\n clear(): void\n stats(): ShapeCacheStats\n}\n\n/** An LRU of `ShapeBuffers` by key, bounded by entries and by bytes of the arrays. Pure memoisation: a hit gives the bytes a miss would. */\nexport function createShapeCache(options: ShapeCacheOptions = {}): ShapeCache {\n const maxEntries = options.maxEntries ?? 256\n const maxBytes = options.maxBytes ?? 64 * 1024 * 1024\n const entries = new Map<string, { buffers: ShapeBuffers; bytes: number }>()\n let bytes = 0\n let hits = 0\n let misses = 0\n let evictions = 0\n const drop = (key: string): boolean => {\n const entry = entries.get(key)\n if (!entry) return false\n entries.delete(key)\n bytes -= entry.bytes\n return true\n }\n return {\n get(key) {\n const entry = entries.get(key)\n if (!entry) {\n misses++\n return undefined\n }\n hits++\n // most recently used goes last\n entries.delete(key)\n entries.set(key, entry)\n return entry.buffers\n },\n set(key, buffers) {\n drop(key)\n const size = byteSizeOf(buffers)\n if (size > maxBytes || maxEntries <= 0) return\n entries.set(key, { buffers, bytes: size })\n bytes += size\n for (const oldest of entries.keys()) {\n if (entries.size <= maxEntries && bytes <= maxBytes) break\n drop(oldest)\n evictions++\n }\n },\n has: (key) => entries.has(key),\n delete: drop,\n clear() {\n entries.clear()\n bytes = 0\n },\n stats: () => ({ entries: entries.size, bytes, hits, misses, evictions }),\n }\n}\n","import type { ShapeCache } from './cache'\nimport { generate, shapeKey } from './generate'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\nimport type { ShapeJob, ShapeReply } from './worker'\n\n/** Anything with `postMessage` / `onmessage` / `terminate`: a browser `Worker`, a `worker_threads` wrapper, an in-thread fake. */\nexport interface WorkerLike {\n onmessage: ((event: { data: unknown }) => void) | null\n onerror?: ((event: unknown) => void) | null\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void\n terminate(): unknown\n}\n\nexport interface ShapePoolOptions {\n /** Workers (default 0: generate in the calling thread). */\n readonly size?: number\n /** Makes one worker that runs `installShapeWorker`. Without it the pool generates in the calling thread. */\n readonly spawn?: () => WorkerLike\n /** Results by `shapeKey`: a hit resolves at once and never reaches a worker. */\n readonly cache?: ShapeCache\n /** Generators of the `custom` nodes for the jobs made in the calling thread (the workers register their own). */\n readonly generators?: Readonly<Record<string, ShapeGenerator>>\n /** Look custom nodes up in `generators` only (for example `shapes.record()` of `createShapes`), never in the global registry; the jobs then run in the calling thread, since a worker cannot receive functions. */\n readonly isolatedGenerators?: boolean\n}\n\nexport interface ShapeRequest {\n readonly schema: ShapeSchema\n readonly options?: GenerateOptions\n}\n\nexport interface ShapePoolStats {\n readonly workers: number\n readonly jobs: number\n readonly cacheHits: number\n readonly shared: number\n readonly inThread: number\n readonly busy: number\n}\n\nexport interface ShapePool {\n /** `generate(schema, options)` off the main thread. Same key, same promise while in flight; the result is shared (read-only). */\n generate(schema: ShapeSchema, options?: GenerateOptions): Promise<ShapeBuffers>\n /** A list spread over the workers, resolved in input order. */\n generateMany(list: readonly (ShapeSchema | ShapeRequest)[]): Promise<ShapeBuffers[]>\n stats(): ShapePoolStats\n /** Stops the workers; pending jobs reject. */\n terminate(): void\n}\n\ninterface Slot {\n worker: WorkerLike\n pending: Map<number, { resolve: (b: ShapeBuffers) => void; reject: (e: Error) => void }>\n}\n\nconst isRequest = (value: ShapeSchema | ShapeRequest): value is ShapeRequest => (value as ShapeRequest).schema !== undefined && (value as ShapeSchema).root === undefined\n\n/**\n * A pool of shape workers. The schema is cheap (plain data) and is built on the main thread; the buffers are generated in a worker and\n * transferred back. With `size: 0` or no `spawn` it generates in the calling thread, with the same cache and in-flight sharing.\n */\nexport function createShapePool(options: ShapePoolOptions = {}): ShapePool {\n const size = options.spawn ? Math.max(0, options.size ?? 0) : 0\n const cache = options.cache\n const slots: Slot[] = []\n const inFlight = new Map<string, Promise<ShapeBuffers>>()\n let nextId = 1\n let jobs = 0\n let cacheHits = 0\n let shared = 0\n let inThread = 0\n let terminated = false\n\n const failAll = (slot: Slot, error: Error): void => {\n for (const job of slot.pending.values()) job.reject(error)\n slot.pending.clear()\n }\n const spawnSlot = (): Slot => {\n const slot: Slot = { worker: (options.spawn as () => WorkerLike)(), pending: new Map() }\n slot.worker.onmessage = (event) => {\n const reply = event.data as ShapeReply\n const job = slot.pending.get(reply.id)\n if (!job) return\n slot.pending.delete(reply.id)\n if (reply.ok) job.resolve(reply.buffers)\n else job.reject(new Error(reply.error))\n }\n slot.worker.onerror = (event) => {\n // a worker that crashed takes its jobs with it; a fresh one takes its place\n failAll(slot, new Error(`game-shapes worker failed: ${(event as { message?: string })?.message ?? String(event)}`))\n slot.worker.terminate()\n const index = slots.indexOf(slot)\n if (index >= 0 && !terminated) slots[index] = spawnSlot()\n }\n return slot\n }\n for (let i = 0; i < size; i++) slots.push(spawnSlot())\n\n const run = (schema: ShapeSchema, generateOptions: GenerateOptions): Promise<ShapeBuffers> => {\n // custom generators passed per call are functions: they cannot reach a worker, so that job runs here\n if (slots.length === 0 || generateOptions.generators || options.isolatedGenerators) {\n inThread++\n try {\n const generators = { ...(options.generators ?? {}), ...(generateOptions.generators ?? {}) }\n return Promise.resolve(generate(schema, { ...generateOptions, ...(Object.keys(generators).length ? { generators } : {}), ...(options.isolatedGenerators ? { isolatedGenerators: true } : {}) }))\n } catch (error) {\n return Promise.reject(error)\n }\n }\n let slot = slots[0] as Slot\n for (const s of slots) if (s.pending.size < slot.pending.size) slot = s\n const id = nextId++\n const job: ShapeJob = { id, schema, options: generateOptions }\n return new Promise<ShapeBuffers>((resolve, reject) => {\n slot.pending.set(id, { resolve, reject })\n slot.worker.postMessage(job)\n })\n }\n\n const pool: ShapePool = {\n generate(schema, generateOptions = {}) {\n if (terminated) return Promise.reject(new Error('createShapePool: the pool was terminated'))\n jobs++\n const key = shapeKey(schema, generateOptions)\n const hit = cache?.get(key)\n if (hit) {\n cacheHits++\n return Promise.resolve(hit)\n }\n const flying = inFlight.get(key)\n if (flying) {\n shared++\n return flying\n }\n const promise = run(schema, generateOptions).then(\n (buffers) => {\n inFlight.delete(key)\n cache?.set(key, buffers)\n return buffers\n },\n (error: unknown) => {\n inFlight.delete(key)\n throw error\n },\n )\n inFlight.set(key, promise)\n return promise\n },\n generateMany(list) {\n return Promise.all(list.map((item) => (isRequest(item) ? pool.generate(item.schema, item.options) : pool.generate(item))))\n },\n stats: () => ({ workers: slots.length, jobs, cacheHits, shared, inThread, busy: slots.reduce((n, s) => n + s.pending.size, 0) }),\n terminate() {\n terminated = true\n for (const slot of slots) {\n failAll(slot, new Error('createShapePool: the pool was terminated'))\n slot.worker.terminate()\n }\n slots.length = 0\n },\n }\n return pool\n}\n","import { generate } from './generate'\nimport { transferablesOf } from './merge'\nimport type { GenerateOptions, ShapeBuffers, ShapeGenerator, ShapeSchema } from './types'\n\n/** A job the pool posts: `options` without `generators` (functions do not cross threads; register them in the worker script). */\nexport interface ShapeJob {\n readonly id: number\n readonly schema: ShapeSchema\n readonly options?: Omit<GenerateOptions, 'generators'>\n}\n\nexport type ShapeReply = { readonly id: number; readonly ok: true; readonly buffers: ShapeBuffers } | { readonly id: number; readonly ok: false; readonly error: string }\n\n/** What a worker scope looks like: `self` in a browser worker, a `worker_threads` `parentPort` wrapper in Node, or an in-thread fake. */\nexport interface WorkerScopeLike {\n onmessage: ((event: { data: unknown }) => void) | null\n postMessage(message: unknown, transfer?: ArrayBuffer[]): void\n}\n\nexport interface ShapeWorkerOptions {\n /** Generators of the `custom` nodes, the same ones the main thread registers. */\n readonly generators?: Readonly<Record<string, ShapeGenerator>>\n /** Transfer the arrays back (default true: zero copy, the worker keeps nothing). */\n readonly transfer?: boolean\n}\n\n/**\n * The worker side of `createShapePool`: answers each job with `generate(schema, options)`, transferring every array.\n *\n * ```ts\n * // shape-worker.ts\n * import { installShapeWorker } from '@adatechnology/game-shapes/worker'\n * installShapeWorker(self as never, { generators: myGenerators })\n * ```\n */\nexport function installShapeWorker(scope: WorkerScopeLike, options: ShapeWorkerOptions = {}): void {\n const transfer = options.transfer !== false\n scope.onmessage = (event) => {\n const job = event.data as ShapeJob\n try {\n const buffers = generate(job.schema, { ...(job.options ?? {}), ...(options.generators ? { generators: options.generators } : {}) })\n const reply: ShapeReply = { id: job.id, ok: true, buffers }\n scope.postMessage(reply, transfer ? transferablesOf(buffers) : [])\n } catch (error) {\n const reply: ShapeReply = { id: job.id, ok: false, error: error instanceof Error ? error.message : String(error) }\n scope.postMessage(reply)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,WAAS,SAASA,QAA0B,WAAW,UAAkB;AAC9E,QAAIA,WAAU,OAAW,QAAO;AAChC,QAAI,OAAOA,WAAU,SAAU,QAAO,KAAK,MAAMA,MAAK;AACtD,UAAM,QAAQ,sBAAsB,KAAKA,MAAK;AAC9C,QAAI,CAAC,MAAO,OAAM,IAAI,MAAM,wBAAwBA,MAAK,8BAA8B;AACvF,WAAO,SAAS,MAAM,CAAC,GAAa,EAAE;AAAA,EACxC;AAGO,M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M,IAAI,MAAM,0CAA0C,CAAC;AACnE,eAAK,OAAO,UAAU;AAAA,QACxB;AACA,cAAM,SAAS;AAAA,MACjB;AAAA,IACF;AACA,WAAO;AAAA,EACT;;;AC/HO,WAAS,mBAAmB,OAAwB,UAA8B,CAAC,GAAS;AACjG,UAAM,WAAW,QAAQ,aAAa;AACtC,UAAM,YAAY,CAAC,UAAU;AAC3B,YAAM,MAAM,MAAM;AAClB,UAAI;AACF,cAAM,UAAU,SAAS,IAAI,QAAQ,EAAE,GAAI,IAAI,WAAW,CAAC,GAAI,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC,EAAG,CAAC;AAClI,cAAM,QAAoB,EAAE,IAAI,IAAI,IAAI,IAAI,MAAM,QAAQ;AAC1D,cAAM,YAAY,OAAO,WAAW,gBAAgB,OAAO,IAAI,CAAC,CAAC;AAAA,MACnE,SAAS,OAAO;AACd,cAAM,QAAoB,EAAE,IAAI,IAAI,IAAI,IAAI,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE;AACjH,cAAM,YAAY,KAAK;AAAA,MACzB;AAAA,IACF;AAAA,EACF;","names":["color","p","width","height","depth","indexArray","sign","list","num","equals","area","ring","bs","layeroffset","color","pack","list"]}
|