@adatechnology/game-terrain-three 0.6.7 → 0.6.9

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/fireball.ts","../../game-contracts/src/blast-wave.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/body-measures.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/rain-cover.ts","../../game-contracts/src/nav-obstacles.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../../game-terrain/src/terrain.ts","../../game-terrain/src/catalog.ts","../../game-terrain/src/random.ts","../../game-terrain/src/cracks.ts","../../game-terrain/src/debris.ts","../../game-terrain/src/ground-loss.ts","../../game-terrain/src/height-patch.ts","../../game-terrain/src/marks.ts","../../game-terrain/src/impl.ts","../../game-terrain/src/types.ts","../../game-terrain/src/footprints.ts","../../game-terrain/src/buoyancy.ts","../src/surface-material.ts","../src/chunk-geometry.ts","../src/decal-layers.ts","../src/layers.ts","../src/zone-layer.ts","../src/rebar.ts","../src/renderer.ts","../src/test-area/locale.ts","../src/test-area/test-module.ts"],"sourcesContent":["export { createTerrainRenderer } from './renderer'\nexport type { TerrainRenderer, TerrainRendererOptions } from './renderer'\nexport { createSurfaceMaterial } from './surface-material'\n/** @deprecated import from '@adatechnology/game-terrain-three/testing' */\nexport { createTerrainTestModule, terrainLotsGround, TERRAIN_AREA_GROUND, TERRAIN_STRIPS } from './testing'\nexport { terrainProfileName } from './test-area/locale'\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 by default: inside it the charge is in contact and the body is torn apart anyway (a caller that loads a part next to the charge passes a smaller `nearest`). */\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, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, nearest) / w3\n // products, not `**` past 2: V8 gives `x ** 3` a different last bit on Node 22 and 24, and the goldens must agree on both\n const near = (z / 0.23) * (z / 0.23)\n const far = z / 1.55\n const scaled = (0.067 * Math.sqrt(1 + near * near)) / (z * z * Math.cbrt(1 + far * far * far))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/** Sea-level atmospheric pressure, Pa. */\nconst ATMOSPHERE = 101325\n\n/**\n * Peak side-on (incident) overpressure of the wave, in Pa, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `Ps/Pa = 808 (1 + (Z/4.5)^2) / (sqrt(1 + (Z/0.048)^2) sqrt(1 + (Z/0.32)^2) sqrt(1 + (Z/1.35)^2))`, with the scaled distance `Z = R / W^(1/3)` (m/kg^(1/3)).\n * What a wall takes from a blast is read against it: about 7 kPa cracks plaster and breaks windows, 14 to 20 kPa knocks parts of a brick wall out, 35 kPa and over brings an\n * unreinforced brick wall down (Glasstone and Dolan, \"The Effects of Nuclear Weapons\", 1977, table 5.139; UFC 3-340-02).\n */\nexport function sideOnOverpressure(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, nearest) / Math.cbrt(tnt)\n const ratio = (808 * (1 + (z / 4.5) ** 2)) / (Math.sqrt(1 + (z / 0.048) ** 2) * Math.sqrt(1 + (z / 0.32) ** 2) * Math.sqrt(1 + (z / 1.35) ** 2))\n return ratio * ATMOSPHERE\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 { bodyImpulse, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport 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 * A target that says its `area` (m2 it shows the wave) is pushed by the blast wave itself instead (`bodyImpulse`: Kinney-Graham impulse of the charge `blast.tnt`, or of `energy` by\n * `tntPerJoule`, reflected on that area, divided by the mass): a 2 kg shovel 0.8 m from a hand grenade gets a few m/s, not the cap. `maxSpeed` still caps it (a light thing next to the charge would otherwise tunnel through what stands in its way); `coupling` and `falloffPower` do not apply.\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; readonly area?: 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 =\n target.area !== undefined\n ? Math.min(o.maxSpeed, (bodyImpulse(blast.tnt ?? blast.energy * DEFAULT_BLAST_IMPULSE.tntPerJoule, distance) * target.area * reach) / mass)\n : 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 heat of a blast, from the size and life of its fireball and not from the game radius of the blast. Pure functions in SI units (m, s, W/m2, J/m2).\n *\n * A condensed charge (TNT, Composition B, C4) makes a small fireball that lives milliseconds: its radius and its life both grow as the cube root of the charge\n * (Hopkinson-Cranz scaling, as the wave does). A burning fuel (the gas of a cylinder that bursts, petrol) makes a fireball metres wide that lives about a second:\n * the BLEVE correlations of the CCPS guidelines, `D = 5.8 M^(1/3)` m and `t = 0.45 M^(1/3)` s for `M` kg of fuel, with a surface emissive power of a few hundred kW/m2.\n * What a surface takes is the heat per square metre over the life of the fireball: the whole flux inside it, and outside it the share a sphere of radius `R` sends to a\n * surface that faces it at `d` from its centre (the view factor `(R / d)^2`). A surface catches fire when that dose passes what its material needs (`ignitionDose`).\n */\n\n/** The fireball of a blast: how wide, how long and how hot it burns on what it touches. */\nexport interface Fireball {\n /** Metres. */\n readonly radius: number\n /** Seconds the fireball lives. */\n readonly seconds: number\n /** W/m2 it puts on a surface inside it (radiation and the hot gases together). */\n readonly flux: number\n}\n\n/** m/kg^(1/3): radius of the luminous fireball of a condensed charge (an engineering estimate; the M67, 0.24 kg of TNT, is 0.8 m). */\nconst CHARGE_RADIUS = 1.3\n/** s/kg^(1/3): its life (the M67 burns 6 ms). */\nconst CHARGE_SECONDS = 0.01\n/** W/m2 on a surface inside the fireball of a condensed charge: detonation products at some 2500 K, radiation and convection. */\nconst CHARGE_FLUX = 1.5e6\n/** m/kg^(1/3): radius of a fuel fireball, half of the CCPS diameter 5.8 M^(1/3). */\nconst FUEL_RADIUS = 2.9\n/** s/kg^(1/3): life of a fuel fireball (CCPS, below 30 t of fuel). */\nconst FUEL_SECONDS = 0.45\n/** W/m2: surface emissive power of a hydrocarbon fireball (CCPS gives 200 to 350). */\nconst FUEL_FLUX = 250e3\n/** J/m2 per degree between the room and the ignition temperature: the dose a solid needs to light under a brief heat (paper at 230 °C takes 63 kJ/m2, hard wood at 330 °C 93). */\nconst DOSE_PER_DEGREE = 300\n\n/** The fireball of `tnt` kg of TNT equivalent of a condensed charge. */\nexport function chargeFireball(tnt: number): Fireball {\n const cube = Math.cbrt(Math.max(0, tnt))\n return { radius: CHARGE_RADIUS * cube, seconds: CHARGE_SECONDS * cube, flux: CHARGE_FLUX }\n}\n\n/** The fireball of `fuel` kg of a burning hydrocarbon (the gas of a cylinder, petrol). */\nexport function fuelFireball(fuel: number): Fireball {\n const cube = Math.cbrt(Math.max(0, fuel))\n return { radius: FUEL_RADIUS * cube, seconds: FUEL_SECONDS * cube, flux: FUEL_FLUX }\n}\n\n/** J/m2 a surface facing the fireball takes at `distance` metres from its centre: the whole flux inside it, the view factor `(R / d)^2` of the sphere outside. */\nexport function fireballDose(fireball: Fireball, distance: number): number {\n const share = distance <= fireball.radius ? 1 : (fireball.radius / distance) ** 2\n return fireball.flux * fireball.seconds * share\n}\n\n/** J/m2 a surface of a material that ignites at `ignitionC` needs to catch fire from a brief heat, starting at `ambientC`. */\nexport function ignitionDose(ignitionC: number, ambientC = 20): number {\n return DOSE_PER_DEGREE * Math.max(1, ignitionC - ambientC)\n}\n","import { sideOnImpulse, sideOnOverpressure } from './blast-impulse'\n\n/**\n * The blast wave on a part, from Hopkinson-Cranz scaling: the reflected load of a charge of TNT equivalent at a distance (Kinney and Graham's side-on fits, reflected by\n * Rankine-Hugoniot for the pressure and the Kingery-Bulmash ratio for the impulse), and the work it puts into a part of a given area, mass and thickness (the smaller\n * asymptote of its pressure-impulse diagram, Baker et al. 1983). Shared by the destruction world and every module that takes blasts on its own parts (vehicles).\n */\n\n/** Pa */\nconst ATMOSPHERE = 101325\n/** Scaled distance (m/kg^(1/3)) below which the far-field fits are held: closer is a charge in contact, where the fits stop being the wave. */\nconst NEAREST_SCALED = 0.2\n/** m: a charge's near field and the size of a charge add this much to the standoff when the area the wave loads evenly is taken. */\nconst LOADED_MARGIN = 0.15\n/** J/kg: the TNT equivalent's definition. */\nexport const TNT_JOULES = 4.184e6\n/**\n * Share of the charge energy that a target crushes and spalls when the charge is in contact with it, at the scaled distance 0 (an engineering estimate of the cratering efficiency of\n * contact charges in concrete and masonry: a few percent of the energy goes into breaking the material, the rest into air and ground shock).\n */\nconst SHOCK_COUPLING = 0.04\n/** m/kg^(1/3): scaled distance at which the crushing and spalling of a surface is a quarter of that at contact (they fall off as `(1 + (Z / Z0)^2)^-2`; spalling of concrete stops near Z = 1.5). */\nconst SHOCK_SCALED = 0.6\n\n/** The wave on a face that looks at the charge: reflected peak overpressure (Pa) and reflected positive impulse (Pa s). */\nexport interface WaveLoad {\n readonly pressure: number\n readonly impulse: number\n}\n\n/** The reflected load at `distance` m from `tnt` kg of TNT. */\nexport function reflectedLoad(tnt: number, distance: number): WaveLoad {\n if (!(tnt > 0)) return { pressure: 0, impulse: 0 }\n const cube = Math.cbrt(tnt)\n const nearest = NEAREST_SCALED * cube\n const side = sideOnOverpressure(tnt, distance, nearest)\n const z = Math.max(distance, nearest) / cube\n // ideal gas, normal reflection: Pr = 2 Ps (7 Pa + 4 Ps) / (7 Pa + Ps), 2 for a weak wave, up to 8 for a strong one\n const pressure = (2 * side * (7 * ATMOSPHERE + 4 * side)) / (7 * ATMOSPHERE + side)\n const impulse = sideOnImpulse(tnt, distance, nearest) * (2 + 4 / (1 + z * z))\n return { pressure, impulse }\n}\n\n\nexport interface WaveWorkInput {\n /** Kilograms of TNT. */\n readonly tnt: number\n /** Metres from the charge to the nearest point of the part. */\n readonly distance: number\n /** 0..1: the share of the wave that gets through what stands in between. */\n readonly reach: number\n /** m2 the part shows the charge. */\n readonly area: number\n readonly mass: number\n /** m: how far the part moves under the wave before it fails (its own thickness). */\n readonly thickness: number\n}\n\nexport interface WaveWork {\n /** m2 the wave loads evenly. */\n readonly loaded: number\n /** Joules the wave puts into the part as a whole (it moves and bends, the P-I work). */\n readonly energy: number\n /** Joules that crush and spall the face next to the charge (`shockWork`), on top of `energy`. */\n readonly shock: number\n /** Reflected peak overpressure on the part (Pa), after cover. */\n readonly pressure: number\n}\n\n/**\n * What a blast puts into a part: `min(J^2 / 2 m, P A d)` with the load `P`, `J / A` of `reflectedLoad` cut by `reach`, over the area the wave loads evenly (a disc as wide as the\n * standoff, so a wall 10 m wide is not loaded as one block by a charge 1 m from it) and the mass of the piece of the part under that area. A 2 mm steel blade 0.8 m from an M67 gets\n * about 75 J (a dent); a 2 tonne wall 1.5 m away gets about 120 J (a scuff), so the damage depends on how much the part weighs for the area it shows.\n */\nexport function waveWork(input: WaveWorkInput): WaveWork {\n const load = reflectedLoad(input.tnt, input.distance)\n const reach = Math.min(1, Math.max(0, input.reach))\n const pressure = load.pressure * reach\n if (!(input.area > 0) || !(input.mass > 0) || pressure <= 0) return { energy: 0, shock: 0, pressure, loaded: 0 }\n const loaded = Math.min(input.area, Math.PI * (input.distance + LOADED_MARGIN) ** 2)\n const mass = input.mass * (loaded / input.area)\n const impulse = load.impulse * reach * loaded\n const impulsive = (impulse * impulse) / (2 * mass)\n const quasiStatic = pressure * loaded * Math.max(input.thickness, 1e-4)\n return { energy: Math.min(impulsive, quasiStatic), shock: shockWork(input), pressure, loaded }\n}\n\n/**\n * Crushing and spalling of the face next to a charge, which the far-field fits do not see: the charge energy `W * 4.184 MJ`, times the share that crushes material at that scaled\n * distance (`SHOCK_COUPLING (1 + (Z / 0.6)^2)^-2`), times the share of the sphere around the charge that the part intercepts (`A / 4 pi (R + r_c)^2`, at most a half: a face on the charge).\n * A grenade 0.8 m from a blade gives it about 1 J of this; a block of C4 against a wall gives it tens of kilojoules.\n */\nfunction shockWork(input: WaveWorkInput): number {\n const cube = Math.cbrt(input.tnt)\n if (!(cube > 0) || !(input.area > 0)) return 0\n const z = Math.max(input.distance, 0) / cube\n const radius = Math.cbrt((3 * input.tnt) / (4 * Math.PI * 1600))\n const share = Math.min(0.5, input.area / (4 * Math.PI * (input.distance + radius) ** 2))\n // products, not `**` past 2: V8 gives `x ** -2` a different last bit on Node 22 and 24, and the goldens must agree on both\n const falloff = 1 + (z / SHOCK_SCALED) * (z / SHOCK_SCALED)\n const reach = Math.min(1, Math.max(0, input.reach))\n return (SHOCK_COUPLING * input.tnt * TNT_JOULES * share * reach * reach) / (falloff * falloff)\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\n/**\n * One drawn piece of a hosted body as a solid for a physics engine, in the impl's frame (`DestructibleImpl.colliders`): a box turned as drawn where a box fits the piece\n * (every corner within 1 cm of a vertex), else the piece's triangles (`mesh`, with the box around them). `id` is the part of `describe()` the piece is.\n * A piece handed back is never changed in place: a piece that changed is a new object (the world reuses what it made of an object it has seen, `hostedSolids`).\n */\nexport interface DrawnCollider {\n readonly id: string\n /** Names the piece across lists (a piece measured again is the same piece): without it, the place in the list. */\n readonly key?: string\n readonly center: Vec3\n readonly half: Vec3\n readonly rotation: [number, number, number, number]\n readonly mesh?: { readonly vertices: Float32Array; readonly indices: Uint32Array }\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 /**\n * The pieces the impl draws, as what an engine collides with in their place (in the frame `describe()` answers in): one per drawn piece, none for a part that broke or\n * came off. Without it the engine takes the boxes of `describe()`. Same cost contract as `describe()`: the world asks again only when state, place or a pose changes.\n */\n colliders?(): readonly DrawnCollider[]\n /** True while `colliders()` still has pieces to make (a vehicle that just spawned fills in over several updates): the world asks again at the next update. */\n collidersPending?(): boolean\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', 'pieces'], 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 if (hit.pieces !== undefined && !(Number.isFinite(hit.pieces) && hit.pieces >= 1)) out.push(`${hit.type} hit \"pieces\" must be a finite number of at least 1`)\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 { Vec3 } from './destruction'\n\n/** Anthropometric measures of a standing/seated body derived from stature and lateral build (metres). */\nexport type BodyMeasures = {\n /** Standing stature from sole to top of skull (excluding hair/hat), in metres. */\n readonly heightMetres: number\n /** Lateral build multiplier (1.0 = reference adult). */\n readonly build: number\n /** Vertical distance from seat surface (H-point) to top of skull, in metres. */\n readonly seatedHeightMetres: number\n /** Vertical distance from seat surface (H-point) to eye level, in metres. */\n readonly seatedEyeHeightMetres: number\n /** Bideltoid shoulder width, in metres. */\n readonly shoulderWidthMetres: number\n /** Horizontal buttock-to-knee length (hip to front of knee), in metres. */\n readonly thighLengthMetres: number\n /** Vertical knee-to-sole length (popliteal/knee height), in metres. */\n readonly shinLengthMetres: number\n}\n\n/** Functional roles a vehicle seat can play. */\nexport const SEAT_ROLES = ['driver', 'front_passenger', 'rear', 'cargo', 'rider', 'pilot', 'crew'] as const\n\n/** Functional role of a vehicle seat. */\nexport type SeatRole = (typeof SEAT_ROLES)[number]\n\n/** Usable interior clearance of one seat in vehicle local coordinates (+x front, +y up, +z right), in metres. */\nexport type SeatSpace = {\n /** Stable seat identifier within the vehicle (e.g. 'driver', 'front_right', 'rear_left', 'rider'). */\n readonly id: string\n /** Functional role of the seat. */\n readonly role: SeatRole\n /** Seat hip point (H-point, cushion top centre) in vehicle local coordinates, in metres. */\n readonly hipPoint: Vec3\n /** Clear vertical height from hipPoint to headliner/roof (minimum of 5 rays). `Infinity` for open vehicles/bikes/boats. */\n readonly headroomMetres: number\n /** Clear longitudinal knee/leg space from hipPoint along seat facing direction to first obstruction. `Infinity` if open. */\n readonly legroomMetres: number\n /** Available lateral width at shoulder height for this seat, in metres. `Infinity` for open-sided seats. */\n readonly widthMetres: number\n /** Id of the door opening that serves this seat (matches `DoorOpening.id`); `undefined` for open entry. */\n readonly doorId?: string\n}\n\n/** Clear opening of a vehicle door or hatch, in metres. */\nexport type DoorOpening = {\n /** Matches the vehicle door zone id (e.g. 'door_front_left', 'hatch_commander'). */\n readonly id: string\n /** Clear horizontal opening width, in metres. `Infinity` if open entry. */\n readonly widthMetres: number\n /** Clear vertical opening height, in metres. `Infinity` if open entry. */\n readonly heightMetres: number\n}\n\n/** Canonical reasons a body cannot fit a seat/door pair (Spec 012 D2). */\nexport const FIT_REJECT_REASONS = ['head', 'legs', 'shoulders', 'door'] as const\n\n/** Why a body does not fit a seat/door pair (binary with reason). */\nexport type FitRejectReason = (typeof FIT_REJECT_REASONS)[number]\n\n/** Result of checking whether a body fits a seat (and optionally its access door). */\nexport type FitResult =\n | { readonly fits: true }\n | { readonly fits: false; readonly reason: FitRejectReason }\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 /**\n * The shaft of a two-handed tool (a shovel, an axe, a sledgehammer) the left hand may slide along, world space: a left grip out of the arm's reach is taken at the nearest point of\n * this segment the hand reaches, the hand still closed on the shaft, as one shortens the grip on a handle. Absent, the left hand goes to `L` or stops short of it.\n */\n slideL?: { readonly from: Vec3; readonly to: Vec3 } | 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 /** The same for the left hand (its index on the trigger of a tool of its own, with a tool in each hand); absent, the left hand's fingers all follow `gripL`. */\n fingersL?: { 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/** A hand of the body: `R` the right, `L` the left. A tool in one hand alone is in the right; the left holds one of its own only with a tool in each hand (`HostTool.offHand`). */\nexport type ToolHand = 'R' | 'L'\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). `hand` is the hand that fired (absent: the right one); a source that draws\n * one tool only answers the same for both.\n */\nexport type MuzzleSource = (hand?: ToolHand) => 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 /** The queue runs to empty in the drain of its phase, outside the frame deadline and the budget (the blow's visible effect). Counted apart. Default false. */\n readonly mustDrain?: boolean\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 BREACH_CUT: 'floorplan.breach-cut',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n AUDIO_OCCLUSION: 'audio.occlusion',\n FLUID_FILM: 'fluids.film',\n VEHICLE_LOD_BATCH: 'vehicles.lod-batch',\n SETTLED_BATCH: 'destruction.settled-batch',\n STATIC_BATCH: 'render.static-batch',\n ANIMALS_STATIC_BATCH: 'animals.static-batch',\n CHARACTERS_STATIC_BATCH: 'characters.static-batch',\n HOUSE_SHADOW_BATCH: 'floorplan.shadow-batch',\n DESTRUCTION_PREFIT: 'destruction.prefit',\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 // every frame: the walls cut since the last frame are painted once each, and a hole must show in the frame of the blast\n [DEFERRED_QUEUE_ID.BREACH_CUT]: { priority: 260, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_OCCLUSION]: { priority: 190, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.FLUID_FILM]: { priority: 120, phase: 'idle', minEveryFrames: 2 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n [DEFERRED_QUEUE_ID.VEHICLE_LOD_BATCH]: { priority: 90, phase: 'idle', minEveryFrames: 4 },\n [DEFERRED_QUEUE_ID.SETTLED_BATCH]: { priority: 70, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.ANIMALS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.CHARACTERS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.HOUSE_SHADOW_BATCH]: { priority: 50, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.DESTRUCTION_PREFIT]: { priority: 40, phase: 'idle', minEveryFrames: 30 },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\n/** The queues that may register with `mustDrain: true`: a new one needs the owner's decision (CLAUDE.md §15), and `budget.register` throws for any other. */\nexport const MUST_DRAIN_QUEUE_IDS: ReadonlySet<string> = new Set([DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS, DEFERRED_QUEUE_ID.BREACH_CUT])\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\n/** Drains a queue no budget registered (D2): runs it until `budgetMs` from now. The one place outside game-runtime that times deferred work. */\nexport function drainDetached(queue: DeferredQueue, budgetMs: number, clock: () => number = () => performance.now()): number {\n return queue.run(clock() + budgetMs, clock)\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 picture of the real thing the card is about, with its author and licence: the host shows it on the card, linked to `page`. */\n readonly image?: { readonly url: string; readonly alt: string; readonly credit?: string; readonly page?: 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","/** A world rectangle `[x0, z0, x1, z1]`, metres. */\nexport type RainCoverBounds = readonly [x0: number, z0: number, x1: number, z1: number]\n\n/**\n * Something with a roof or a slab over it (a house, a shed, a bus stop, a car): it says, for a point on the ground plan, how high the cover over it is.\n * The rain asks before it falls, splashes or wets the ground: under a cover there is none.\n */\nexport interface RainCoverSource {\n /** Where the source may cover anything; a point outside is never asked. */\n bounds(): RainCoverBounds\n /** Top (world y, metres) of the highest intact roof or slab over (x, z); `undefined` for open sky, or for a hole a blast or a collapse opened. */\n coverTopAt(x: number, z: number): number | undefined\n /** Grows whenever the covers change (a roof panel broke, a hole opened): whoever caches reads it. */\n version(): number\n}\n\n/** What the rain reads (`ModuleHost.rainCover`): every source of the host together. */\nexport interface RainCover {\n /** The highest cover over (x, z) among the sources, or `undefined` for open sky. */\n coverTopAt(x: number, z: number): number | undefined\n /** Changes whenever a source is added or removed or one of them changes. */\n version(): number\n /** True while there is no source: the rain skips the test. */\n isEmpty(): boolean\n /** Adds a source; returns the function that takes it away. */\n add(source: RainCoverSource): () => void\n}\n\nexport function createRainCover(): RainCover {\n const sources = new Set<RainCoverSource>()\n let list: RainCoverSource[] = []\n let membership = 0\n return {\n coverTopAt(x, z) {\n let top: number | undefined\n for (const source of list) {\n const [x0, z0, x1, z1] = source.bounds()\n if (x < x0 || x > x1 || z < z0 || z > z1) continue\n const value = source.coverTopAt(x, z)\n if (value !== undefined && (top === undefined || value > top)) top = value\n }\n return top\n },\n version() {\n let sum = membership\n for (const source of list) sum += source.version()\n return sum\n },\n isEmpty: () => list.length === 0,\n add(source) {\n sources.add(source)\n list = [...sources]\n membership++\n return () => {\n if (!sources.delete(source)) return\n list = [...sources]\n membership++\n }\n },\n }\n}\n\nexport type GridRainCoverOptions = {\n readonly bounds: RainCoverBounds\n /** Side of a cell, metres (default 0.25: a blast hole is bigger). */\n readonly cellSize?: number\n /** The exact answer at a cell centre; called again for every cell only after `invalidate`. */\n readonly coverTopAt: (x: number, z: number) => number | undefined\n}\n\nexport type GridRainCoverSource = RainCoverSource & {\n /** The covers changed (a roof panel broke): the grid is cut again on the next question, and `version` grows. */\n invalidate(): void\n}\n\nconst NO_COVER = -Infinity\n\n/** A source answered from a grid cut once from `coverTopAt`: a question is two array reads, however many panels the roof has. */\nexport function createGridRainCover(options: GridRainCoverOptions): GridRainCoverSource {\n const [x0, z0, x1, z1] = options.bounds\n const cell = options.cellSize ?? 0.25\n const columns = Math.max(1, Math.ceil((x1 - x0) / cell))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cell))\n const cells = new Float32Array(columns * rows)\n let revision = 0\n let isCut = false\n const cut = (): void => {\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n const top = options.coverTopAt(x0 + (column + 0.5) * cell, z0 + (row + 0.5) * cell)\n cells[row * columns + column] = top === undefined ? NO_COVER : top\n }\n }\n isCut = true\n }\n return {\n bounds: () => options.bounds,\n coverTopAt(x, z) {\n if (!isCut) cut()\n const column = Math.floor((x - x0) / cell)\n const row = Math.floor((z - z0) / cell)\n if (column < 0 || row < 0 || column >= columns || row >= rows) return undefined\n const top = cells[row * columns + column]!\n return top === NO_COVER ? undefined : top\n },\n version: () => revision,\n invalidate() {\n isCut = false\n revision++\n },\n }\n}\n\n/** A roof or slab seen from above: the rectangle it covers and the height of its top. */\nexport type RainCoverRect = { readonly bounds: RainCoverBounds; readonly top: number }\n\n/** A round opening in a cover (a blast hole), centre and radius in the ground plan. */\nexport type RainCoverHole = { readonly x: number; readonly z: number; readonly radius: number }\n\n/** The exact answer for a list of rectangles with holes: the highest rectangle over the point whose hole does not take the point. */\nexport function rainCoverTopOf(rects: readonly RainCoverRect[], holes: readonly RainCoverHole[], x: number, z: number): number | undefined {\n let top: number | undefined\n for (const rect of rects) {\n if (x < rect.bounds[0] || x > rect.bounds[2] || z < rect.bounds[1] || z > rect.bounds[3]) continue\n if (top !== undefined && rect.top <= top) continue\n if (holes.some((hole) => (x - hole.x) ** 2 + (z - hole.z) ** 2 <= hole.radius ** 2)) continue\n top = rect.top\n }\n return top\n}\n\n/** A roof seen from above as a turned rectangle: its centre on the ground plan, half sides along its own axes, the turn about y and the height of its top. */\nexport type RainCoverFootprint = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly yaw: number; readonly top: number }\n\nexport type FootprintRainCoverSource = RainCoverSource & {\n /**\n * Puts the roofs and the openings where they are now (a car moved, a window broke). The answer follows at once; the version grows only with `bumpVersion`,\n * which a mover asks once it has gone far enough for whoever caches (the far curtain) to cut again.\n */\n set(footprints: readonly RainCoverFootprint[], openings: readonly RainCoverFootprint[], bumpVersion: boolean): void\n}\n\ntype Prepared = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly cos: number; readonly sin: number; readonly top: number }\n\nconst prepare = (f: RainCoverFootprint): Prepared => ({ x: f.x, z: f.z, halfX: f.halfX, halfZ: f.halfZ, cos: Math.cos(f.yaw), sin: Math.sin(f.yaw), top: f.top })\n\nconst insideTurned = (f: Prepared, x: number, z: number): boolean => {\n const dx = x - f.x\n const dz = z - f.z\n return Math.abs(dx * f.cos + dz * f.sin) <= f.halfX && Math.abs(-dx * f.sin + dz * f.cos) <= f.halfZ\n}\n\n/**\n * A source of turned rectangles with openings (a car's cabin, a tent, a kiosk): a question is a few multiplications per rectangle, no allocation, so the near rain\n * asks it for every drop. `set` moves the rectangles whenever the thing moves; nothing else is cut or cached.\n */\nexport function createFootprintRainCover(): FootprintRainCoverSource {\n let roofs: Prepared[] = []\n let openings: Prepared[] = []\n let bounds: RainCoverBounds = [0, 0, 0, 0]\n let revision = 0\n return {\n bounds: () => bounds,\n version: () => revision,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) {\n if ((top !== undefined && roof.top <= top) || !insideTurned(roof, x, z)) continue\n top = roof.top\n }\n if (top === undefined) return undefined\n for (const opening of openings) if (insideTurned(opening, x, z)) return undefined\n return top\n },\n set(footprints, cutouts, bumpVersion) {\n roofs = footprints.map(prepare)\n openings = cutouts.map(prepare)\n let x0 = Infinity\n let z0 = Infinity\n let x1 = -Infinity\n let z1 = -Infinity\n for (const roof of roofs) {\n const reach = Math.abs(roof.halfX * roof.cos) + Math.abs(roof.halfZ * roof.sin)\n const reachZ = Math.abs(roof.halfX * roof.sin) + Math.abs(roof.halfZ * roof.cos)\n x0 = Math.min(x0, roof.x - reach)\n x1 = Math.max(x1, roof.x + reach)\n z0 = Math.min(z0, roof.z - reachZ)\n z1 = Math.max(z1, roof.z + reachZ)\n }\n bounds = roofs.length === 0 ? [0, 0, 0, 0] : [x0, z0, x1, z1]\n if (bumpVersion) revision++\n },\n }\n}\n\n/** The most cells a fixed footprint cover cuts: a wide district gets a coarser cell instead of a bigger grid. */\nconst FIXED_COVER_MAX_CELLS = 1_000_000\n\n/** A source of turned rectangles that never move (the buildings of a district, a tent, a kiosk): answered from a grid cut once, two array reads a question however many roofs there are. */\nexport function createFixedFootprintRainCover(footprints: readonly RainCoverFootprint[], cellSize = 0.5): RainCoverSource {\n const roofs = footprints.map(prepare)\n if (roofs.length === 0) return { bounds: () => [0, 0, 0, 0], coverTopAt: () => undefined, version: () => 0 }\n const x0 = Math.min(...roofs.map((r) => r.x - Math.abs(r.halfX * r.cos) - Math.abs(r.halfZ * r.sin)))\n const x1 = Math.max(...roofs.map((r) => r.x + Math.abs(r.halfX * r.cos) + Math.abs(r.halfZ * r.sin)))\n const z0 = Math.min(...roofs.map((r) => r.z - Math.abs(r.halfX * r.sin) - Math.abs(r.halfZ * r.cos)))\n const z1 = Math.max(...roofs.map((r) => r.z + Math.abs(r.halfX * r.sin) + Math.abs(r.halfZ * r.cos)))\n const cell = Math.max(cellSize, Math.sqrt(((x1 - x0) * (z1 - z0)) / FIXED_COVER_MAX_CELLS))\n return createGridRainCover({\n bounds: [x0, z0, x1, z1],\n cellSize: cell,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) if ((top === undefined || roof.top > top) && insideTurned(roof, x, z)) top = roof.top\n return top\n },\n })\n}\n","/** What an obstacle on the ground is to a walker: a solid (a wall, a lot wall, a fence, a board) or a door (a door or a gate, which opens and can be broken). */\nexport const NAV_OBSTACLE_KIND = { SOLID: 'solid', DOOR: 'door' } as const\nexport type NavObstacleKind = (typeof NAV_OBSTACLE_KIND)[keyof typeof NAV_OBSTACLE_KIND]\n\n/** A box of an obstacle on the ground: world metres `[x0, z0, x1, z1]` and how high it stands over the ground (a low remnant of a wall can be climbed). */\nexport type NavObstacleBox = {\n readonly rect: readonly [number, number, number, number]\n readonly height: number\n}\n\n/**\n * One thing that stops a walker on the ground, as the SDK that builds it publishes it for a navigation grid (the crowd's): a whole wall is one box, a wall a blast\n * cut stands in the boxes of what is left of it, a wall that is gone has none. A door is one box, passable while `open`.\n */\nexport type NavObstacle = {\n /** Stable for the life of the source: a change names the same obstacle again. */\n readonly id: string\n readonly kind: NavObstacleKind\n readonly boxes: readonly NavObstacleBox[]\n /** A door or a gate that lets walkers through now (always false for a solid). */\n readonly open: boolean\n /** A door the barricade's boards cover, each making it harder to break (0 for none). */\n readonly boards: number\n}\n\n/**\n * The obstacles one or more SDKs put on the ground (the houses' walls, doors, lot walls and gates), for whoever keeps a navigation grid. Pulled once per fixed step, so a\n * grid that follows it changes at the same step on every run.\n */\nexport type NavObstacleSource = {\n /** Every obstacle as it stands now. */\n obstacles(): readonly NavObstacle[]\n /** The obstacles that changed since the last call (a door opened or closed, a wall cut or gone); empty when none did. */\n changes(): readonly NavObstacle[]\n /** A walker broke the door `id` open (the horde hit it until it gave way): the owner shows it open. */\n breakDoor(id: string): void\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 laterite: 'gravel',\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 * The worker coordinator as the packages see it: a package declares its heavy work as a task kind (a pure function of plain data) or a\n * resident kind (an instance pinned to one worker), and takes a `WorkerCoordinator` through its options. The implementation is\n * `@adatechnology/game-workers`; nothing in a package makes a `Worker` of its own (CLAUDE.md §14).\n */\n\n/**\n * The pools a kind runs in. `sim`: physics and anything the next frames read; the result is applied in a fixed frame and computed on the\n * main thread when the worker is late, so it is the same whichever thread made it. `build`: generation at load (shapes, colliders,\n * normals), no frame deadline. `background`: the living world far from the player, the lowest priority, never takes a `sim` worker.\n */\nexport const WORKER_LANES = ['sim', 'build', 'background'] as const\nexport type WorkerLane = (typeof WORKER_LANES)[number]\n\n/**\n * What happens when no worker answers in time (or there is none). `sync`: the main thread runs the same kernel and the late answer is\n * thrown away (the only rule of the `sim` lane). `drop`: the job is given up and its promise rejects with `WorkerTaskDropped`.\n * `keep-waiting`: it waits for a worker (a fresh one after a crash); with no worker at all it runs on the main thread.\n */\nexport const WORKER_LATE_RULES = ['sync', 'drop', 'keep-waiting'] as const\nexport type WorkerLateRule = (typeof WORKER_LATE_RULES)[number]\n\n/** How a kind is scheduled: the defaults the kind declares, any of which a game may override by id (`CoordinatorOptions.kinds`). */\nexport interface WorkerKindSchedule {\n readonly lane: WorkerLane\n /** Higher runs first, as `DEFERRED_PRIORITY`. */\n readonly priority: number\n /** Frames between the frame a job is submitted in and the frame its result is applied in (`sim` lane; default 1). */\n readonly latencyFrames?: number\n readonly late: WorkerLateRule\n}\n\n/**\n * A job with no state: plain data in, plain data out, through `run`, the same function in the worker and on the main thread. `run` reads\n * nothing but its input (a seed travels inside it), so the bytes out are the same whichever thread ran it.\n */\nexport interface TaskKind<In, Out> extends WorkerKindSchedule {\n /** `package.thing`, unique in a coordinator: `destruction.ground-tiles`. */\n readonly id: string\n readonly kind: 'task'\n run(input: In): Out\n /** The buffers of the output to transfer back (zero copy). The input is copied, never transferred, when `late` is `sync` (unless `transferAwaitedInput`): the main thread may still need it. */\n transferOutput?(value: Out): readonly ArrayBuffer[]\n /** The buffers of the input to transfer when `late` is not `sync` (and on awaited jobs of a `sync` kind with `transferAwaitedInput`). */\n transferInput?(value: In): readonly ArrayBuffer[]\n /**\n * With `late: 'sync'`, transfer the input (`transferInput`) on awaited jobs (`run`) too, instead of copying it: for a caller that keeps its own copy of the input for its\n * own fallback (the ground tiles). Once sent, such a job is never run on the main thread (its input is gone): a worker that dies holding it rejects its promise with an\n * error named `WORKER_INPUT_LOST` (`isWorkerInputLost`: the caller makes it from its own copy), one that answers with an error rejects with that error. Jobs read through\n * `submit`/`collect` still copy their input.\n * Needs `transferInput`.\n */\n readonly transferAwaitedInput?: boolean\n /** One input each worker runs once at `warm` (the JIT compiles the kernel before the first real job). */\n readonly warmup?: In\n}\n\n/** One instance of a resident kind: built from `init` once per worker, then stepped. */\nexport interface ResidentInstance<Step, Result> {\n step(input: Step): Result\n dispose?(): void\n}\n\n/**\n * A kind with an instance pinned to one worker (the crowd physics, a region of the world). With `late: 'sync'` the step must be a pure\n * function of `init` and the step's input (the state lives on the main thread and travels each step), so a main-thread instance gives the\n * same result; a resident that keeps its own state in the worker uses `drop` or `keep-waiting`.\n */\nexport interface ResidentKind<Init, Step, Result> extends WorkerKindSchedule {\n readonly id: string\n readonly kind: 'resident'\n create(init: Init): ResidentInstance<Step, Result>\n transferOutput?(value: Result): readonly ArrayBuffer[]\n transferInput?(value: Step): readonly ArrayBuffer[]\n}\n\n/** A kind of any input and output, for registries (the methods are bivariant, so every `TaskKind<In, Out>` is one). */\nexport type AnyTaskKind = TaskKind<unknown, unknown>\nexport type AnyResidentKind = ResidentKind<unknown, unknown, unknown>\nexport type AnyWorkerKind = AnyTaskKind | AnyResidentKind\n\n/** Where a result came from. `worker`: on time. `main`: the main thread ran it (late worker, crash, or no worker). */\nexport type WorkerResultSource = 'worker' | 'main'\n\n/** A job of the `sim` lane: its result is read in `dueFrame`, never before, whichever thread made it. */\nexport interface TaskHandle<Out> {\n readonly dueFrame: number\n /**\n * The result in `frame` (>= `dueFrame`, an error before it): the worker's when it is back, otherwise the kernel run here now and the\n * late answer thrown away. The same value on every later call.\n */\n collect(frame: number): Out\n /** Resolves when the result exists (worker or main thread); for the `build` and `background` lanes. */\n readonly promise: Promise<Out>\n /** Where the collected result came from; `null` before `collect` or the promise settles. */\n readonly source: WorkerResultSource | null\n /** Drops a job not yet collected: it leaves the queue, or its answer is thrown away. */\n cancel(): void\n}\n\nexport interface ResidentHandle<Step, Result> {\n readonly id: string\n /** Steps the instance with `input` in `frame`; read the result with `collect(dueFrame)`. The input is the coordinator's from here on. */\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result>\n dispose(): void\n}\n\nexport interface WorkerKindStats {\n readonly id: string\n readonly lane: WorkerLane\n readonly submitted: number\n /** Answers that came back from a worker, on time or late. */\n readonly answered: number\n /** Results that came from a worker before they were needed. */\n readonly onTime: number\n /** Results the main thread computed (late worker, crash, no worker). */\n readonly fallback: number\n readonly dropped: number\n readonly cancelled: number\n readonly failed: number\n /** Milliseconds inside the worker, summed over `answered`. */\n readonly workerMs: number\n /** Milliseconds on the main thread, summed (fallbacks). */\n readonly mainMs: number\n /** Milliseconds waiting in the queue before a worker took the job, summed. */\n readonly queueMs: number\n}\n\nexport interface WorkerCoordinatorStats {\n readonly workers: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n readonly queued: number\n readonly running: number\n readonly respawned: number\n readonly kinds: readonly WorkerKindStats[]\n}\n\nexport interface WorkerCoordinator {\n /** A `sim` job submitted in `at.frame` (default: the last `tick`), due `latencyFrames` later. The input is the coordinator's from here on: do not change it. */\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out>\n /**\n * A job awaited instead of collected: a `build` or `background` job, or a `sim` job in the simulation thread (which may wait; with no worker\n * it runs on this thread). A promise, cancelled through `signal`.\n */\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out>\n /** An instance of a resident kind on one worker (or on the main thread when there is none). */\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result>\n /** The frame now; the runtime calls it at the start of each fixed step. Jobs are ordered by priority, then by the nearest due frame. */\n tick(frame: number): void\n /** Starts the workers and runs each kind's `warmup` in every worker; rejects when a worker does not know one of the kinds. */\n warm(kinds: readonly AnyWorkerKind[]): Promise<void>\n /** The schedule a kind runs with here (its own, with the game's overrides). */\n scheduleOf(kind: AnyWorkerKind): WorkerKindSchedule\n stats(): WorkerCoordinatorStats\n dispose(): void\n}\n\n/** The ids of the kit's kinds (`TaskKind.id` / `ResidentKind.id`), what `WORKER_KIND_DEFAULTS` is keyed by. */\nexport const WORKER_KIND_ID = {\n GROUND_TILES: 'destruction.ground-tiles',\n CROWD_PHYSICS: 'crowd.physics',\n PIECE_BOXES: 'destruction.piece-boxes',\n STATIC_COLLIDERS: 'destruction.static-colliders',\n SHAPES_GENERATE: 'shapes.generate',\n WORLD_REGION: 'world.region',\n} as const\n\n/** Default schedule of the kit's kinds; each kind carries its own copy, a game overrides any of them by id. */\nexport const WORKER_KIND_DEFAULTS = {\n [WORKER_KIND_ID.GROUND_TILES]: { lane: 'sim', priority: 300, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.CROWD_PHYSICS]: { lane: 'sim', priority: 250, latencyFrames: 1, late: 'sync' },\n [WORKER_KIND_ID.PIECE_BOXES]: { lane: 'sim', priority: 200, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: 'build', priority: 150, late: 'sync' },\n [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: 'build', priority: 100, late: 'sync' },\n [WORKER_KIND_ID.WORLD_REGION]: { lane: 'background', priority: 10, latencyFrames: 10, late: 'drop' },\n} as const satisfies Readonly<Record<string, WorkerKindSchedule>>\n\n/** The name of the error an awaited job with a transferred input (`transferAwaitedInput`) rejects with when its worker died holding it. */\nexport const WORKER_INPUT_LOST = 'WorkerTaskInputLost'\n\n/** Whether a rejection is that of a job whose transferred input was lost with its worker (`WORKER_INPUT_LOST`): the caller's own fallback makes it, nothing else is wrong. */\nexport const isWorkerInputLost = (error: unknown): boolean => error instanceof Error && error.name === WORKER_INPUT_LOST\n\n/*\n * The simulation thread (spec 009, T22): a game's whole fixed step in one worker that may wait. A package declares its simulation as a\n * `SimModule`; `@adatechnology/game-workers` runs it (`installSimThread`, `startSimThread`, `runSimInline`).\n */\n\n/** One running simulation, built in the simulation thread from the start message's `init`. */\nexport interface SimInstance {\n /**\n * One fixed step. It may return a promise: the loop waits for it (jobs handed to the coordinator are awaited, not raced against a frame),\n * so the result never depends on how fast the other workers were.\n */\n step(frame: number, dt: number, commands: readonly Float64Array[]): void | Promise<void>\n /** Writes the state the page draws into `out` (the snapshot's bytes, `snapshotBytes` long). */\n write(out: Uint8Array, frame: number): void\n dispose?(): void\n}\n\n/** What the simulation thread can build, by id (the worker's file registers every module the game starts). */\nexport interface SimModule<Init> {\n /** `package.thing`: `crowd.horde`. */\n readonly id: string\n create(init: Init): SimInstance | Promise<SimInstance>\n}\nexport type AnySimModule = SimModule<unknown>\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 BendHinge,\n Dent,\n DestructibleSpec,\n BlastCasing,\n BlastCharge,\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 PartAperture,\n PartShape,\n PartSpec,\n CarryHands,\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 GroundLoss,\n PartSettlement,\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 { chargeFireball, fireballDose, fuelFireball, ignitionDose } from './fireball'\nexport { TNT_JOULES, reflectedLoad, waveWork } from './blast-wave'\nexport type { WaveLoad, WaveWork, WaveWorkInput } from './blast-wave'\nexport type { Fireball } from './fireball'\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, sideOnOverpressure } 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, DrawnCollider, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport type { ToolCondition } from './tool-condition'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { FIT_REJECT_REASONS, SEAT_ROLES } from './body-measures'\nexport type { BodyMeasures, DoorOpening, FitRejectReason, FitResult, SeatRole, SeatSpace } from './body-measures'\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, ToolHand } from './hands'\nexport { FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectPose, 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, MUST_DRAIN_QUEUE_IDS, checkDeferredQueue, drainDetached } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach, HostTakenItem, HostTap } 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 { createFixedFootprintRainCover, createFootprintRainCover, createGridRainCover, createRainCover, rainCoverTopOf } from './rain-cover'\nexport type { FootprintRainCoverSource, GridRainCoverOptions, GridRainCoverSource, RainCover, RainCoverBounds, RainCoverFootprint, RainCoverHole, RainCoverRect, RainCoverSource } from './rain-cover'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject } from './footprint'\nexport { NAV_OBSTACLE_KIND } from './nav-obstacles'\nexport type { NavObstacle, NavObstacleBox, NavObstacleKind, NavObstacleSource } from './nav-obstacles'\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'\nexport { WORKER_INPUT_LOST, WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES, WORKER_LATE_RULES, isWorkerInputLost } from './workers'\nexport type { AnyResidentKind, AnySimModule, AnyTaskKind, AnyWorkerKind, ResidentHandle, ResidentInstance, ResidentKind, SimInstance, SimModule, TaskHandle, TaskKind, WorkerCoordinator, WorkerCoordinatorStats, WorkerKindSchedule, WorkerKindStats, WorkerLane, WorkerLateRule, WorkerResultSource } from './workers'\n","import { TNT_JOULES } from '@adatechnology/game-contracts'\nimport type { Hit } from '@adatechnology/game-contracts'\nimport { DEFAULT_BAR_DIAMETER, DEFAULT_BAR_YIELD_JOULES, DEFAULT_BAR_YIELD_PA, DEFAULT_PROFILE, TERRAIN_MATERIALS, TERRAIN_PROFILES } from './catalog'\nimport { createCrackStore, CRACK_REFERENCE_JOULES } from './cracks'\nimport { createDebrisStore } from './debris'\nimport { lossOf, SLIDE_LOSS_MIN_LOWERING, tallyLowered, voidUnder } from './ground-loss'\nimport type { HeightGrid, LossTally } from './ground-loss'\nimport { blendHeights, cellCoordinate as cellCoordinateOf } from './height-patch'\nimport type { HeightPatch } from './height-patch'\nimport { createMarkStore } from './marks'\nimport { createRandom } from './random'\nimport type { GroundExcavation, GroundLayout, Terrain, TerrainDig, TerrainDigResult, TerrainFill, TerrainBlow, TerrainBlowResult, TerrainBudget, TerrainChunk, TerrainColumn, TerrainDebris, TerrainDecal, TerrainLoad, TerrainMark, TerrainMaterial, TerrainOptions, TerrainProfile, TerrainRegion, TerrainSnapshot, TerrainStratum, TerrainStrike } from './types'\n\nexport const DEFAULT_TERRAIN_BUDGET: TerrainBudget = {\n markAreaSize: 2,\n maxMarksPerArea: 24,\n maxMarks: 800,\n maxDirtyChunksPerFrame: 6,\n maxDebris: 400,\n maxDebrisPerBlow: 36,\n maxSlideCellsPerFrame: 2500,\n maxBurningCells: 300,\n maxCracks: 120,\n maxDecals: 300,\n}\n\nconst GRAVITY = 9.81\n/** A bowl narrower than this many cells cannot be drawn by the height field: it stays a fine mark. */\nconst FINE_CELLS = 1.5\n/** A hole deeper than this many cells is no longer a mark on the surface. */\nconst FINE_DEPTH_CELLS = 0.4\nconst RIGID_WIDENING = 2.5\n/** Calibre (mm) a round's crater has the material's own shape at: a thinner round goes deeper and opens less for the same energy, a thicker one opens more. */\nconst REFERENCE_CALIBER = 7.62\n/** How far a calibre bends the crater's depth over its radius: (reference / calibre) to this power, kept within `CALIBER_ASPECT_RANGE`. */\nconst CALIBER_ASPECT_POWER = 0.5\nconst CALIBER_ASPECT_RANGE = [0.6, 1.6] as const\n/** A round's crater is at least this many calibres across. */\nconst CALIBERS_ACROSS = 2.5\n\n/** Depth-over-radius factor of a round's crater: 1 without a calibre or at the reference one. */\nconst caliberAspect = (caliber: number | undefined): number =>\n caliber && caliber > 0 ? Math.min(CALIBER_ASPECT_RANGE[1], Math.max(CALIBER_ASPECT_RANGE[0], (REFERENCE_CALIBER / caliber) ** CALIBER_ASPECT_POWER)) : 1\n/** The smallest crater radius (m) a round of `caliber` mm leaves. */\nconst caliberRadius = (caliber: number | undefined): number => (caliber && caliber > 0 ? (caliber / 1000) * CALIBERS_ACROSS / 2 : 0)\n/** Bars alone do not drop a slab that still has this share of its concrete to lose. */\nconst COLLAPSE_DEPTH_SHARE = 0.75\nconst COLLAPSE_SPREAD_BEND = 0.5\n/** Metres around a weight over which bare bars share it with the weights beside it. */\nconst BARS_SHARE_REACH = 0.6\nconst RIM_REACH = 1.45\n/** Under this temperature (°C) a flame does nothing to the ground. */\nconst FLAME_MINIMUM = 200\n/** How far over the ground a flame still touches it, beyond its radius. */\nconst FLAME_REACH = 0.6\n/** How far a blast above the ground still reaches it, as a share of its radius. */\nconst BLAST_HEIGHT_REACH = 0.35\n/**\n * Metres of ground the fireball of a 1 MJ blast blackens, growing with the cube root of the energy (a frag grenade, 200 kJ: about 0.7 m), and the share of\n * the material's darkest char (`TerrainFireResponse.maxScorch`) it leaves at the centre, fading to the edge: concrete only soots, turf chars.\n */\nconst BLAST_SOOT_REACH = 1.2\nconst BLAST_SOOT = 0.9\n/** Share of a blow's energy that throws the pieces. */\nconst THROW_SHARE = 0.02\n/** Side of a square of ground that burns as one, in metres. */\nconst FIRE_CELL = 0.5\nconst FIRE_SECONDS = 7\nconst FIRE_SPREAD_PER_SECOND = 0.35\nconst SLIDE_SHARE = 0.4\nconst SLIDE_EPSILON = 0.002\n/** Radius of a thrown piece per kind: a clod is a fist of soil, a chip is a thumb of concrete. */\nconst PIECE_RADIUS: Record<TerrainMaterial['debris'], number> = { clods: 0.045, chips: 0.022, shards: 0.028, splinters: 0.02, dust: 0.012, blocks: 0.08 }\n/** Metres per second the fastest piece of a blow leaves at: a blast throws, a dropped weight only kicks. */\nconst MAX_PIECE_SPEED: Record<TerrainBlow, number> = { explosive: 14, ballistic: 5, blunt: 2.5, slash: 1.5 }\n\n/** Cells the bed takes to go from the bank down to the full depth, so that a body wades in instead of falling. */\nconst BANK_CELLS = 6\nconst CRACK_MIN_RADIUS = 0.18\nconst RIPPLE_SECONDS = 1.6\n/** Water thinner than this at the bank neither splashes nor floats anything. */\nconst WATER_MINIMUM = 0.02\n\nconst clampIndex = (value: number, max: number): number => Math.max(0, Math.min(max, value))\nconst sparse = (array: Float32Array): [number, number][] => {\n const entries: [number, number][] = []\n array.forEach((value, index) => {\n if (value !== 0) entries.push([index, value])\n })\n return entries\n}\nconst fillSparse = (array: Float32Array, entries: readonly (readonly [number, number])[]): void => {\n array.fill(0)\n for (const [index, value] of entries) array[index] = value\n}\n\n/** Layer a depth falls in; past the end, the last one. */\nfunction stratumAtDepth(profile: TerrainProfile, depth: number): { index: number; stratum: TerrainStratum; top: number } {\n let top = 0\n for (let index = 0; index < profile.strata.length; index++) {\n const stratum = profile.strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return { index, stratum, top }\n top += stratum.thickness\n }\n const index = profile.strata.length - 1\n const stratum = profile.strata[index]!\n return { index, stratum, top: top - stratum.thickness }\n}\n\n/** Same stratum as `stratumAtDepth`, without allocating: per-read paths (state(), fire per vertex) must not create garbage. */\nfunction stratumMaterialAtDepth(profile: TerrainProfile, depth: number): string {\n const strata = profile.strata\n let top = 0\n for (let index = 0; index < strata.length; index++) {\n const stratum = strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return stratum.material\n top += stratum.thickness\n }\n return strata[strata.length - 1]!.material\n}\nconst totalThickness = (profile: TerrainProfile): number => profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n\nexport function createTerrain(options: TerrainOptions): Terrain {\n const [x0, z0, x1, z1] = options.bounds\n const cellSize = options.cellSize ?? 0.1\n const chunkCells = options.chunkCells ?? 32\n const columns = Math.max(1, Math.ceil((x1 - x0) / cellSize))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cellSize))\n const stride = columns + 1\n const vertexCount = stride * (rows + 1)\n const chunksX = Math.ceil(columns / chunkCells)\n const chunksZ = Math.ceil(rows / chunkCells)\n const budget: TerrainBudget = { ...DEFAULT_TERRAIN_BUDGET, ...options.budget }\n const gravity = options.gravity ?? GRAVITY\n const materials = new Map<string, TerrainMaterial>([...TERRAIN_MATERIALS, ...(options.materials ?? [])].map((material) => [material.id, material]))\n const profileMap = new Map<string, TerrainProfile>([...TERRAIN_PROFILES, ...(options.profiles ?? [])].map((profile) => [profile.id, profile]))\n const profileList = [...profileMap.values()]\n for (const profile of profileList) {\n for (const stratum of profile.strata) if (!materials.has(stratum.material)) throw new Error(`game-terrain: profile \"${profile.id}\" uses material \"${stratum.material}\", which has no ground behaviour`)\n }\n const indexOfProfile = new Map(profileList.map((profile, index) => [profile.id, index]))\n const maxDepthOf = profileList.map(totalThickness)\n\n // `surface` is the ground as the map has it; `base` is that less the water standing on it, so that everything that stands on the ground stands on the bed\n const surface = new Float32Array(vertexCount)\n if (options.baseHeight) {\n for (let row = 0; row <= rows; row++) for (let column = 0; column <= columns; column++) surface[row * stride + column] = options.baseHeight(x0 + column * cellSize, z0 + row * cellSize)\n }\n const base = Float32Array.from(surface)\n const hasWater = profileList.some((profile) => profile.water)\n const dug = new Float32Array(vertexCount)\n const loose = new Float32Array(vertexCount)\n const scorch = new Float32Array(vertexCount)\n const barBend = new Float32Array(vertexCount)\n const profileIndex = new Uint8Array(vertexCount)\n const touched = new Uint8Array(chunksX * chunksZ)\n const mixed = new Uint8Array(chunksX * chunksZ)\n const dirty = new Set<number>()\n const marks = createMarkStore(budget)\n const cracks = createCrackStore()\n const decalList: TerrainDecal[] = []\n let decalSerial = 0\n let decalsVersion = 0\n const unitDamage = new Map<string, number>()\n const debrisStore = createDebrisStore(() => budget.maxDebris)\n const sliding = new Set<number>()\n const burning = new Map<number, number>()\n const seed = options.seed ?? 1\n let random = createRandom(seed)\n let currentLayout: GroundLayout = options.layout ?? { surface: DEFAULT_PROFILE }\n\n const deformListeners = new Set<(region: TerrainRegion) => void>()\n const emitDeform = (x: number, z: number, radius: number): void => {\n for (const listener of deformListeners) listener({ x, z, radius })\n }\n const grid: HeightGrid = { x0, z0, cellSize, stride, columns, rows, dug }\n /** Sand that is still sliding: what it lowered so far, told once it comes to rest. */\n const slideTally: LossTally = new Map()\n const emitGroundLoss = (tally: LossTally, source: string, minLowering: number): void => {\n if (!options.onGroundLoss) return\n const loss = lossOf(grid, tally, { source, minLowering, shape: source === 'slab' ? 'flat' : 'bowl' })\n if (loss) options.onGroundLoss(loss)\n }\n /** Lowers a vertex to `depth` under the untouched surface, counting it in `tally`. */\n const dropVertex = (index: number, depth: number, tally: LossTally): void => {\n tallyLowered(tally, index, depth - dug[index]!)\n dug[index] = depth\n }\n\n const chunkOfVertex = (column: number, row: number): number => Math.min(chunksZ - 1, Math.floor(row / chunkCells)) * chunksX + Math.min(chunksX - 1, Math.floor(column / chunkCells))\n /** A vertex on a chunk's edge belongs to its neighbours as well. */\n function touchVertex(column: number, row: number): void {\n const chunk = chunkOfVertex(column, row)\n touched[chunk] = 1\n dirty.add(chunk)\n if (column % chunkCells === 0 && column > 0) markChunk(chunk - 1)\n if (row % chunkCells === 0 && row > 0) markChunk(chunk - chunksX)\n if (column % chunkCells === 0 && row % chunkCells === 0 && column > 0 && row > 0) markChunk(chunk - chunksX - 1)\n }\n function markChunk(chunk: number): void {\n touched[chunk] = 1\n dirty.add(chunk)\n }\n\n const profileId = (id: string): number => indexOfProfile.get(id) ?? indexOfProfile.get(DEFAULT_PROFILE) ?? 0\n\n function applyLayout(layout: GroundLayout): void {\n currentLayout = layout\n profileIndex.fill(profileId(layout.surface))\n for (const zone of layout.zones ?? []) {\n const index = profileId(zone.surface)\n const [zx0, zz0, zx1, zz1] = zone.rect\n const column0 = clampIndex(Math.round((zx0 - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((zx1 - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((zz0 - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((zz1 - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) profileIndex.fill(index, row * stride + column0, row * stride + column1 + 1)\n }\n if (hasWater) layBeds()\n for (let chunkZ = 0; chunkZ < chunksZ; chunkZ++) {\n for (let chunkX = 0; chunkX < chunksX; chunkX++) {\n const chunk = chunkZ * chunksX + chunkX\n const first = profileIndex[(chunkZ * chunkCells) * stride + chunkX * chunkCells]\n const firstDrop = surface[(chunkZ * chunkCells) * stride + chunkX * chunkCells]! - base[(chunkZ * chunkCells) * stride + chunkX * chunkCells]!\n let isMixed = 0\n const lastRow = Math.min(rows, (chunkZ + 1) * chunkCells)\n const lastColumn = Math.min(columns, (chunkX + 1) * chunkCells)\n for (let row = chunkZ * chunkCells; row <= lastRow && !isMixed; row++) {\n for (let column = chunkX * chunkCells; column <= lastColumn; column++) {\n if (profileIndex[row * stride + column] !== first || surface[row * stride + column]! - base[row * stride + column]! !== firstDrop) {\n isMixed = 1\n break\n }\n }\n }\n mixed[chunk] = isMixed\n dirty.add(chunk)\n }\n }\n for (const excavation of layout.excavations ?? []) excavate(excavation)\n }\n\n /**\n * Digs a construction's trench or pit: every vertex over the rectangle (the cell it starts in to the one it ends in, so the full depth spans the whole\n * rectangle and the wall slopes in the cell outside it) down to its depth, never less deep than it already was. A planned dig is no ground loss.\n */\n function excavate(excavation: GroundExcavation): void {\n const [ex0, ez0, ex1, ez1] = excavation.rect\n const column0 = clampIndex(Math.floor((ex0 - x0) / cellSize + 1e-6), columns)\n const column1 = clampIndex(Math.ceil((ex1 - x0) / cellSize - 1e-6), columns)\n const row0 = clampIndex(Math.floor((ez0 - z0) / cellSize + 1e-6), rows)\n const row1 = clampIndex(Math.ceil((ez1 - z0) / cellSize - 1e-6), rows)\n const alongX = (excavation.along ?? (ex1 - ex0 >= ez1 - ez0 ? 'x' : 'z')) === 'x'\n const from = alongX ? ex0 : ez0, length = Math.max(1e-6, alongX ? ex1 - ex0 : ez1 - ez0)\n const far = excavation.toDepth ?? excavation.depth\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const at = alongX ? x0 + column * cellSize : z0 + row * cellSize\n const t = Math.max(0, Math.min(1, (at - from) / length))\n const depth = excavation.depth + (far - excavation.depth) * t\n if (depth <= dug[index]!) continue\n dug[index] = depth\n touchVertex(column, row)\n }\n }\n }\n\n /** Lowers the ground under the water, in a bank from the edge of each pool. */\n function layBeds(): void {\n const steps = new Uint8Array(vertexCount)\n for (let index = 0; index < vertexCount; index++) steps[index] = profileList[profileIndex[index]!]!.water ? BANK_CELLS : 0\n for (let pass = 0; pass < BANK_CELLS; pass++) {\n for (let row = 0; row <= rows; row++) {\n for (let column = 0; column <= columns; column++) {\n const index = row * stride + column\n if (steps[index] === 0) continue\n const lowest = Math.min(column > 0 ? steps[index - 1]! : BANK_CELLS, column < columns ? steps[index + 1]! : BANK_CELLS, row > 0 ? steps[index - stride]! : BANK_CELLS, row < rows ? steps[index + stride]! : BANK_CELLS)\n steps[index] = Math.min(steps[index]!, lowest + 1)\n }\n }\n }\n for (let index = 0; index < vertexCount; index++) base[index] = surface[index]! - (profileList[profileIndex[index]!]!.water?.depth ?? 0) * (steps[index]! / BANK_CELLS)\n }\n\n const vertexHeight = (column: number, row: number): number => {\n const index = row * stride + column\n return base[index]! - dug[index]! + loose[index]!\n }\n const contains = (x: number, z: number): boolean => x >= x0 && x <= x1 && z >= z0 && z <= z1\n\n function addDecal(spec: Omit<TerrainDecal, 'id' | 'age'>): void {\n if (decalList.length >= budget.maxDecals) decalList.shift()\n decalList.push({ ...spec, id: ++decalSerial, age: 0 })\n decalsVersion++\n }\n function clearDecalsInside(x: number, z: number, radius: number): void {\n const before = decalList.length\n for (let i = before - 1; i >= 0; i--) {\n const decal = decalList[i]!\n if (decal.kind !== 'ripple' && decal.kind !== 'splat' && decal.kind !== 'crack' && Math.hypot(decal.x - x, decal.z - z) < radius) decalList.splice(i, 1)\n }\n if (decalList.length !== before) decalsVersion++\n }\n\n // `heightAt` and `heightGrid` are twins: both find a point's cell with `cellCoordinate` and blend its corners with `blendCell`, so the grid answers what the point does, to the bit\n /** Where `v` falls along an axis of `count` cells from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\n // the blend and the cell are `height-patch`'s, so a patch read anywhere (`heightPatchGrid`) answers what these do\n const cellCoordinate = (v: number, origin: number, count: number): number => cellCoordinateOf(v, origin, count, cellSize)\n const heightOfVertex = (index: number): number => base[index]! - dug[index]! + loose[index]!\n /** The ground in the cell whose first corner is vertex `index`, `tx` and `tz` across it. */\n const blendCell = (index: number, tx: number, tz: number): number =>\n blendHeights(blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx), blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx), tz)\n\n function heightAt(x: number, z: number): number {\n // beyond the terrain the ground is untouched: no blow can dig it and a piece thrown out lands on it\n if (!contains(x, z)) return options.baseHeight?.(x, z) ?? 0\n const fx = cellCoordinate(x, x0, columns)\n const fz = cellCoordinate(z, z0, rows)\n const column = fx | 0\n const row = fz | 0\n return blendCell(row * stride + column, fx - column, fz - row)\n }\n\n // the cell and the blend of each column and row a grid reads, kept between grids so a read costs no new arrays\n let gridColumns = new Int32Array(0)\n let gridBlendX = new Float64Array(0)\n let gridRows = new Int32Array(0)\n let gridBlendZ = new Float64Array(0)\n let gridNear = new Float64Array(0)\n let gridFar = new Float64Array(0)\n\n function heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n if (gridColumns.length < width) {\n gridColumns = new Int32Array(width)\n gridBlendX = new Float64Array(width)\n }\n if (gridRows.length < depth) {\n gridRows = new Int32Array(depth)\n gridBlendZ = new Float64Array(depth)\n }\n // each column and row as `heightAt` finds it (-1: past the terrain, where the host's `baseHeight` answers), so every height is the one `heightAt` gives, to the bit\n for (let i = 0; i < width; i++) {\n const x = xs[i]!\n const fx = cellCoordinate(x, x0, columns)\n gridColumns[i] = x >= x0 && x <= x1 ? fx | 0 : -1\n gridBlendX[i] = fx - (fx | 0)\n }\n for (let j = 0; j < depth; j++) {\n const z = zs[j]!\n const fz = cellCoordinate(z, z0, rows)\n gridRows[j] = z >= z0 && z <= z1 ? fz | 0 : -1\n gridBlendZ[j] = fz - (fz | 0)\n }\n // `blendCell` blends along x first, then along z: the two x blends of a column depend on its row only, so they are made once per row of cells and\n // each point is then the same last step `blendCell` takes, on the same numbers (the same bits); a lattice finer than the cells reads each row many times\n if (gridNear.length < width) {\n gridNear = new Float64Array(width)\n gridFar = new Float64Array(width)\n }\n let blended = -2\n for (let j = 0; j < depth; j++) {\n const row = gridRows[j]!\n const tz = gridBlendZ[j]!\n if (row < 0) {\n for (let i = 0; i < width; i++) out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const column = gridColumns[i]!\n if (column < 0) continue\n const index = row * stride + column\n const tx = gridBlendX[i]!\n gridNear[i] = blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx)\n gridFar[i] = blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx)\n }\n }\n for (let i = 0; i < width; i++) {\n if (gridColumns[i]! < 0) {\n out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n out[j * width + i] = blendHeights(gridNear[i]!, gridFar[i]!, tz)\n }\n }\n }\n\n function heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null {\n // the same test `heightGrid` makes of each point: a rectangle wholly inside reads no `baseHeight`\n if (!(minX >= x0 && maxX <= x1 && minZ >= z0 && maxZ <= z1)) return null\n const column0 = cellCoordinate(minX, x0, columns) | 0\n const row0 = cellCoordinate(minZ, z0, rows) | 0\n const width = (cellCoordinate(maxX, x0, columns) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, z0, rows) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) {\n const from = (row0 + j) * stride + column0\n for (let i = 0; i < width; i++) heights[j * width + i] = heightOfVertex(from + i)\n }\n return { cellSize, originX: x0, originZ: z0, columns, rows, column0, row0, width, depth, heights }\n }\n\n function heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { low: number; high: number } | null {\n if (!contains(minX, minZ) || !contains(maxX, maxZ)) return null\n const cellOf = (v: number, origin: number, count: number): number => Math.floor(Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize)))\n const column0 = cellOf(minX, x0, columns)\n const column1 = cellOf(maxX, x0, columns) + 1\n const row0 = cellOf(minZ, z0, rows)\n const row1 = cellOf(maxZ, z0, rows) + 1\n let low = Infinity\n let high = -Infinity\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const h = base[index]! - dug[index]! + loose[index]!\n if (h < low) low = h\n if (h > high) high = h\n }\n }\n return { low, high }\n }\n\n const vertexOf = (x: number, z: number): { column: number; row: number; index: number } => {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n return { column, row, index: row * stride + column }\n }\n\n function waterAt(x: number, z: number): { liquid: string; level: number; depth: number } | null {\n if (!hasWater || !contains(x, z)) return null\n const { index } = vertexOf(x, z)\n const water = profileList[profileIndex[index]!]!.water\n if (!water) return null\n const level = surface[index]!\n const depth = level - heightAt(x, z)\n return depth > WATER_MINIMUM ? { liquid: water.liquid, level, depth } : null\n }\n const exposedAt = (x: number, z: number): TerrainMaterial => {\n const { column, row } = vertexOf(x, z)\n return vertexMaterial(column, row)\n }\n const footAt = (x: number, z: number): number => {\n if (!contains(x, z)) return heightAt(x, z)\n return heightAt(x, z) - (exposedAt(x, z).footing?.sink ?? 0)\n }\n function walkFactorAt(x: number, z: number): number {\n if (!contains(x, z)) return 1\n const water = waterAt(x, z) ? profileList[profileIndex[vertexOf(x, z).index]!]!.water : null\n return Math.min(water?.drag ?? 1, exposedAt(x, z).footing?.drag ?? 1)\n }\n function ripple(x: number, z: number, radius: number): void {\n addDecal({ kind: 'ripple', x, z, radius, angle: 0, material: exposedAt(x, z).id })\n }\n function press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean {\n if (!contains(spec.x, spec.z)) return false\n if (waterAt(spec.x, spec.z)) {\n ripple(spec.x, spec.z, spec.radius * 2)\n return true\n }\n const material = exposedAt(spec.x, spec.z)\n if (!material.footing?.prints) return false\n addDecal({ kind: spec.kind ?? 'print', x: spec.x, z: spec.z, radius: spec.radius, angle: spec.angle ?? 0, material: material.id })\n return true\n }\n\n function vertexMaterial(column: number, row: number): TerrainMaterial {\n const index = row * stride + column\n return materials.get(stratumMaterialAtDepth(profileList[profileIndex[index]!]!, dug[index]!))!\n }\n\n /** `material(columnAt(x, z).material)` without building the column: the pieces ask it for every round contact. */\n function surfaceMaterialAt(x: number, z: number): TerrainMaterial {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n const index = row * stride + column\n const which = profileIndex[index]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n return materials.get(stratumMaterialAtDepth(profileList[which]!, depth))!\n }\n\n function rollingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rolling\n }\n\n function rollingDampingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rollingDamping\n }\n\n function columnAt(x: number, z: number): TerrainColumn {\n const { index } = vertexOf(x, z)\n const which = profileIndex[index]!\n const profile = profileList[which]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n const layer = stratumAtDepth(profile, depth)\n return { profile: profile.id, material: layer.stratum.material, stratum: layer.index, depth, remaining: maxDepthOf[which]! - depth, scorch: scorch[index]!, loose: loose[index]! }\n }\n\n /** Removes from a vertex: what is heaped first, then the column, never past its limit. Returns what came off. */\n function removeFromVertex(index: number, amount: number): number {\n const fromLoose = Math.min(loose[index]!, amount)\n loose[index] = loose[index]! - fromLoose\n const fromColumn = Math.min(maxDepthOf[profileIndex[index]!]! - dug[index]!, amount - fromLoose)\n if (fromColumn > 0) dug[index] = dug[index]! + fromColumn\n return fromLoose + Math.max(0, fromColumn)\n }\n /** Adds to a vertex: a soft floor fills what was dug, then heaps; on a rigid one the rubble just heaps. */\n function addToVertex(index: number, amount: number, fillsColumn: boolean): void {\n const filled = fillsColumn ? Math.min(dug[index]!, amount) : 0\n dug[index] = dug[index]! - filled\n loose[index] = loose[index]! + amount - filled\n }\n const isSoftExposed = (index: number): boolean => materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!.reposeDegrees !== undefined\n\n /** The vertices under a rectangle centred at (x, z): the cells a blade of that size bites. */\n function verticesUnder(x: number, z: number, size: readonly [number, number]): number[] {\n // as many vertices across as the size has cells (each vertex stands for its cell's area), centred on (x, z)\n const nu = Math.max(1, Math.round(size[0] / cellSize)), nv = Math.max(1, Math.round(size[1] / cellSize))\n const column0 = clampIndex(Math.round((x - x0) / cellSize - (nu - 1) / 2), columns), column1 = clampIndex(column0 + nu - 1, columns)\n const row0 = clampIndex(Math.round((z - z0) / cellSize - (nv - 1) / 2), rows), row1 = clampIndex(row0 + nv - 1, rows)\n const out: number[] = []\n for (let row = row0; row <= row1; row++) for (let column = column0; column <= column1; column++) out.push(row * stride + column)\n return out\n }\n const touchIndex = (index: number): void => touchVertex(index % stride, Math.floor(index / stride))\n /** The material a shovel meets at a vertex: the loose earth heaped there, else the stratum at the depth dug so far. */\n const materialAtVertex = (index: number): TerrainMaterial =>\n loose[index]! > 1e-4 ? materials.get('soil')! : materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!\n\n /** Lowers a vertex by up to `depth` through what a shovel digs (heaped earth first), stopping at what it does not. Returns how far it went. */\n function digVertex(index: number, depth: number): number {\n let left = depth\n while (left > 1e-6) {\n if (loose[index]! > 1e-6) {\n const take = Math.min(loose[index]!, left)\n loose[index] = loose[index]! - take\n left -= take\n continue\n }\n const profile = profileList[profileIndex[index]!]!\n const layer = stratumAtDepth(profile, dug[index]!)\n if (!materials.get(layer.stratum.material)?.dig || dug[index]! >= maxDepthOf[profileIndex[index]!]! - 1e-6) break\n const take = Math.min(left, layer.top + layer.stratum.thickness - dug[index]!)\n if (take <= 1e-6) break\n dug[index] = dug[index]! + take\n left -= take\n }\n return depth - left\n }\n\n /** Heaps `volume` of earth round (x, z), highest in the middle, and lets it settle to its slope. */\n function heapAt(x: number, z: number, volume: number): void {\n if (volume <= 0) return\n const radius = Math.max(cellSize * 2, Math.cbrt(volume) * 1.6)\n const indices = verticesUnder(x, z, [2 * radius, 2 * radius])\n const weight = (index: number): number => {\n const px = x0 + (index % stride) * cellSize, pz = z0 + Math.floor(index / stride) * cellSize\n const q = Math.hypot(px - x, pz - z) / radius\n return q < 1 ? 1 - q * q : 0\n }\n const total = indices.reduce((sum, i) => sum + weight(i), 0)\n if (total <= 0) return\n const cellArea = cellSize * cellSize\n for (const index of indices) {\n const w = weight(index)\n if (w <= 0) continue\n loose[index] = loose[index]! + (volume * w) / (total * cellArea)\n sliding.add(index)\n touchIndex(index)\n }\n emitDeform(x, z, radius)\n }\n\n function dig(spec: TerrainDig): TerrainDigResult {\n const size = spec.size ?? [0.3, 0.3], depth = spec.depth ?? 0.2\n const centre = vertexOf(spec.x, spec.z).index\n // under water a shovel brings nothing up\n if (profileList[profileIndex[centre]!]!.water) return { volume: 0, material: 'water', effort: 0, refused: 'water' }\n const met = materialAtVertex(centre)\n if (!met.dig) return { volume: 0, material: met.id, effort: 0, refused: met.id }\n if (met.dig.closes) return { volume: 0, material: met.id, effort: met.dig.effort, closes: true }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n let volume = 0\n for (const index of verticesUnder(spec.x, spec.z, size)) {\n const before = dug[index]!\n const went = digVertex(index, depth)\n if (went <= 0) continue\n tallyLowered(tally, index, dug[index]! - before)\n volume += went * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n marks.removeInside(spec.x, spec.z, Math.max(size[0], size[1]) / 2)\n emitDeform(spec.x, spec.z, Math.max(size[0], size[1]))\n // what the blade took from under a footing is ground lost under it: the structure feels it\n emitGroundLoss(tally, 'dig', 0)\n if (spec.dump) heapAt(spec.dump.x, spec.dump.z, volume)\n return { volume, material: met.id, effort: volume > 0 ? met.dig.effort : 0 }\n }\n\n function fill(spec: TerrainFill): number {\n const cellArea = cellSize * cellSize\n // the earth of the heap round `from`, nearest first, up to the volume asked\n let taken = 0\n const source = verticesUnder(spec.from.x, spec.from.z, [2 * spec.from.radius, 2 * spec.from.radius]).filter((i) => loose[i]! > 1e-6)\n for (const index of source) {\n if (taken >= spec.volume) break\n const take = Math.min(loose[index]!, (spec.volume - taken) / cellArea)\n loose[index] = loose[index]! - take\n taken += take * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (taken <= 0) return 0\n emitDeform(spec.from.x, spec.from.z, spec.from.radius)\n // laid in the hole: the deepest vertices of the bite first, so the hole closes level\n const target = verticesUnder(spec.x, spec.z, spec.size ?? [0.3, 0.3]).sort((a, b) => dug[b]! - dug[a]!)\n let left = taken\n for (const index of target) {\n if (left <= 1e-9) break\n const amount = Math.min(left / cellArea, Math.max(dug[index]!, (left / cellArea) / target.length))\n addToVertex(index, amount, true)\n left -= amount * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (left > 1e-9) heapAt(spec.x, spec.z, left)\n emitDeform(spec.x, spec.z, Math.max(...(spec.size ?? [0.3, 0.3])))\n return taken\n }\n\n /** Digs a lobed bowl into the height field, heaps the rim share around it. */\n function stampBowl(x: number, z: number, radius: number, depth: number, rimVolume: number, lossSource: string | null = 'crater'): void {\n const reach = radius * RIM_REACH\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const phaseA = random() * 6.283\n const phaseB = random() * 6.283\n const shapeOf = (px: number, pz: number): number => {\n const angle = Math.atan2(pz - z, px - x)\n return Math.hypot(px - x, pz - z) / (radius * (1 + 0.12 * Math.sin(angle * 5 + phaseA) + 0.06 * Math.sin(angle * 11 + phaseB)))\n }\n let rimWeight = 0\n if (rimVolume > 0) {\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n if (q >= 1 && q < RIM_REACH) rimWeight += Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)\n }\n }\n }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n const index = row * stride + column\n if (q < 1) {\n const before = dug[index]!\n removeFromVertex(index, depth * (1 - q * q) * (0.92 + random() * 0.16))\n tallyLowered(tally, index, dug[index]! - before)\n sliding.add(index)\n touchVertex(column, row)\n } else if (q < RIM_REACH && rimWeight > 0) {\n loose[index] = loose[index]! + (rimVolume * Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)) / (rimWeight * cellArea)\n sliding.add(index)\n touchVertex(column, row)\n }\n }\n }\n marks.removeInside(x, z, radius)\n clearDecalsInside(x, z, radius)\n emitDeform(x, z, reach)\n if (lossSource) emitGroundLoss(tally, lossSource, 0)\n }\n\n function throwPieces(spec: { x: number; y: number; z: number; volume: number; material: TerrainMaterial; energy: number; direction?: readonly number[]; quota: number; bowlRadius: number; blow: TerrainBlow }): void {\n const radius = PIECE_RADIUS[spec.material.debris]\n const pieceVolume = (4 / 3) * Math.PI * radius ** 3\n const count = Math.min(spec.quota, Math.max(1, Math.round(spec.volume / pieceVolume)))\n const mass = Math.max(1e-3, spec.volume * 1500)\n const launch = Math.min(MAX_PIECE_SPEED[spec.blow], Math.sqrt((2 * spec.energy * THROW_SHARE) / mass))\n for (let i = 0; i < count; i++) {\n const angle = random() * 6.283\n const out = spec.bowlRadius * Math.sqrt(random()) * 0.8\n const speed = launch * (0.5 + random() * 0.7)\n const spread = 0.35 + random() * 0.65\n const backX = spec.direction ? -(spec.direction[0] ?? 0) * 0.4 : 0\n const backZ = spec.direction ? -(spec.direction[2] ?? 0) * 0.4 : 0\n debrisStore.throwPiece({\n material: spec.material.id,\n kind: spec.material.debris,\n radius: radius * (0.6 + random() * 0.9),\n position: [spec.x + Math.cos(angle) * out, spec.y + 0.03, spec.z + Math.sin(angle) * out],\n velocity: [(Math.cos(angle) * spread + backX) * speed, (0.6 + random() * 0.7) * speed, (Math.sin(angle) * spread + backZ) * speed],\n spin: [(random() - 0.5) * 14, (random() - 0.5) * 14, (random() - 0.5) * 14],\n })\n }\n }\n\n function strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult {\n const { x, z } = spec\n const start = columnAt(x, z)\n const profile = profileMap.get(start.profile)!\n const waterHere = waterAt(x, z)\n const waterResult = waterHere ? { water: { liquid: waterHere.liquid, level: waterHere.level } } : {}\n if (waterHere) ripple(x, z, Math.min(1.5, 0.15 + Math.cbrt(spec.energy) / 40))\n const removed: { material: string; volume: number }[] = []\n const point: [number, number, number] = [x, heightAt(x, z), z]\n const startLayer = stratumAtDepth(profile, start.depth)\n if (start.loose <= 0 && materials.get(startLayer.stratum.material)!.units) return strikeUnits(blow, spec, startLayer, profile, point)\n const blowEnergy = spec.energy * (waterHere ? (profile.water?.blowShare[blow] ?? 1) : 1)\n let energy = blowEnergy\n let depth = start.depth\n let radius = 0\n let carved = 0\n let breached = false\n const firstMaterial = materials.get(start.material)!\n if (start.loose <= 0) {\n for (;;) {\n const layer = stratumAtDepth(profile, depth)\n const bottom = layer.top + layer.stratum.thickness\n const room = bottom - depth\n if (room <= 1e-6) break\n const material = materials.get(layer.stratum.material)!\n const response = material.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) break\n const bars = layer.stratum.reinforcement\n // a contact charge with enough for the whole thickness of a rigid layer breaks it right through: the shock spalls the far face and the layer goes in one piece, bars or not\n const breach = blow === 'explosive' ? material.breach : undefined\n const breachJoules = breach ? breach.joulesPerCubedThickness * layer.stratum.thickness ** 3 : Infinity\n if (breach && depth <= layer.top + 1e-6 && energy >= breachJoules) {\n const takenRadius = layer.stratum.thickness * breach.radiusOverThickness * Math.cbrt(energy / breachJoules)\n const takenVolume = (Math.PI * takenRadius * takenRadius * room) / 2\n energy -= breachJoules\n depth += room\n carved += room\n breached = true\n radius = Math.max(radius, takenRadius)\n removed.push({ material: material.id, volume: takenVolume })\n continue\n }\n const pastCover = bars !== undefined && depth - layer.top >= bars.cover - 1e-6\n const specificEnergy = response.specificEnergy * (pastCover ? bars.resistance : 1)\n const limit = bars && !pastCover ? Math.min(room, layer.top + bars.cover - depth) : room\n const aspect = response.aspect * caliberAspect(spec.caliber)\n const volume = energy / specificEnergy\n const wanted = Math.cbrt((2 * volume) / (Math.PI * aspect))\n const wantedDepth = wanted * aspect\n const takenDepth = Math.min(wantedDepth, limit)\n const takenRadius = takenDepth < wantedDepth ? takenDepth / aspect : wanted\n const takenVolume = (Math.PI * takenRadius * takenRadius * takenDepth) / 2\n energy -= takenVolume * specificEnergy\n depth += takenDepth\n carved += takenDepth\n radius = Math.max(radius, takenRadius, response.minRadius ?? 0, spec.contactRadius ?? 0, caliberRadius(spec.caliber))\n const last = removed[removed.length - 1]\n if (last?.material === material.id) (last as { volume: number }).volume += takenVolume\n else removed.push({ material: material.id, volume: takenVolume })\n if (energy <= 1e-6 || takenDepth >= wantedDepth - 1e-9) break\n }\n } else {\n // a loose heap has no strength: it takes the blow as soft ground before the column does\n const response = firstMaterial.hits[blow]\n if (response && energy >= (response.thresholdJoules ?? 0)) {\n const volume = energy / response.specificEnergy\n radius = Math.cbrt((2 * volume) / (Math.PI * response.aspect))\n carved = radius * response.aspect\n removed.push({ material: firstMaterial.id, volume })\n }\n }\n let collapsed = loadBars(blow, spec.energy, x, z, profile)\n const crack = crackAround(blow, spec.energy, x, z, start.loose > 0 ? undefined : firstMaterial)\n const extra = { ...(crack ? { crack } : {}), ...(breached ? { breached } : {}), ...waterResult }\n // a weight that lands flat (its contact as wide as the dent) presses the ground down: it packs the soil under it, it does not take it away\n const pressed = spec.contactRadius !== undefined && spec.contactRadius >= radius\n if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true, ...extra }\n\n // a rigid floor cannot go down any more where it is already deep: the next blow breaks the edge of the hole, so a hole in a slab opens as it deepens\n if (firstMaterial.reposeDegrees === undefined && start.loose <= 0) radius *= 1 + RIGID_WIDENING * (start.depth / maxDepthOfProfile(profile))\n\n const volumeTotal = removed.reduce((sum, entry) => sum + entry.volume, 0)\n const fine = radius < cellSize * FINE_CELLS\n if (fine) depositMark({ x, z, radius, depth: carved, blow, profile, cap: maxDepthOfProfile(profile) })\n else {\n const rimShare = materials.get(removed[0]!.material)!.rimShare ?? 0\n stampBowl(x, z, radius, carved, volumeTotal * rimShare, pressed ? null : 'crater')\n }\n if (firstMaterial.cracks) addDecal({ kind: 'crack', x, z, radius: Math.max(CRACK_MIN_RADIUS, radius * firstMaterial.cracks), angle: random() * 6.283, material: firstMaterial.id })\n // under water what comes off stays a cloud at the bottom, unless a blast opens the water\n let quota = waterHere && blow !== 'explosive' ? 0 : budget.maxDebrisPerBlow\n for (const entry of removed) {\n const material = materials.get(entry.material)!\n const thrown = entry.volume * (1 - (fine ? 0 : (material.rimShare ?? 0)))\n if (thrown <= 0 || quota <= 0) continue\n const share = Math.max(1, Math.round((quota * entry.volume) / volumeTotal))\n throwPieces({ x, y: point[1], z, volume: thrown, material, energy: spec.energy * (entry.volume / volumeTotal), direction: spec.direction, quota: share, bowlRadius: radius, blow })\n quota -= share\n }\n // a breach bares the bars under the same blow that broke the concrete, so they take that blow's load at once and, over a void, may let the floor go\n if (breached) collapsed = loadBars(blow, spec.energy, x, z, profile) || collapsed\n const after = columnAt(x, z)\n return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine, ...extra }\n }\n\n /** A rigid surface cracks around a hard enough blow, the lines running out with the cube root of the energy; a soft one (soil, sand, turf) only gives way. */\n function crackAround(blow: TerrainBlow, energy: number, x: number, z: number, material: TerrainMaterial | undefined): ReturnType<typeof cracks.add> | undefined {\n const response = material?.crack\n if (!material || !response || energy < response.thresholdJoules) return undefined\n // a cut does not crack a slab; a bullet, a hammer and a blast do\n if (blow === 'slash') return undefined\n const scale = Math.cbrt(energy / CRACK_REFERENCE_JOULES)\n return cracks.add({ x, z, reach: response.reach * scale, width: response.width * scale, material: material.id, seed: Math.floor(random() * 2 ** 31) }, budget.maxCracks)\n }\n\n /**\n * A floor of separate pieces: a blow does not dig them, it shakes them. Each takes the energy that reaches it, added blow by blow, and past its limit it comes off the bed whole and is thrown.\n * Under the limit the blow only chips it.\n */\n function strikeUnits(blow: TerrainBlow, spec: TerrainStrike, layer: { stratum: TerrainStratum; top: number }, profile: TerrainProfile, point: [number, number, number]): TerrainBlowResult {\n const { x, z, energy } = spec\n const material = materials.get(layer.stratum.material)!\n const units = material.units!\n const response = material.hits[blow]\n const bottom = layer.top + layer.stratum.thickness\n const miss: TerrainBlowResult = { point, radius: 0, depth: 0, totalDepth: layer.top, removed: [], exposed: material.id, atLimit: false, rebarExposed: false, collapsed: false, fine: true }\n if (!response || energy < (response.thresholdJoules ?? 0)) return miss\n const reach = Math.max(spec.contactRadius ?? 0, response.minRadius ?? 0, caliberRadius(spec.caliber), Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect * caliberAspect(spec.caliber))))\n const rowFirst = Math.floor((z - reach) / units.width)\n const rowLast = Math.floor((z + reach) / units.width)\n let loosened = 0\n for (let row = rowFirst; row <= rowLast; row++) {\n const shift = Math.abs(row % 2) * cellSize\n const unitFirst = Math.floor((x - reach - shift) / units.length)\n const unitLast = Math.floor((x + reach - shift) / units.length)\n for (let unit = unitFirst; unit <= unitLast; unit++) {\n const minX = unit * units.length + shift\n const minZ = row * units.width\n const near = Math.hypot(Math.max(minX - x, 0, x - minX - units.length), Math.max(minZ - z, 0, z - minZ - units.width))\n if (near > reach) continue\n const key = `${unit}:${row}`\n const taken = (unitDamage.get(key) ?? 0) + energy * (1 - (near / (reach + 1e-6)) ** 2)\n unitDamage.set(key, taken)\n if (taken >= units.looseJoules && liftUnit(minX, minZ, units, bottom, material, profile)) {\n loosened++\n const speed = Math.min(MAX_PIECE_SPEED[blow], Math.sqrt((2 * energy * THROW_SHARE) / Math.max(1, loosened * 15)))\n const angle = random() * 6.283\n debrisStore.throwPiece({ material: material.id, kind: 'blocks', radius: units.length / 2, position: [minX + units.length / 2, point[1] + 0.05, minZ + units.width / 2], velocity: [Math.cos(angle) * speed * 0.6, speed * (0.5 + random() * 0.5), Math.sin(angle) * speed * 0.6], spin: [(random() - 0.5) * 8, (random() - 0.5) * 8, (random() - 0.5) * 8] })\n }\n }\n }\n if (loosened === 0) {\n // not enough to lift a piece: a chip off its face and a hairline\n addDecal({ kind: 'crack', x, z, radius: Math.max(0.05, reach * 2), angle: random() * 6.283, material: material.id })\n throwPieces({ x, y: point[1], z, volume: 1e-5, material: { ...material, debris: 'chips' }, energy, ...(spec.direction ? { direction: spec.direction } : {}), quota: 3, bowlRadius: 0.02, blow })\n return { ...miss, radius: Math.max(0.02, Math.min(reach, 0.06)) }\n }\n emitDeform(x, z, reach + units.length)\n clearDecalsInside(x, z, reach)\n const volume = loosened * units.length * units.width * layer.stratum.thickness\n const after = columnAt(x, z)\n return { point, radius: reach, depth: layer.stratum.thickness, totalDepth: after.depth, removed: [{ material: material.id, volume }], exposed: after.material, atLimit: false, rebarExposed: false, collapsed: false, fine: false }\n }\n\n /** Takes one piece off its bed. False when it had already gone. */\n function liftUnit(minX: number, minZ: number, units: { length: number; width: number }, bottom: number, material: TerrainMaterial, profile: TerrainProfile): boolean {\n const column0 = clampIndex(Math.round((minX - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((minX + units.length - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((minZ - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((minZ + units.width - z0) / cellSize), rows)\n let lifted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (profileList[profileIndex[index]!]!.id !== profile.id || dug[index]! >= bottom) continue\n if (materials.get(stratumAtDepth(profile, dug[index]!).stratum.material) !== material) continue\n dug[index] = bottom\n lifted = true\n touchVertex(column, row)\n }\n }\n return lifted\n }\n\n /**\n * A blow loads the bars that are bare around it: they bend, and past their limit they give way. The bowl a blow would open tells how far it reaches. Where the slab has nothing under it, the floor goes with them.\n */\n function loadBars(blow: TerrainBlow, energy: number, x: number, z: number, profile: TerrainProfile): boolean {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return false\n const response = materials.get(bars.material)!.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) return false\n const yieldJoules = bars.reinforcement.yieldJoules ?? DEFAULT_BAR_YIELD_JOULES\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n const reach = Math.max(cellSize * FINE_CELLS, Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect)) * (1 + RIGID_WIDENING))\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const limit = maxDepthOfProfile(profile)\n let collapsed = false\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (dug[index]! < cover) continue\n const q = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z) / reach\n if (q >= 1) continue\n barBend[index] = barBend[index]! + (energy / yieldJoules) * (1 - q * q)\n touchVertex(column, row)\n if (barBend[index]! >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n collapsed = true\n }\n }\n }\n if (collapsed) giveWay({ x, z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return collapsed\n }\n\n /** What gave way takes down what was already bending around it, and what stood there must look again. */\n function giveWay(spec: { x: number; z: number; reach: number; profile: TerrainProfile; tally: LossTally }): void {\n const { x, z, reach, profile, tally } = spec\n emitDeform(x, z, reach)\n if (profile.drop === undefined) return\n const limit = maxDepthOfProfile(profile)\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (barBend[index]! >= COLLAPSE_SPREAD_BEND && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n touchVertex(column, row)\n }\n }\n }\n }\n\n /** Depth under the surface of the bars of a profile, and the stratum that holds them. */\n function barsOf(profile: TerrainProfile): { stratum: TerrainStratum; cover: number } | null {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return null\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n return { stratum: bars, cover }\n }\n\n /**\n * Weights on bare bars. Each bar over the hole works as a beam that yields at its plastic moment fy·d³/6; the bars of a mesh crossing a hole of any size hold 8·Mp/spacing\n * on a spot, so the bend is the weight over that. Weights over the same bars add up (a stack, things side by side). The share of a footprint on intact concrete is carried\n * by the concrete. Bars do not spring back: the bend only grows.\n */\n function bearAll(loads: readonly TerrainLoad[]): boolean {\n const bends = new Map<number, number>()\n const touched: { load: TerrainLoad; reach: number; profile: TerrainProfile }[] = []\n for (const load of loads) {\n const spread = spreadLoad(load, bends)\n if (spread) touched.push({ load, ...spread })\n }\n let opened = false\n const tally: LossTally = new Map()\n for (const [index, bend] of bends) {\n if (barBend[index]! >= bend) continue\n barBend[index] = bend\n const column = index % stride\n const row = (index - column) / stride\n touchVertex(column, row)\n const profile = profileList[profileIndex[index]!]!\n const limit = maxDepthOfProfile(profile)\n if (bend >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n opened = true\n }\n }\n if (opened) for (const { load, reach, profile } of touched) giveWay({ x: load.x, z: load.z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return opened\n }\n\n /** Adds the bend one weight gives the bare bars under it to `bends`; null where it stands on no bare bars. */\n function spreadLoad(load: TerrainLoad, bends: Map<number, number>): { reach: number; profile: TerrainProfile } | null {\n if (!contains(load.x, load.z) || load.newtons <= 0) return null\n const profile = profileList[profileIndex[vertexOf(load.x, load.z).index]!]!\n const bars = barsOf(profile)\n if (!bars) return null\n const reinforcement = bars.stratum.reinforcement!\n const moment = ((reinforcement.yieldPa ?? DEFAULT_BAR_YIELD_PA) * (reinforcement.diameter ?? DEFAULT_BAR_DIAMETER) ** 3) / 6\n const holds = (8 * moment) / reinforcement.spacing\n // the footprint of a box reaches its corners: a disc of its half side would leave them standing on the slab\n const footprint = load.radius * Math.SQRT2 + cellSize\n // and the bars of a hole carry together what stands on it: weights side by side add up as a stack does\n const reach = Math.max(footprint, BARS_SHARE_REACH)\n const column0 = clampIndex(Math.floor((load.x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((load.x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((load.z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((load.z + reach - z0) / cellSize), rows)\n const bare: number[] = []\n let under = 0\n let onBars = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - load.x, z0 + row * cellSize - load.z)\n if (distance >= reach) continue\n const index = row * stride + column\n const isBare = dug[index]! >= bars.cover\n if (isBare) bare.push(index)\n if (distance >= footprint) continue\n under++\n if (isBare) onBars++\n }\n }\n if (onBars === 0) return null\n const bend = (load.newtons * (onBars / under)) / holds\n for (const index of bare) bends.set(index, (bends.get(index) ?? 0) + bend)\n return { reach, profile }\n }\n\n const maxDepthOfProfile = (profile: TerrainProfile): number => maxDepthOf[indexOfProfile.get(profile.id)!]!\n function rebarShowing(profile: TerrainProfile, depth: number): boolean {\n const layer = stratumAtDepth(profile, depth)\n return layer.stratum.reinforcement !== undefined && depth - layer.top >= layer.stratum.reinforcement.cover - 1e-6\n }\n\n function depositMark(spec: { x: number; z: number; radius: number; depth: number; blow: TerrainBlow; profile: TerrainProfile; cap: number }): void {\n const { x, z, radius, depth, blow, profile, cap } = spec\n const dugHere = dug[vertexOf(x, z).index]!\n const existing = marks.near(x, z, radius)\n let mark: TerrainMark\n if (existing) {\n existing.radius = Math.hypot(existing.radius, radius)\n existing.depth = Math.min(cap - dugHere, existing.depth + depth)\n existing.count++\n existing.blow = blow\n mark = existing\n } else {\n mark = marks.add({ x, z, radius, depth: Math.min(cap - dugHere, depth), blow, material: '' })\n }\n mark.material = stratumAtDepth(profile, dugHere + mark.depth - 1e-6).stratum.material\n if (mark.radius >= cellSize * FINE_CELLS || mark.depth >= cellSize * FINE_DEPTH_CELLS) {\n const bowlRadius = Math.max(mark.radius, cellSize * FINE_CELLS)\n const bowlDepth = mark.depth\n marks.remove(mark)\n stampBowl(mark.x, mark.z, bowlRadius, bowlDepth, 0)\n }\n }\n\n function burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void {\n if (spec.temperature < FLAME_MINIMUM) return\n const column0 = clampIndex(Math.floor((spec.x - spec.radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((spec.x + spec.radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((spec.z - spec.radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((spec.z + spec.radius - z0) / cellSize), rows)\n let melted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(x0 + column * cellSize - spec.x, z0 + row * cellSize - spec.z) > spec.radius) continue\n // water does not catch: only what floats on it could burn\n if (hasWater && base[row * stride + column]! < surface[row * stride + column]!) continue\n melted = burnVertex(column, row, spec.seconds) || melted\n }\n }\n if (melted) emitDeform(spec.x, spec.z, spec.radius)\n }\n\n /** The soot of a blast's fireball within `radius` of (x, z): darkest at the centre, by what each material takes (`fire.maxScorch`); it lights nothing. */\n function soot(x: number, z: number, radius: number): void {\n if (radius <= 0) return\n const column0 = clampIndex(Math.floor((x - radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + radius - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z)\n const response = distance < radius ? vertexMaterial(column, row).fire : undefined\n if (!response) continue\n const index = row * stride + column\n const before = scorch[index]!\n scorch[index] = Math.max(before, response.maxScorch * BLAST_SOOT * Math.sqrt(1 - distance / radius))\n if (scorch[index] !== before) touchVertex(column, row)\n }\n }\n }\n\n /** True when the flame took ground away, so that what stood there must look again. */\n function burnVertex(column: number, row: number, seconds: number): boolean {\n const index = row * stride + column\n const material = vertexMaterial(column, row)\n const response = material.fire\n if (!response) return false\n const before = scorch[index]!\n scorch[index] = Math.max(before, Math.min(response.maxScorch, before + response.scorchPerSecond * seconds))\n if (response.burnsAway) removeFromVertex(index, response.burnsAway * seconds)\n if (scorch[index] !== before || response.burnsAway) touchVertex(column, row)\n if (response.flammable) ignite(x0 + column * cellSize, z0 + row * cellSize)\n return (response.burnsAway ?? 0) > 0\n }\n\n const fireKey = (x: number, z: number): number => Math.floor((z - z0) / FIRE_CELL) * 65536 + Math.floor((x - x0) / FIRE_CELL)\n function ignite(x: number, z: number): void {\n const key = fireKey(x, z)\n if (burning.has(key) || burning.size >= budget.maxBurningCells) return\n const index = vertexOf(x, z).index\n if (scorch[index]! >= 1) return\n burning.set(key, FIRE_SECONDS)\n }\n\n function updateFire(dt: number): void {\n for (const [key, remaining] of [...burning]) {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n const x = x0 + (cellColumn + 0.5) * FIRE_CELL\n const z = z0 + (cellRow + 0.5) * FIRE_CELL\n burn({ x, z, radius: FIRE_CELL * 0.75, temperature: 600, seconds: dt })\n if (random() < FIRE_SPREAD_PER_SECOND * dt) {\n const angle = Math.floor(random() * 4) * (Math.PI / 2)\n const nextX = x + Math.cos(angle) * FIRE_CELL\n const nextZ = z + Math.sin(angle) * FIRE_CELL\n if (contains(nextX, nextZ)) {\n const { column, row, index } = vertexOf(nextX, nextZ)\n if (vertexMaterial(column, row).fire?.flammable && scorch[index]! < 1) ignite(nextX, nextZ)\n }\n }\n if (remaining - dt <= 0) burning.delete(key)\n else burning.set(key, remaining - dt)\n }\n }\n\n function updateSlides(): void {\n if (sliding.size === 0) return\n let budgetLeft = budget.maxSlideCellsPerFrame\n let minX = Infinity\n let minZ = Infinity\n let maxX = -Infinity\n let maxZ = -Infinity\n for (const index of sliding) {\n if (budgetLeft-- <= 0) break\n sliding.delete(index)\n const column = index % stride\n const row = (index - column) / stride\n if (!isSoftExposed(index)) continue\n const material = vertexMaterial(column, row)\n const slope = Math.tan(((material.reposeDegrees ?? 90) * Math.PI) / 180) * cellSize\n const height = vertexHeight(column, row)\n const neighbours: [number, number][] = [[column - 1, row], [column + 1, row], [column, row - 1], [column, row + 1]]\n for (const [nextColumn, nextRow] of neighbours) {\n if (nextColumn < 0 || nextRow < 0 || nextColumn > columns || nextRow > rows) continue\n const excess = height - vertexHeight(nextColumn, nextRow) - slope\n if (excess <= SLIDE_EPSILON) continue\n const before = dug[index]!\n const moved = removeFromVertex(index, excess * SLIDE_SHARE)\n if (moved <= 0) continue\n tallyLowered(slideTally, index, dug[index]! - before)\n const next = nextRow * stride + nextColumn\n const nextBefore = dug[next]!\n addToVertex(next, moved, isSoftExposed(next))\n tallyLowered(slideTally, next, dug[next]! - nextBefore)\n sliding.add(index)\n sliding.add(next)\n touchVertex(column, row)\n touchVertex(nextColumn, nextRow)\n const px = x0 + column * cellSize\n const pz = z0 + row * cellSize\n minX = Math.min(minX, px)\n maxX = Math.max(maxX, px)\n minZ = Math.min(minZ, pz)\n maxZ = Math.max(maxZ, pz)\n }\n }\n if (minX <= maxX) emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n if (sliding.size === 0 && slideTally.size > 0) {\n emitGroundLoss(slideTally, 'slide', SLIDE_LOSS_MIN_LOWERING)\n slideTally.clear()\n }\n }\n\n /** The box (in x, z) round the vertices that settled rubble raised in this update, told once as one deform. */\n const settledArea = { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity }\n function emitSettledArea(): void {\n if (settledArea.minX > settledArea.maxX) return\n const { minX, minZ, maxX, maxZ } = settledArea\n settledArea.minX = settledArea.minZ = Infinity\n settledArea.maxX = settledArea.maxZ = -Infinity\n emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n }\n\n /** A piece of soft ground joins the height where it stops, so that what is thrown out piles up and can be walked on. */\n function settle(piece: TerrainDebris): boolean {\n const material = materials.get(piece.material)\n if (!material || material.reposeDegrees === undefined || material.scatters) return false\n if (material.splats && contains(piece.position[0], piece.position[2]) && !waterAt(piece.position[0], piece.position[2])) addDecal({ kind: 'splat', x: piece.position[0], z: piece.position[2], radius: piece.radius * 2.6, angle: piece.id * 2.399, material: material.id })\n if (!contains(piece.position[0], piece.position[2])) return true\n const { index, column, row } = vertexOf(piece.position[0], piece.position[2])\n addToVertex(index, ((4 / 3) * Math.PI * piece.radius ** 3) / (cellSize * cellSize), false)\n sliding.add(index)\n touchVertex(column, row)\n const px = x0 + column * cellSize, pz = z0 + row * cellSize\n settledArea.minX = Math.min(settledArea.minX, px)\n settledArea.maxX = Math.max(settledArea.maxX, px)\n settledArea.minZ = Math.min(settledArea.minZ, pz)\n settledArea.maxZ = Math.max(settledArea.maxZ, pz)\n return true\n }\n\n function applyHit(hit: Hit): TerrainBlowResult | null {\n const [x, y, z] = hit.point\n switch (hit.type) {\n case 'ballistic':\n case 'blunt':\n case 'slash': {\n if (!hit.energy) return null\n const contactRadius = hit.type === 'blunt' ? hit.radius : undefined\n const caliber = hit.type === 'ballistic' ? hit.caliber : undefined\n return strike(hit.type, { x, z, energy: hit.energy, ...(hit.direction ? { direction: hit.direction } : {}), ...(contactRadius !== undefined ? { contactRadius } : {}), ...(caliber !== undefined ? { caliber } : {}) })\n }\n case 'explosive': {\n if (!hit.energy) return null\n const above = Math.max(0, y - heightAt(x, z))\n const reach = (hit.radius ?? 1) * BLAST_HEIGHT_REACH\n if (above >= reach) return null\n const share = (1 - above / reach) ** 2\n // the ground's specific energies are of real joules (a kilogram of TNT is 4.184 MJ): a charge the blast was told says them; its `energy` is the arsenal's damage scale\n soot(x, z, BLAST_SOOT_REACH * Math.cbrt((hit.energy * share) / 1e6))\n return strike('explosive', { x, z, energy: (hit.hasCharge && hit.tnt !== undefined && hit.tnt > 0 ? hit.tnt * TNT_JOULES : hit.energy) * share })\n }\n case 'fire':\n case 'heat':\n if (y - heightAt(x, z) > (hit.radius ?? 0.2) + FLAME_REACH) return null\n burn({ x, z, radius: hit.radius ?? 0.2, temperature: hit.temperature ?? 0, seconds: hit.duration ?? 0.016 })\n return null\n default:\n return null\n }\n }\n\n function raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null {\n const [ox = 0, oy = 0, oz = 0] = origin\n const [dx = 0, dy = 0, dz = 0] = direction\n const step = cellSize * 0.75\n let previous = 0\n for (let t = 0; t <= maxDistance; t += step) {\n const x = ox + dx * t\n const z = oz + dz * t\n if (contains(x, z) && oy + dy * t <= heightAt(x, z)) {\n let low = previous\n let high = t\n for (let i = 0; i < 6; i++) {\n const middle = (low + high) / 2\n if (oy + dy * middle <= heightAt(ox + dx * middle, oz + dz * middle)) high = middle\n else low = middle\n }\n const px = ox + dx * high\n const pz = oz + dz * high\n const gx = heightAt(px + cellSize, pz) - heightAt(px - cellSize, pz)\n const gz = heightAt(px, pz + cellSize) - heightAt(px, pz - cellSize)\n const length = Math.hypot(gx, 2 * cellSize, gz)\n return { point: [px, oy + dy * high, pz], distance: high, normal: [-gx / length, (2 * cellSize) / length, -gz / length] }\n }\n previous = t\n }\n return null\n }\n\n function chunk(index: number): TerrainChunk {\n const chunkZ = Math.floor(index / chunksX)\n const chunkX = index - chunkZ * chunksX\n return { index, column: chunkX * chunkCells, row: chunkZ * chunkCells, cells: chunkCells, pristine: !touched[index] && !mixed[index] && !options.baseHeight }\n }\n\n function reset(): void {\n dug.fill(0)\n loose.fill(0)\n scorch.fill(0)\n barBend.fill(0)\n touched.fill(0)\n marks.clear()\n cracks.clear()\n decalList.length = 0\n decalsVersion++\n unitDamage.clear()\n debrisStore.clear()\n sliding.clear()\n slideTally.clear()\n burning.clear()\n // the craters and clods draw from here: a reset ground digs the same as a new one\n random = createRandom(seed)\n applyLayout(currentLayout)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n }\n\n applyLayout(currentLayout)\n\n return {\n bounds: options.bounds,\n cellSize,\n columns,\n rows,\n stride,\n chunkCells,\n chunksX,\n chunksZ,\n budget,\n dug,\n loose,\n scorch,\n barBend,\n profileIndex,\n profileList,\n material: (id) => {\n const material = materials.get(id)\n if (!material) throw new Error(`game-terrain: unknown material \"${id}\"`)\n return material\n },\n layout: () => currentLayout,\n setLayout(layout) {\n currentLayout = layout\n reset()\n },\n heightAt,\n heightGrid,\n heightPatch,\n heightRange,\n footAt,\n walkFactorAt,\n waterAt,\n press,\n ripple,\n decals: () => decalList,\n get decalsVersion() {\n return decalsVersion\n },\n vertexHeight,\n vertexMaterial,\n columnAt,\n rollingAt,\n rollingDampingAt,\n contains,\n raycast,\n strike,\n burn,\n open(excavation) {\n excavate(excavation)\n const [ex0, ez0, ex1, ez1] = excavation.rect\n emitDeform((ex0 + ex1) / 2, (ez0 + ez1) / 2, Math.hypot(ex1 - ex0, ez1 - ez0) / 2 + cellSize * 2)\n },\n dig,\n fill,\n applyHit,\n bear: bearAll,\n voidUnder: (x, z, radius) => voidUnder(grid, { x, z, radius }),\n onDeform(listener) {\n deformListeners.add(listener)\n return () => deformListeners.delete(listener)\n },\n update(dt) {\n debrisStore.update(dt, { heightAt, gravity, settle })\n emitSettledArea()\n updateSlides()\n updateFire(dt)\n for (let i = decalList.length - 1; i >= 0; i--) {\n const decal = decalList[i]!\n decal.age += dt\n if (decal.kind === 'ripple' && decal.age > RIPPLE_SECONDS) {\n decalList.splice(i, 1)\n decalsVersion++\n }\n }\n },\n get dirtyChunkCount() {\n return dirty.size\n },\n drainDirtyChunks(max = budget.maxDirtyChunksPerFrame) {\n const taken: TerrainChunk[] = []\n for (const index of dirty) {\n if (taken.length >= max) break\n dirty.delete(index)\n taken.push(chunk(index))\n }\n return taken\n },\n chunk,\n marks: () => marks.list,\n cracks: () => cracks.list,\n get cracksVersion() {\n return cracks.version\n },\n debris: () => debrisStore.list,\n burningPoints: () => [...burning.keys()].map((key) => {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n return [x0 + (cellColumn + 0.5) * FIRE_CELL, z0 + (cellRow + 0.5) * FIRE_CELL] as const\n }),\n get marksVersion() {\n return marks.version\n },\n stats: () => ({ marks: marks.list.length, debris: debrisStore.list.length, debrisMoving: debrisStore.list.filter((piece) => !piece.atRest).length, dirtyChunks: dirty.size, burning: burning.size }),\n reset,\n serialize(): TerrainSnapshot {\n return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })), cracks: cracks.list.map((crack) => ({ ...crack })), decals: decalList.filter((decal) => decal.kind !== 'ripple').map((decal) => ({ ...decal })) }\n },\n load(snapshot) {\n currentLayout = snapshot.layout\n reset()\n fillSparse(dug, snapshot.dug)\n fillSparse(loose, snapshot.loose)\n fillSparse(scorch, snapshot.scorch)\n fillSparse(barBend, snapshot.barBend ?? [])\n marks.load(snapshot.marks)\n cracks.load(snapshot.cracks ?? [])\n decalList.push(...(snapshot.decals ?? []).map((decal) => ({ ...decal })))\n decalSerial = decalList.reduce((highest, decal) => Math.max(highest, decal.id), decalSerial)\n for (let chunkIndex = 0; chunkIndex < touched.length; chunkIndex++) markChunk(chunkIndex)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n },\n }\n}\n","import type { TerrainBlow, TerrainMaterial, TerrainProfile } from './types'\n\n// Specific energies are what the marks of real blows imply: a 500 J pistol round leaves about 120 cm³ in soil and 3 cm³ in concrete, an 800 kJ grenade a 1.3 m crater in soil and a 25 cm spall on a slab.\n// Cracks run about a metre from a grenade on a slab and half that on asphalt; a contact charge breaks a reinforced slab right through at about 1 kg of TNT (4.2 MJ) for 12 cm,\n// the thickness cubed (the breaching rule of thumb), leaving a hole about one and a half thicknesses wide with the bars across it.\n// Rolling resistance (C_rr) of each ground, for a round thing rolling on it. Tyre tables (Engineering ToolBox \"Rolling Resistance\", after Gillespie, Fundamentals of Vehicle\n// Dynamics, 1992; Wong, Theory of Ground Vehicles): concrete and new asphalt 0.010-0.015, small new cobbles 0.010-0.015, large worn cobbles 0.03, solid sand, loose gravel and\n// medium hard soil 0.04-0.08, loose sand 0.2-0.4. Grass: a mown golf green 0.07-0.13 (Penner, The physics of putting, Can. J. Phys. 80, 2002), a lawn is longer and slower.\n// A tyre spreads its load; a small rigid roller (a rod, a casing) sinks deeper for its size, so on soft ground the high end of each range is taken. Mud is taken as loose sand\n// (the wheel sinks), dry clay and laterite as medium hard soil at its low end, loose snow (0.3 m, a foot sinks 8 cm) an estimate between packed snow (~0.03) and sand.\n// The rough hard floors keep the 0.015 the kit has always used; a smooth one (glazed tile 0.008, a hardwood floor 0.01) holds a small roller back less, so a bottle rolls farther on it.\n// Rolling damping (1/s, `rollingDamping`): the share of its spin a roller loses per second on top of C_rr, from what drags more the faster it rolls (grass blades, ploughed sand\n// and mud, crunched gravel and snow). Rough hard floors lose 0.3 a second (grit, joints, the floor's own give), glazed tile and hardwood about a third of that; grass 1.5, so a can rolling onto a lawn stops within a metre\n// or two, as one does; loose sand and mud the most. Estimates from the stop distances of a ball or a can on each ground, not a table: no standard publishes them.\nexport const TERRAIN_MATERIALS: readonly TerrainMaterial[] = [\n {\n id: 'turf',\n rolling: 0.15,\n rollingDamping: 1.5,\n dig: { effort: 1.3 },\n debris: 'clods',\n rimShare: 0.25,\n reposeDegrees: 55,\n color: [0.09, 0.2, 0.04],\n pattern: 'grass',\n hits: {\n ballistic: { specificEnergy: 3e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.45 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.45, flammable: true },\n },\n {\n id: 'soil',\n rolling: 0.08,\n rollingDamping: 0.6,\n dig: { effort: 1 },\n debris: 'clods',\n rimShare: 0.35,\n reposeDegrees: 40,\n color: [0.2, 0.12, 0.06],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 4e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 4e6, aspect: 0.45 },\n },\n fire: { maxScorch: 0.6, scorchPerSecond: 0.15 },\n },\n {\n id: 'sand',\n rolling: 0.3,\n rollingDamping: 2.0,\n dig: { effort: 0.8 },\n debris: 'dust',\n rimShare: 0.5,\n reposeDegrees: 33,\n color: [0.62, 0.5, 0.3],\n pattern: 'sand',\n hits: {\n ballistic: { specificEnergy: 2.5e6, aspect: 0.5 },\n blunt: { specificEnergy: 1e6, aspect: 0.2, thresholdJoules: 30 },\n slash: { specificEnergy: 1.5e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.35 },\n },\n fire: { maxScorch: 0.2, scorchPerSecond: 0.05 },\n },\n {\n id: 'gravel',\n rolling: 0.08,\n rollingDamping: 1.0,\n dig: { effort: 1.6 },\n debris: 'chips',\n rimShare: 0.15,\n reposeDegrees: 38,\n color: [0.27, 0.25, 0.22],\n pattern: 'gravel',\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.4 },\n blunt: { specificEnergy: 8e6, aspect: 0.2, thresholdJoules: 200 },\n slash: { specificEnergy: 3e7, aspect: 0.3, thresholdJoules: 400 },\n explosive: { specificEnergy: 1e7, aspect: 0.35 },\n },\n fire: { maxScorch: 0.3, scorchPerSecond: 0.06 },\n scatters: true,\n },\n {\n id: 'asphalt',\n rolling: 0.015,\n rollingDamping: 0.35,\n debris: 'chips',\n color: [0.05, 0.05, 0.055],\n pattern: 'asphalt',\n crack: { reach: 0.6, width: 0.008, thresholdJoules: 800 },\n hits: {\n ballistic: { specificEnergy: 3e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1e8, aspect: 0.1, thresholdJoules: 400 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 400 },\n explosive: { specificEnergy: 2e8, aspect: 0.12 },\n },\n fire: { maxScorch: 0.85, scorchPerSecond: 0.1, burnsAway: 0.00005 },\n },\n {\n id: 'concrete',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.33, 0.33, 0.31],\n pattern: 'concrete',\n crack: { reach: 1, width: 0.006, thresholdJoules: 300 },\n breach: { joulesPerCubedThickness: 2.4e9, radiusOverThickness: 1.5 },\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 3e8, aspect: 0.08, thresholdJoules: 800 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 2.7e9, aspect: 0.12 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'mortar',\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.42, 0.4, 0.36],\n pattern: 'plain',\n hits: {\n ballistic: { specificEnergy: 4e7, aspect: 0.2 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 300 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 300 },\n explosive: { specificEnergy: 8e8, aspect: 0.14 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'ceramic',\n rolling: 0.008,\n rollingDamping: 0.1,\n debris: 'shards',\n color: [0.72, 0.7, 0.66],\n pattern: 'tile',\n crack: { reach: 0.5, width: 0.002, thresholdJoules: 40 },\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.1, minRadius: 0.05 },\n blunt: { specificEnergy: 1e7, aspect: 0.08, thresholdJoules: 80, minRadius: 0.06 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 200, minRadius: 0.03 },\n explosive: { specificEnergy: 1e8, aspect: 0.03, minRadius: 0.12 },\n },\n fire: { maxScorch: 0.5, scorchPerSecond: 0.08 },\n },\n {\n id: 'wood_hard',\n rolling: 0.01,\n rollingDamping: 0.12,\n debris: 'splinters',\n color: [0.3, 0.16, 0.07],\n pattern: 'planks',\n hits: {\n ballistic: { specificEnergy: 2.5e7, aspect: 0.35, minRadius: 0.012 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 120 },\n slash: { specificEnergy: 1.5e7, aspect: 0.4, thresholdJoules: 15 },\n explosive: { specificEnergy: 2e8, aspect: 0.1, minRadius: 0.1 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.2, burnsAway: 0.0012, flammable: true },\n },\n {\n id: 'stone',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.23, 0.22, 0.2],\n pattern: 'stone',\n crack: { reach: 0.5, width: 0.004, thresholdJoules: 1000 },\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e8, aspect: 0.08, thresholdJoules: 1500 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 4e9, aspect: 0.14 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n },\n {\n id: 'mud',\n rolling: 0.3,\n rollingDamping: 3.0,\n // the shovel lifts it, and the hole fills in behind the blade\n dig: { effort: 1.4, closes: true },\n debris: 'clods',\n rimShare: 0.15,\n reposeDegrees: 18,\n color: [0.11, 0.075, 0.04],\n pattern: 'mud',\n hits: {\n ballistic: { specificEnergy: 1.2e6, aspect: 0.7 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 15 },\n slash: { specificEnergy: 5e4, aspect: 0.5 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.4 },\n },\n fire: { maxScorch: 0.15, scorchPerSecond: 0.03 },\n footing: { sink: 0.07, drag: 0.6, prints: true },\n splash: 'mud',\n splats: true,\n },\n {\n id: 'clay',\n rolling: 0.05,\n rollingDamping: 0.4,\n dig: { effort: 2.2 },\n debris: 'chips',\n color: [0.47, 0.27, 0.14],\n pattern: 'clay',\n hits: {\n ballistic: { specificEnergy: 1e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1.5e7, aspect: 0.15, thresholdJoules: 100 },\n slash: { specificEnergy: 6e7, aspect: 0.3, thresholdJoules: 30 },\n explosive: { specificEnergy: 8e6, aspect: 0.25 },\n },\n fire: { maxScorch: 0.35, scorchPerSecond: 0.05 },\n cracks: 4,\n },\n {\n // laterite, a soil baked hard (piçarra): no shovel goes in; only a heavy blow or a charge sinks or cracks it\n id: 'laterite',\n rolling: 0.05,\n rollingDamping: 0.4,\n debris: 'chips',\n rimShare: 0.2,\n color: [0.36, 0.17, 0.08],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 5e7, aspect: 0.2, thresholdJoules: 200 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 600 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 400 },\n explosive: { specificEnergy: 3e8, aspect: 0.18 },\n },\n },\n {\n id: 'snow',\n rolling: 0.1,\n rollingDamping: 1.2,\n dig: { effort: 0.6 },\n debris: 'dust',\n rimShare: 0.4,\n reposeDegrees: 38,\n color: [0.82, 0.85, 0.88],\n pattern: 'snow',\n hits: {\n ballistic: { specificEnergy: 1.5e6, aspect: 1 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 10 },\n slash: { specificEnergy: 5e4, aspect: 0.6 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.5 },\n },\n fire: { maxScorch: 0, scorchPerSecond: 0, burnsAway: 0.015 },\n footing: { sink: 0.08, drag: 0.7, prints: true },\n },\n {\n id: 'cobble',\n rolling: 0.03,\n rollingDamping: 0.6,\n debris: 'blocks',\n color: [0.2, 0.19, 0.18],\n pattern: 'cobble',\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e7, aspect: 0.12, thresholdJoules: 250 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 1.5e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n units: { length: 0.3, width: 0.2, looseJoules: 4000 },\n },\n {\n id: 'paver',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'blocks',\n color: [0.36, 0.33, 0.3],\n pattern: 'paver',\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 4e7, aspect: 0.12, thresholdJoules: 150 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 1.2e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n units: { length: 0.2, width: 0.2, looseJoules: 2500 },\n },\n]\n\n/** How far a blow is held back by the water it crosses before it reaches the bed: a round slows fast in water; a blast is pushed down by it. */\nconst WATER_BLOW_SHARE: Record<TerrainBlow, number> = { ballistic: 0.5, slash: 0.3, blunt: 0.5, explosive: 1 }\n\nexport const TERRAIN_PROFILES: readonly TerrainProfile[] = [\n { id: 'lawn', strata: [{ material: 'turf', thickness: 0.05 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dirt', strata: [{ material: 'soil', thickness: 1.8 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'sand', strata: [{ material: 'sand', thickness: 2.5 }] },\n { id: 'road', strata: [{ material: 'asphalt', thickness: 0.05 }, { material: 'gravel', thickness: 0.25 }, { material: 'soil', thickness: 1.5 }] },\n // a pavement for walking: concrete over its gravel bed over the soil, as the road's layers (a blast digs down to the pipes under it)\n { id: 'sidewalk', strata: [{ material: 'concrete', thickness: 0.08 }, { material: 'gravel', thickness: 0.22 }, { material: 'soil', thickness: 1.5 }] },\n { id: 'concrete_slab', strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'suspended_slab', drop: 3, strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'tile_floor', strata: [{ material: 'ceramic', thickness: 0.008 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'wood_floor', strata: [{ material: 'wood_hard', thickness: 0.022 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'stone_paving', strata: [{ material: 'stone', thickness: 0.08 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n { id: 'mud', strata: [{ material: 'mud', thickness: 0.5 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'gravel_bed', strata: [{ material: 'gravel', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dry_clay', strata: [{ material: 'clay', thickness: 0.35 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'snow', strata: [{ material: 'snow', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'cobblestone', strata: [{ material: 'cobble', thickness: 0.12 }, { material: 'sand', thickness: 0.06 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n // rock at the surface (an outcrop, a quarry floor): a blast only spalls it and a shot chips it\n // a yard as it is dug: topsoil, the clay under it, rock deep down\n { id: 'yard', strata: [{ material: 'soil', thickness: 0.35 }, { material: 'clay', thickness: 1.6 }, { material: 'stone', thickness: 1 }] },\n // ground baked hard (laterite over rock): no shovel goes in\n { id: 'hardpan', strata: [{ material: 'laterite', thickness: 0.8 }, { material: 'stone', thickness: 1.5 }] },\n { id: 'bedrock', surfacePattern: 'rock', strata: [{ material: 'stone', thickness: 3 }] },\n { id: 'paver_floor', strata: [{ material: 'paver', thickness: 0.08 }, { material: 'sand', thickness: 0.05 }, { material: 'gravel', thickness: 0.15 }, { material: 'soil', thickness: 1.2 }] },\n // a pond deep enough to stand chest-high in: a charge on its bed goes off under the water\n { id: 'pond', water: { liquid: 'water', depth: 1.4, drag: 0.4, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.2 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'shallow_water', water: { liquid: 'water', depth: 0.3, drag: 0.65, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.15 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n]\n\n/** About twelve grenades (200 kJ) on the same spot of bare bars. */\nexport const DEFAULT_BAR_YIELD_JOULES = 2_400_000\n\n/** A 10 mm bar of CA-50 steel: bare, a mesh of them at 15 cm holds about 450 kg on a spot. */\nexport const DEFAULT_BAR_DIAMETER = 0.01\nexport const DEFAULT_BAR_YIELD_PA = 500e6\n\n/** The profile of a floor with nothing else said: a plain slab. */\nexport const DEFAULT_PROFILE = 'concrete_slab'\n","/** A small seeded stream: the same seed digs the same crater, so a blow of a few bytes draws the same on every client. */\nexport function createRandom(seed: number): () => number {\n let state = seed | 0\n return () => {\n state = (state + 0x6d2b79f5) | 0\n let mixed = Math.imul(state ^ (state >>> 15), 1 | state)\n mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { createRandom } from './random'\nimport type { TerrainCrack } from './types'\n\n/** Energy the reach and width of a material's cracks are given for (`TerrainCrackResponse`). */\nexport const CRACK_REFERENCE_JOULES = 1e6\n/** A new star this close to an old one, as a share of the old one's reach, lengthens it instead. */\nconst MERGE_SHARE = 0.35\n/** Lines never get thinner than a hairline, nor more than a star holds. */\nconst HAIRLINE = 0.0015\nconst MIN_RAYS = 4\nconst MAX_RAYS = 11\nconst SEGMENTS = 4\nconst BRANCH_CHANCE = 0.45\n\n/** One piece of a crack line on the ground plane, with the width at each end. */\nexport interface CrackSegment {\n readonly x0: number\n readonly z0: number\n readonly x1: number\n readonly z1: number\n readonly w0: number\n readonly w1: number\n}\n\nexport interface CrackStore {\n readonly list: TerrainCrack[]\n readonly version: number\n /** Opens a star at the point, or lengthens and widens the one already there. */\n add(spec: { x: number; z: number; reach: number; width: number; material: string; seed: number }, max: number): TerrainCrack\n clear(): void\n load(cracks: readonly TerrainCrack[]): void\n}\n\nexport function createCrackStore(): CrackStore {\n const list: TerrainCrack[] = []\n let version = 0\n let nextId = 1\n let born = 0\n return {\n list,\n get version() {\n return version\n },\n add(spec, max) {\n version++\n const near = list.find((crack) => Math.hypot(crack.x - spec.x, crack.z - spec.z) < crack.reach * MERGE_SHARE)\n if (near) {\n // a second blow on cracked ground runs the lines further and opens them: concrete fatigues, it does not heal\n near.reach = Math.max(near.reach, spec.reach) + Math.min(near.reach, spec.reach) * 0.25\n near.width = Math.max(near.width, spec.width) * 1.1\n near.rays = Math.min(MAX_RAYS, near.rays + 1)\n return near\n }\n if (list.length >= max) list.shift()\n const rays = MIN_RAYS + Math.floor(createRandom(spec.seed)() * (MAX_RAYS - MIN_RAYS - 2))\n const crack: TerrainCrack = { id: nextId++, x: spec.x, z: spec.z, reach: spec.reach, width: Math.max(HAIRLINE, spec.width), rays, seed: spec.seed, material: spec.material, born: born++ }\n list.push(crack)\n return crack\n },\n clear() {\n list.length = 0\n version++\n },\n load(cracks) {\n list.length = 0\n for (const crack of cracks) {\n list.push({ ...crack })\n nextId = Math.max(nextId, crack.id + 1)\n born = Math.max(born, crack.born + 1)\n }\n version++\n },\n }\n}\n\n/**\n * The lines of a star, from its seed: rays that wander a little as they run out and thin towards their tips, with a branch now and then. The same crack always draws the same\n * lines, so only the crack travels in a snapshot or over the network.\n */\nexport function crackLines(crack: TerrainCrack): CrackSegment[] {\n const random = createRandom(crack.seed)\n const segments: CrackSegment[] = []\n const widthAt = (distance: number): number => Math.max(HAIRLINE, crack.width * (1 - distance / crack.reach))\n for (let ray = 0; ray < crack.rays; ray++) {\n let angle = (ray / crack.rays) * Math.PI * 2 + (random() - 0.5) * 0.6\n const length = crack.reach * (0.45 + 0.55 * random())\n let x = crack.x\n let z = crack.z\n let run = 0\n for (let segment = 0; segment < SEGMENTS; segment++) {\n const step = (length / SEGMENTS) * (0.75 + 0.5 * random())\n angle += (random() - 0.5) * 0.5\n const nx = x + Math.cos(angle) * step\n const nz = z + Math.sin(angle) * step\n segments.push({ x0: x, z0: z, x1: nx, z1: nz, w0: widthAt(run), w1: widthAt(run + step) })\n if (segment > 0 && random() < BRANCH_CHANCE) {\n const side = angle + (random() < 0.5 ? -1 : 1) * (0.45 + random() * 0.5)\n const branch = step * (0.5 + 0.6 * random())\n const w = widthAt(run + step) * 0.6\n segments.push({ x0: nx, z0: nz, x1: nx + Math.cos(side) * branch, z1: nz + Math.sin(side) * branch, w0: Math.max(HAIRLINE, w), w1: HAIRLINE })\n }\n run += step\n x = nx\n z = nz\n }\n }\n return segments\n}\n","import type { TerrainDebris, TerrainDebrisKind } from './types'\n\nconst REST_SPEED = 0.6\nconst RESTITUTION = 0.25\nconst FRICTION = 0.55\nconst MAX_BOUNCES = 2\nconst REST_GAP = 0.01\n\nexport interface DebrisWorld {\n heightAt(x: number, z: number): number\n gravity: number\n /** Soft pieces join the ground where they stop; a false keeps the piece as loose rubble. */\n settle(piece: TerrainDebris): boolean\n}\n\n/** Pieces thrown by blows: they fly, hit the deformed ground, and come to rest. Past `max` the oldest at rest goes first. */\nexport interface DebrisStore {\n readonly list: TerrainDebris[]\n throwPiece(spec: { material: string; kind: TerrainDebrisKind; radius: number; position: [number, number, number]; velocity: [number, number, number]; spin: [number, number, number] }): void\n update(dt: number, world: DebrisWorld): void\n clear(): void\n}\n\nexport function createDebrisStore(max: () => number): DebrisStore {\n const list: TerrainDebris[] = []\n let serial = 0\n\n function makeRoom(): void {\n if (list.length < max()) return\n let at = 0\n let oldest = Infinity\n let oldestResting = -1\n let restingBorn = Infinity\n list.forEach((piece, index) => {\n if (piece.born < oldest) {\n oldest = piece.born\n at = index\n }\n if (piece.atRest && piece.born < restingBorn) {\n restingBorn = piece.born\n oldestResting = index\n }\n })\n list.splice(oldestResting >= 0 ? oldestResting : at, 1)\n }\n\n return {\n list,\n throwPiece(spec) {\n makeRoom()\n list.push({ ...spec, id: ++serial, born: serial, atRest: false, bounces: 0 })\n },\n update(dt, world) {\n for (let i = list.length - 1; i >= 0; i--) {\n const piece = list[i]!\n if (piece.atRest) {\n // what it lay on was dug away or heaped over: it falls again, or rides up\n const under = world.heightAt(piece.position[0], piece.position[2]) + piece.radius * 0.6\n if (piece.position[1] > under + REST_GAP) piece.atRest = false\n else if (piece.position[1] < under - REST_GAP) piece.position[1] = under\n if (piece.atRest) continue\n }\n const { position, velocity } = piece\n velocity[1] -= world.gravity * dt\n position[0] += velocity[0] * dt\n position[1] += velocity[1] * dt\n position[2] += velocity[2] * dt\n const ground = world.heightAt(position[0], position[2]) + piece.radius * 0.6\n if (position[1] > ground) continue\n position[1] = ground\n const speed = Math.hypot(velocity[0], velocity[1], velocity[2])\n if (speed < REST_SPEED || piece.bounces >= MAX_BOUNCES) {\n piece.atRest = true\n if (world.settle(piece)) list.splice(i, 1)\n continue\n }\n piece.bounces++\n velocity[1] = Math.abs(velocity[1]) * RESTITUTION\n velocity[0] *= FRICTION\n velocity[2] *= FRICTION\n }\n },\n clear() {\n list.length = 0\n serial = 0\n },\n }\n}\n","import type { GroundLoss } from '@adatechnology/game-contracts'\nimport type { TerrainVoid } from './types'\n\n/** A loss shallower than this (m below the untouched surface) is a scuff, not a void anything bears over. */\nexport const GROUND_LOSS_MIN_DEPTH = 0.02\n/** Sand that slid tells the host only where it lowered the ground by at least this much (m). */\nexport const SLIDE_LOSS_MIN_LOWERING = 0.05\n/** Under this depth (m) a vertex still counts as ground in `voidUnder`. */\nexport const VOID_MIN_DEPTH = 0.02\n\nexport interface HeightGrid {\n readonly x0: number\n readonly z0: number\n readonly cellSize: number\n readonly stride: number\n readonly columns: number\n readonly rows: number\n readonly dug: Float32Array\n}\n\n/** What one event lowered, by vertex (metres of the column, not of the loose heap on it). Lowerings of the same vertex add up; a fill counts against them. */\nexport type LossTally = Map<number, number>\n\nexport function tallyLowered(tally: LossTally, index: number, amount: number): void {\n if (amount !== 0) tally.set(index, (tally.get(index) ?? 0) + amount)\n}\n\n/**\n * The disc the tally lowered, or null when it is shallower than `GROUND_LOSS_MIN_DEPTH`. Vertices lowered less than `minLowering` are left out. `depth` is\n * the deepest the ground is now under its untouched surface there. A `bowl` (a crater, sand that slid) is told as the paraboloid that is half as deep\n * where the ground is now half as deep, so a wide shallow scrape around a deep hole does not pass for a wide deep one; a `flat` hole (a slab that opened)\n * keeps its edge.\n */\nexport function lossOf(grid: HeightGrid, tally: LossTally, spec: { source: string; minLowering: number; shape: 'bowl' | 'flat' }): GroundLoss | null {\n let weight = 0\n let centerX = 0\n let centerZ = 0\n let depth = 0\n let deepest = 0\n const kept: number[] = []\n for (const [index, amount] of tally) {\n if (amount < spec.minLowering || amount <= 0) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n weight += amount\n centerX += (grid.x0 + column * grid.cellSize) * amount\n centerZ += (grid.z0 + row * grid.cellSize) * amount\n depth = Math.max(depth, grid.dug[index]!)\n deepest = Math.max(deepest, amount)\n kept.push(index)\n }\n if (weight <= 0 || depth < GROUND_LOSS_MIN_DEPTH || deepest < GROUND_LOSS_MIN_DEPTH) return null\n centerX /= weight\n centerZ /= weight\n let radius = 0\n for (const index of kept) {\n if (spec.shape === 'bowl' && grid.dug[index]! < depth / 2) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n radius = Math.max(radius, Math.hypot(grid.x0 + column * grid.cellSize - centerX, grid.z0 + row * grid.cellSize - centerZ))\n }\n const reach = spec.shape === 'bowl' ? Math.SQRT2 * (radius + grid.cellSize / 2) : radius + grid.cellSize / 2\n return { x: centerX, z: centerZ, radius: reach, depth, removed: weight * grid.cellSize * grid.cellSize, source: spec.source }\n}\n\n/** How much of the disc (x, z, radius) has no ground under where it was: the vertices inside it, or the nearest one when the disc is smaller than a cell. */\nexport function voidUnder(grid: HeightGrid, spec: { x: number; z: number; radius: number }): TerrainVoid {\n const { x, z, radius } = spec\n const clamp = (value: number, top: number): number => Math.max(0, Math.min(top, value))\n const column0 = clamp(Math.ceil((x - radius - grid.x0) / grid.cellSize), grid.columns)\n const column1 = clamp(Math.floor((x + radius - grid.x0) / grid.cellSize), grid.columns)\n const row0 = clamp(Math.ceil((z - radius - grid.z0) / grid.cellSize), grid.rows)\n const row1 = clamp(Math.floor((z + radius - grid.z0) / grid.cellSize), grid.rows)\n let count = 0\n let sum = 0\n let depth = 0\n let open = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(grid.x0 + column * grid.cellSize - x, grid.z0 + row * grid.cellSize - z) > radius) continue\n const here = grid.dug[row * grid.stride + column]!\n count++\n sum += here\n depth = Math.max(depth, here)\n if (here >= VOID_MIN_DEPTH) open++\n }\n }\n if (count === 0) {\n const here = grid.dug[clamp(Math.round((z - grid.z0) / grid.cellSize), grid.rows) * grid.stride + clamp(Math.round((x - grid.x0) / grid.cellSize), grid.columns)]!\n return { depth: here, mean: here, fraction: here >= VOID_MIN_DEPTH ? 1 : 0 }\n }\n return { depth, mean: sum / count, fraction: open / count }\n}\n","/**\n * The ground's blend as pure functions of numbers, shared by `Terrain.heightAt`, `Terrain.heightGrid` and `heightPatchGrid`: the same code reads the terrain on the main\n * thread and a copy of its vertices anywhere else (a worker has no terrain), so the heights agree to the bit.\n */\n\n/** Where `v` falls along an axis of `count` cells of `cellSize` from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\nexport const cellCoordinate = (v: number, origin: number, count: number, cellSize: number): number => Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize))\n\n/** The blend of two heights, `t` of the way from `near` to `far` (the one step every blend of the ground is made of). */\nexport const blendHeights = (near: number, far: number, t: number): number => near * (1 - t) + far * t\n\n/**\n * The terrain's vertex heights (`base - dug + loose`, as `heightAt` reads them) over a block of its cells, with what places them in the terrain: plain numbers, so a worker\n * can read the ground from them (`heightPatchGrid`) and answer what `heightGrid` does there, to the bit. Made by `Terrain.heightPatch`.\n */\nexport interface HeightPatch {\n readonly cellSize: number\n /** The terrain's first vertex (its bounds' min x and z) and its cells along x and z: where a point's cell is found, with its clamps. */\n readonly originX: number\n readonly originZ: number\n readonly columns: number\n readonly rows: number\n /** The patch's first vertex (column and row of the terrain) and how many vertices it has along x and along z. */\n readonly column0: number\n readonly row0: number\n readonly width: number\n readonly depth: number\n /** The heights, `width` per row, rows from `row0`: `heights[(row - row0) * width + column - column0]` (the array may be longer). */\n readonly heights: Float64Array\n}\n\n// the cell and the blend of each column and row a patch read finds, kept between reads (one at a time) so a read costs no new arrays\nlet patchColumns = new Int32Array(0)\nlet patchBlendX = new Float64Array(0)\nlet patchNear = new Float64Array(0)\nlet patchFar = new Float64Array(0)\n\n/**\n * The ground over a lattice from a patch: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the terrain's `heightGrid` answers there (the same\n * cell, clamps and blends, on the same vertex heights). Every point must lie inside the terrain and over the patch's cells (`Terrain.heightPatch` of a rectangle holding\n * them): one that does not throws. Not reentrant (module scratch).\n */\nexport function heightPatchGrid(patch: HeightPatch, xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightPatchGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n const { cellSize, originX, originZ, columns, rows, column0, row0, heights } = patch\n const stride = patch.width\n if (patchColumns.length < width) {\n patchColumns = new Int32Array(width)\n patchBlendX = new Float64Array(width)\n patchNear = new Float64Array(width)\n patchFar = new Float64Array(width)\n }\n for (let i = 0; i < width; i++) {\n const fx = cellCoordinate(xs[i]!, originX, columns, cellSize)\n const column = (fx | 0) - column0\n if (column < 0 || column + 1 >= stride) throw new RangeError(`heightPatchGrid: x ${xs[i]} is past the patch`)\n patchColumns[i] = column\n patchBlendX[i] = fx - (fx | 0)\n }\n let blended = -1\n for (let j = 0; j < depth; j++) {\n const fz = cellCoordinate(zs[j]!, originZ, rows, cellSize)\n const row = (fz | 0) - row0\n if (row < 0 || row + 1 >= patch.depth) throw new RangeError(`heightPatchGrid: z ${zs[j]} is past the patch`)\n const tz = fz - (fz | 0)\n // the two x blends of a column depend on its row of cells only, as in `heightGrid`\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const index = row * stride + patchColumns[i]!\n const tx = patchBlendX[i]!\n patchNear[i] = blendHeights(heights[index]!, heights[index + 1]!, tx)\n patchFar[i] = blendHeights(heights[index + stride]!, heights[index + stride + 1]!, tx)\n }\n }\n for (let i = 0; i < width; i++) out[j * width + i] = blendHeights(patchNear[i]!, patchFar[i]!, tz)\n }\n}\n\n/** Whether two patches hold the same vertices at the same heights (the ground they read is the same, to the bit, wherever both reach). */\nexport const samePatch = (a: HeightPatch, b: HeightPatch): boolean => {\n if (a.cellSize !== b.cellSize || a.originX !== b.originX || a.originZ !== b.originZ || a.columns !== b.columns || a.rows !== b.rows) return false\n if (a.column0 !== b.column0 || a.row0 !== b.row0 || a.width !== b.width || a.depth !== b.depth) return false\n const count = a.width * a.depth\n for (let k = 0; k < count; k++) if (a.heights[k] !== b.heights[k]) return false\n return true\n}\n","import type { TerrainBudget, TerrainMark } from './types'\n\n/** Two marks at this fraction of their radii or closer are one hole. */\nconst SAME_HOLE = 0.75\n\n/** Fine marks under a budget per area and a global one: past the budget the closest two of the area become one, and past the global one the oldest goes. */\nexport interface MarkStore {\n readonly list: TerrainMark[]\n add(spec: Omit<TerrainMark, 'id' | 'count' | 'born'>): TerrainMark\n near(x: number, z: number, radius: number): TerrainMark | undefined\n depthAt(x: number, z: number): number\n remove(mark: TerrainMark): void\n removeInside(x: number, z: number, radius: number): void\n clear(): void\n load(marks: readonly TerrainMark[]): void\n readonly version: number\n}\n\nexport function createMarkStore(budget: TerrainBudget): MarkStore {\n const list: TerrainMark[] = []\n const areas = new Map<number, TerrainMark[]>()\n let serial = 0\n let version = 0\n const areaKey = (x: number, z: number): number => Math.floor(x / budget.markAreaSize) * 100003 + Math.floor(z / budget.markAreaSize)\n\n function detach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) {\n const at = area.indexOf(mark)\n if (at >= 0) area.splice(at, 1)\n if (area.length === 0) areas.delete(key)\n }\n const at = list.indexOf(mark)\n if (at >= 0) list.splice(at, 1)\n version++\n }\n\n function attach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) area.push(mark)\n else areas.set(key, [mark])\n list.push(mark)\n version++\n }\n\n function mergeClosestPair(area: TerrainMark[]): void {\n let bestA = area[0]!\n let bestB = area[1]!\n let best = Infinity\n for (let i = 0; i < area.length; i++) {\n for (let j = i + 1; j < area.length; j++) {\n const distance = Math.hypot(area[i]!.x - area[j]!.x, area[i]!.z - area[j]!.z)\n if (distance < best) {\n best = distance\n bestA = area[i]!\n bestB = area[j]!\n }\n }\n }\n const weight = bestA.radius ** 2 + bestB.radius ** 2\n const shareB = weight > 0 ? bestB.radius ** 2 / weight : 0.5\n detach(bestB)\n bestA.x += (bestB.x - bestA.x) * shareB\n bestA.z += (bestB.z - bestA.z) * shareB\n bestA.radius = Math.sqrt(weight)\n bestA.depth = Math.max(bestA.depth, bestB.depth)\n bestA.count += bestB.count\n version++\n }\n\n return {\n list,\n add(spec) {\n const mark: TerrainMark = { ...spec, id: ++serial, count: 1, born: serial }\n attach(mark)\n const area = areas.get(areaKey(mark.x, mark.z))!\n if (area.length > budget.maxMarksPerArea) mergeClosestPair(area)\n if (list.length > budget.maxMarks) detach(list.reduce((oldest, candidate) => (candidate.born < oldest.born ? candidate : oldest)))\n return mark\n },\n near(x, z, radius) {\n let found: TerrainMark | undefined\n let best = Infinity\n const reach = Math.ceil((radius + 0.5) / budget.markAreaSize)\n const baseX = Math.floor(x / budget.markAreaSize)\n const baseZ = Math.floor(z / budget.markAreaSize)\n for (let dx = -reach; dx <= reach; dx++) {\n for (let dz = -reach; dz <= reach; dz++) {\n for (const mark of areas.get((baseX + dx) * 100003 + baseZ + dz) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < best && distance < Math.max(mark.radius, radius) * SAME_HOLE) {\n best = distance\n found = mark\n }\n }\n }\n }\n return found\n },\n depthAt(x, z) {\n let depth = 0\n for (const mark of areas.get(areaKey(x, z)) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < mark.radius) depth = Math.max(depth, mark.depth * (1 - (distance / mark.radius) ** 2))\n }\n return depth\n },\n remove: detach,\n removeInside(x, z, radius) {\n for (const mark of [...list]) if (Math.hypot(mark.x - x, mark.z - z) + mark.radius * 0.5 < radius) detach(mark)\n },\n clear() {\n list.length = 0\n areas.clear()\n // the numbering starts again with the ground (a loaded snapshot takes it on from its own marks); `version` only grows, the renderers follow it\n serial = 0\n version++\n },\n load(marks) {\n this.clear()\n for (const mark of marks) {\n attach({ ...mark })\n serial = Math.max(serial, mark.id)\n }\n },\n get version() {\n return version\n },\n }\n}\n","import type { DestructibleImpl, DestructibleSpec, DestructionEvent, Hit, ObjectState, SurfaceRay, SurfaceRayHit } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainBlowResult } from './types'\n\nconst PART_ID = 'ground'\nconst PART_DEPTH = 3\nconst RAY_BACKOFF = 1\nconst GROUND_HP = 1e12\n/** Most metres the ground rises above its flat level (a heap of what a crater threw out): a ray higher than this cannot meet it. */\nconst HEAP_REACH = 3\n\nexport interface TerrainImplOptions {\n readonly id: string\n readonly name?: string\n /** Every blow that left its mark, with what it did. */\n readonly onBlow?: (result: TerrainBlowResult, hit: Hit) => void\n}\n\n/**\n * The ground as an object of the destruction world (`DestructionWorld.register`): shots, blows, blasts and flames reach it through the world's own raycast and blast like anything else.\n * The collision part is a flat box that only says where to look: the world's raycast asks `surfaceRay`, which follows the ground as it is now (craters, heaps),\n * so a round fired into a crater meets its floor, not the flat top of the box over it.\n */\nexport function createTerrainImpl(terrain: Terrain, options: TerrainImplOptions): DestructibleImpl {\n const { id } = options\n const [x0, z0, x1, z1] = terrain.bounds\n const centerColumn = Math.max(0, Math.min(terrain.columns, Math.round((x1 - x0) / 2 / terrain.cellSize)))\n const centerRow = Math.max(0, Math.min(terrain.rows, Math.round((z1 - z0) / 2 / terrain.cellSize)))\n const centerMaterial = (): string => terrain.vertexMaterial(centerColumn, centerRow).id\n const buildSpec = (material: string): DestructibleSpec => ({\n name: options.name ?? 'Ground',\n parts: [\n {\n id: PART_ID,\n material,\n shape: { kind: 'box', size: [x1 - x0, PART_DEPTH, z1 - z0] },\n position: [(x0 + x1) / 2, -PART_DEPTH / 2, (z0 + z1) / 2],\n hp: GROUND_HP,\n anchored: true,\n tags: ['terrain'],\n },\n ],\n joints: [],\n })\n let cachedSpec: DestructibleSpec | undefined\n const spec = (): DestructibleSpec => {\n const material = centerMaterial()\n if (cachedSpec?.parts[0]?.material !== material) cachedSpec = buildSpec(material)\n return cachedSpec\n }\n const buildState = (material: string): ObjectState => ({\n id,\n position: [0, 0, 0],\n rotation: [0, 0, 0, 1],\n parts: [{ id: PART_ID, material, status: 'intact', hp: GROUND_HP, maxHp: GROUND_HP, mass: 0, temperature: 0, burning: false, fuel: 0, char: 0, melt: 0, dents: [], holes: [], cracks: [], group: 0 }],\n joints: [],\n groups: [[PART_ID]],\n destroyed: false,\n })\n let cachedState: ObjectState | undefined\n const state = (): ObjectState => {\n const material = centerMaterial()\n if (cachedState?.parts[0]?.material !== material) cachedState = buildState(material)\n return cachedState\n }\n const resolve = (hit: Hit): Hit => {\n if (hit.type !== 'ballistic' && hit.type !== 'blunt' && hit.type !== 'slash') return hit\n if (!hit.direction) return { ...hit, point: [hit.point[0], terrain.heightAt(hit.point[0], hit.point[2]), hit.point[2]] }\n const [dx, dy, dz] = hit.direction\n const from = [hit.point[0] - dx * RAY_BACKOFF, hit.point[1] - dy * RAY_BACKOFF, hit.point[2] - dz * RAY_BACKOFF]\n const onGround = terrain.raycast(from, hit.direction, RAY_BACKOFF + PART_DEPTH)\n return onGround ? { ...hit, point: onGround.point } : hit\n }\n /** The ground as it is now along the ray, marched only where the ray is within the depth of the ground and the height of a heap. */\n const surfaceRay = (ray: SurfaceRay): SurfaceRayHit | null => {\n if (ray.ignored?.(PART_ID)) return null\n const [ox, oy, oz] = ray.origin\n const [dx, dy, dz] = ray.direction\n const enter = dy < 0 ? Math.max(0, (oy - HEAP_REACH) / -dy) : oy <= HEAP_REACH ? 0 : Infinity\n const leave = dy < 0 ? (oy + PART_DEPTH) / -dy : Math.hypot(x1 - x0, z1 - z0) + Math.hypot(ox - (x0 + x1) / 2, oz - (z0 + z1) / 2)\n const far = Math.min(ray.maxDistance, leave)\n if (!(enter <= far)) return null\n const hit = terrain.raycast([ox + dx * enter, oy + dy * enter, oz + dz * enter], ray.direction, far - enter)\n if (!hit) return null\n return { part: PART_ID, point: hit.point, normal: hit.normal, distance: enter + hit.distance, pathLen: PART_DEPTH }\n }\n return {\n id,\n ...(options.name ? { name: options.name } : {}),\n describe: spec,\n surfaceRay,\n hit(hit): DestructionEvent[] {\n const landed = resolve(hit)\n const result = terrain.applyHit(landed)\n if (!result || result.radius <= 0) return []\n options.onBlow?.(result, landed)\n return [{ type: 'damage', object: id, time: 0, part: PART_ID, amount: 0, hp: GROUND_HP, damageType: hit.type, ...(hit.source ? { source: hit.source } : {}) }]\n },\n update(dt) {\n terrain.update(dt)\n return []\n },\n state,\n reset() {\n terrain.reset()\n },\n serialize: () => terrain.serialize(),\n load(data) {\n terrain.load(data as ReturnType<Terrain['serialize']>)\n },\n }\n}\n","import type { GroundExcavation, GroundLayout, GroundLoss, Hit } from '@adatechnology/game-contracts'\n\nimport type { HeightPatch } from './height-patch'\n\nexport type { GroundExcavation, GroundLayout, GroundZone } from '@adatechnology/game-contracts'\n\n/** The blows that remove ground. Fire and heat char it instead (`TerrainMaterial.fire`). */\nexport type TerrainBlow = 'ballistic' | 'blunt' | 'slash' | 'explosive'\n\n/** A blow at (x, z): `energy` in joules, `direction` where it travels, `contactRadius` of a blunt tool, `caliber` (mm) of a round, which shapes its crater. */\nexport type TerrainStrike = { x: number; z: number; energy: number; direction?: readonly number[]; contactRadius?: number; caliber?: number }\n\n/** What one kind of blow does to a material. */\nexport interface TerrainBlowResponse {\n /** Joules it takes to remove one cubic metre. */\n readonly specificEnergy: number\n /** Depth over radius of the bowl it leaves: a soft ground craters deep, a hard one spalls wide and shallow. */\n readonly aspect: number\n /** A blow under this many joules leaves nothing (a punch on a slab). */\n readonly thresholdJoules?: number\n /** The bowl is never narrower: a tile comes off as a piece, not as the size of the bullet. */\n readonly minRadius?: number\n}\n\nexport type TerrainDebrisKind = 'clods' | 'chips' | 'shards' | 'splinters' | 'dust' | 'blocks'\n\n/** How a material of the destruction catalogue behaves as ground. `id` is the catalogue's. */\nexport interface TerrainMaterial {\n readonly id: string\n readonly hits: Partial<Record<TerrainBlow, TerrainBlowResponse>>\n readonly debris: TerrainDebrisKind\n /** Share of what a blow removes that piles up on the rim; the rest is thrown. Rigid materials have none. */\n readonly rimShare?: number\n /** Steepest slope in degrees it holds; loose ground slides until it is back to it. */\n readonly reposeDegrees?: number\n /** A shovel digs it: `effort` is how hard a shovelful is against loose soil (1); a material without it (concrete, stone, asphalt) is not dug by hand. */\n readonly dig?: { readonly effort: number; readonly closes?: boolean }\n readonly fire?: TerrainFireResponse\n /** Linear rgb, 0..1, of the material where it is exposed. */\n readonly color: readonly [number, number, number]\n /** Surface pattern a renderer draws while the stratum is intact (`TERRAIN_PATTERNS`). */\n readonly pattern?: TerrainPattern\n /** A rigid surface cracks around a hard blow instead of only losing a bowl: lines that run out from the point (concrete, asphalt, tile, stone). */\n readonly crack?: TerrainCrackResponse\n /** A rigid layer a contact charge breaks right through once it has enough for the whole thickness (the scabbing of a slab): `explosive` only. */\n readonly breach?: TerrainBreachResponse\n /** What a foot does on it. */\n readonly footing?: TerrainFooting\n /**\n * Its rolling resistance (C_rr) to a round thing rolling on it (a can, a rod, a casing): the moment C_rr x weight x radius that slows the roll. Soft ground (sand, mud,\n * grass) gives under the roller and holds it back far more than a hard one (asphalt, concrete). Left out: the host's default (a hard floor).\n */\n readonly rolling?: number\n /**\n * Its rolling damping (1/s): the share of its spin a round thing rolling on it loses per second on top of `rolling`, from what drags more the faster it rolls (grass\n * blades, ploughed sand). Added to the roller's own. Left out: the host's default (a hard floor).\n */\n readonly rollingDamping?: number\n /** Liquid (of the fluids catalogue) a blow on it throws up. */\n readonly splash?: string\n /** Its pieces do not join the ground where they land: they stay as loose stones. */\n readonly scatters?: boolean\n /** Its pieces leave a splat on whatever they land on. */\n readonly splats?: boolean\n /** A brittle crust: each blow runs cracks this many bowl radii around it. */\n readonly cracks?: number\n /** Laid in separate pieces on a bed: a blow loosens whole pieces instead of digging a bowl. */\n readonly units?: TerrainUnits\n}\n\nexport interface TerrainCrackResponse {\n /** Metres the longest line runs for a blow of 1 MJ; it grows with the cube root of the energy. */\n readonly reach: number\n /** Metres wide the lines open at the point for 1 MJ, also by the cube root, never under a hairline. */\n readonly width: number\n /** A blow under this many joules leaves no crack (a punch on a slab). */\n readonly thresholdJoules: number\n}\n\nexport interface TerrainBreachResponse {\n /** Joules over the cube of the layer's thickness (J/m³) that break the whole layer through: for reinforced concrete about 1 kg of TNT for 12 cm. */\n readonly joulesPerCubedThickness: number\n /** Radius of the breach over the thickness at that energy; it grows with the cube root of the excess. */\n readonly radiusOverThickness: number\n}\n\nexport interface TerrainFooting {\n /** Metres the foot goes in. */\n readonly sink: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Keeps the print of what presses it. */\n readonly prints?: boolean\n}\n\nexport interface TerrainUnits {\n /** Metres along x, in rows that shift every other one. Multiples of the cell keep the hole sharp. */\n readonly length: number\n /** Metres along z. */\n readonly width: number\n /** Joules a piece takes, added blow by blow, before it comes off its bed. */\n readonly looseJoules: number\n}\n\nexport interface TerrainFireResponse {\n /** How black it gets, 0..1: concrete only soots, wood and turf char through. */\n readonly maxScorch: number\n /** Scorch gained per second in a flame. */\n readonly scorchPerSecond: number\n /** Metres per second the flame eats away (wood char). */\n readonly burnsAway?: number\n /** Catches and carries the fire to the next cells on its own. */\n readonly flammable?: boolean\n}\n\nexport const TERRAIN_PATTERNS = ['plain', 'grass', 'soil', 'sand', 'asphalt', 'concrete', 'tile', 'planks', 'stone', 'mud', 'gravel', 'clay', 'snow', 'cobble', 'paver', 'rock'] as const\nexport type TerrainPattern = (typeof TERRAIN_PATTERNS)[number]\n\n/** One layer of a column, from the top down. */\nexport interface TerrainStratum {\n /** A `TerrainMaterial.id`. */\n readonly material: string\n /** Metres. */\n readonly thickness: number\n /** Bars inside the layer: exposed at `cover`, they make the digging `resistance` times harder. */\n readonly reinforcement?: {\n readonly material: string\n readonly cover: number\n readonly spacing: number\n readonly resistance: number\n /** Joules on one spot of bare bars before they give way (default `DEFAULT_BAR_YIELD_JOULES`). */\n readonly yieldJoules?: number\n /** Metres across one bar (default `DEFAULT_BAR_DIAMETER`): with `yieldPa` it says what weight bare bars hold. */\n readonly diameter?: number\n /** Pascals at which the steel yields (default `DEFAULT_BAR_YIELD_PA`). */\n readonly yieldPa?: number\n }\n}\n\n/** Weight standing still on the ground: a body, a fridge, a car. */\nexport interface TerrainLoad {\n readonly x: number\n readonly z: number\n /** Metres: half the side of the footprint it stands on. */\n readonly radius: number\n readonly newtons: number\n}\n\n/** What a column of ground is made of. The strata end at the digging limit: under them nothing is removed. */\nexport interface TerrainProfile {\n readonly id: string\n readonly strata: readonly TerrainStratum[]\n /** A slab with nothing under it: where its bars give way the floor opens, and the ground is this many metres further down (the floor below). Without it the ground under the slab holds it up. */\n readonly drop?: number\n /** How the untouched top layer is drawn when it is not its material's way: bare rock is stone, but not laid as paving. Dug, the material's own shows. */\n readonly surfacePattern?: TerrainPattern\n /** Water standing over the column: the strata are its bed. */\n readonly water?: TerrainWater\n}\n\nexport interface TerrainWater {\n /** A liquid of the fluids catalogue. */\n readonly liquid: string\n /** Metres from the surface to the bed. */\n readonly depth: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Share of a blow that reaches the bed. */\n readonly blowShare: Partial<Record<TerrainBlow, number>>\n}\n\nexport interface TerrainBudget {\n /** Side in metres of the squares that hold a limited number of marks. */\n readonly markAreaSize: number\n readonly maxMarksPerArea: number\n readonly maxMarks: number\n /** Chunks a renderer redraws per frame; the rest wait. */\n readonly maxDirtyChunksPerFrame: number\n readonly maxDebris: number\n /** Thrown pieces of one blow. */\n readonly maxDebrisPerBlow: number\n /** Cells checked for sliding per frame. */\n readonly maxSlideCellsPerFrame: number\n /** Cells on fire at once. */\n readonly maxBurningCells: number\n /** Stars of cracks kept; past it the oldest goes. */\n readonly maxCracks: number\n /** Cracks, prints, ruts, splats and ripples at once; past it the oldest goes. */\n readonly maxDecals: number\n}\n\nexport interface TerrainOptions {\n /** World rectangle `[x0, z0, x1, z1]` in metres. */\n readonly bounds: readonly [number, number, number, number]\n /** Metres per cell (default 0.1). */\n readonly cellSize?: number\n /** Cells per side of a chunk (default 32). */\n readonly chunkCells?: number\n /** Which profile is where. */\n readonly layout?: GroundLayout\n /** Extra or overriding profiles, by id. */\n readonly profiles?: readonly TerrainProfile[]\n /** Extra or overriding materials, by id. */\n readonly materials?: readonly TerrainMaterial[]\n readonly budget?: Partial<TerrainBudget>\n /** Height of the untouched ground (default flat at 0). */\n readonly baseHeight?: (x: number, z: number) => number\n /** Metres per second squared. */\n readonly gravity?: number\n readonly seed?: number\n /**\n * Ground taken away from under the surface: a crater (`crater`), a slab that gave way into the void under it (`slab`), sand that slid off a slope\n * (`slide`). The host hands it to what stands there (`DestructionWorld.groundLoss`), so foundations over it settle or lose their support.\n */\n readonly onGroundLoss?: (loss: GroundLoss) => void\n}\n\n/** A shovelful (`Terrain.dig`): the blade's footprint at (x, z), how deep it goes in, where the earth is thrown (a heap on the ground there). */\nexport interface TerrainDig {\n readonly x: number\n readonly z: number\n /** Width and length of the blade's bite, metres (default 0.3 x 0.3). */\n readonly size?: readonly [number, number]\n /** How deep one shovelful goes, metres (default 0.2). */\n readonly depth?: number\n /** Where the earth lands: heaped round this point. Without it, it is lost (carried away). */\n readonly dump?: { readonly x: number; readonly z: number }\n}\n\n/** What a shovelful took. */\nexport interface TerrainDigResult {\n /** Cubic metres taken out (and heaped at `dump`). */\n readonly volume: number\n /** The material dug (the one at the bite's centre). */\n readonly material: string\n /** How hard it was against loose soil (1): a shovelful of it takes that much longer. 0 when nothing was dug. */\n readonly effort: number\n /** The material that stopped the blade (concrete, stone...), when it could not dig; `water` where the ground is under water. */\n readonly refused?: string\n /** The blade lifted it but the hole closed behind it (mud): nothing changed. */\n readonly closes?: true\n}\n\n/** Earth thrown back into a hole (`Terrain.fill`): taken from the heap round `from`, laid into the hole at (x, z), at most `volume`. */\nexport interface TerrainFill {\n readonly x: number\n readonly z: number\n readonly size?: readonly [number, number]\n readonly from: { readonly x: number; readonly z: number; readonly radius: number }\n readonly volume: number\n}\n\n/** What is missing under a disc of the ground (`Terrain.voidUnder`). */\nexport interface TerrainVoid {\n /** Metres under the untouched surface at the deepest vertex. */\n readonly depth: number\n /** Metres under the untouched surface, averaged over the disc. */\n readonly mean: number\n /** 0..1, the share of the disc's vertices that are void (dug at least `VOID_MIN_DEPTH`). */\n readonly fraction: number\n}\n\n/** A fine mark: a bullet pock or a chip, smaller than a cell. It grows with the blows on it until it is dug into the height field. */\nexport interface TerrainMark {\n readonly id: number\n x: number\n z: number\n radius: number\n depth: number\n /** The material the mark shows at the bottom. */\n material: string\n blow: TerrainBlow\n /** Blows and marks merged into this one. */\n count: number\n /** Order of creation: the oldest is the one recycled. */\n born: number\n}\n\nexport type TerrainDecalKind = 'crack' | 'print' | 'rut' | 'splat' | 'ripple'\n\n/** A mark with no depth of its own: drawn over the surface, it changes nothing that stands there. */\nexport interface TerrainDecal {\n readonly id: number\n readonly kind: TerrainDecalKind\n readonly x: number\n readonly z: number\n readonly radius: number\n /** Radians around y. */\n readonly angle: number\n /** The material whose colour it takes. */\n readonly material: string\n /** Seconds it has been there; a ripple fades with it. */\n age: number\n}\n\nexport interface TerrainDebris {\n readonly id: number\n readonly material: string\n readonly kind: TerrainDebrisKind\n readonly radius: number\n readonly position: [number, number, number]\n readonly velocity: [number, number, number]\n readonly spin: [number, number, number]\n atRest: boolean\n bounces: number\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** A star of cracks on a rigid surface. The lines themselves come from `crackLines`, drawn from the seed, so a snapshot keeps only this. */\nexport interface TerrainCrack {\n readonly id: number\n readonly x: number\n readonly z: number\n /** Metres the longest line runs. */\n reach: number\n /** Metres wide the lines are at the point. */\n width: number\n rays: number\n readonly seed: number\n readonly material: string\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** What a blow did. */\nexport interface TerrainBlowResult {\n readonly point: readonly [number, number, number]\n /** Bowl radius in metres; 0 when the blow left nothing. */\n readonly radius: number\n /** Metres removed at the point. */\n readonly depth: number\n /** Metres under the untouched surface the point is now. */\n readonly totalDepth: number\n /** Materials removed, top first, with the cubic metres of each. */\n readonly removed: readonly { readonly material: string; readonly volume: number }[]\n /** Material now exposed at the point. */\n readonly exposed: string\n /** The column has no more to give here: the slab's bottom, the end of the rock. */\n readonly atLimit: boolean\n /** Reinforcement is showing at the point. */\n readonly rebarExposed: boolean\n /** The bars gave way here and the slab opened (`TerrainProfile.drop`). */\n readonly collapsed: boolean\n /** Left a fine mark (`true`) or dug the height field (`false`). */\n readonly fine: boolean\n /** The cracks it opened or lengthened around the point, if the surface is rigid. */\n readonly crack?: TerrainCrack\n /** A contact charge broke the rigid layer right through (`TerrainMaterial.breach`). */\n readonly breached?: boolean\n /** The water the blow crossed: `level` is where the splash goes up. */\n readonly water?: { readonly liquid: string; readonly level: number }\n}\n\n/** The water standing at a point. */\nexport interface TerrainWaterHere {\n readonly liquid: string\n readonly level: number\n readonly depth: number\n}\n\nexport interface TerrainRegion {\n readonly x: number\n readonly z: number\n readonly radius: number\n}\n\nexport interface TerrainColumn {\n readonly profile: string\n readonly material: string\n readonly stratum: number\n /** Metres under the untouched surface. */\n readonly depth: number\n /** Metres that can still be dug here. */\n readonly remaining: number\n readonly scorch: number\n readonly loose: number\n}\n\nexport interface TerrainStats {\n readonly marks: number\n readonly debris: number\n readonly debrisMoving: number\n readonly dirtyChunks: number\n readonly burning: number\n}\n\nexport interface TerrainChunk {\n readonly index: number\n /** First column and row of the chunk's vertices. */\n readonly column: number\n readonly row: number\n readonly cells: number\n /** True while nothing touched it and it has one profile: one flat quad draws it. */\n readonly pristine: boolean\n}\n\nexport interface Terrain {\n readonly bounds: readonly [number, number, number, number]\n readonly cellSize: number\n readonly columns: number\n readonly rows: number\n /** Vertices per row. */\n readonly stride: number\n readonly chunkCells: number\n readonly chunksX: number\n readonly chunksZ: number\n readonly budget: TerrainBudget\n /** Per vertex: metres removed under the untouched surface. */\n readonly dug: Float32Array\n /** Per vertex: metres of loose ground heaped on top. */\n readonly loose: Float32Array\n /** Per vertex: 0..1, how burnt. */\n readonly scorch: Float32Array\n /** Per vertex: how far the bare bars have given, 0 straight, 1 or more gone. */\n readonly barBend: Float32Array\n /** Per vertex: index in `profileList`. */\n readonly profileIndex: Uint8Array\n readonly profileList: readonly TerrainProfile[]\n material(id: string): TerrainMaterial\n layout(): GroundLayout\n setLayout(layout: GroundLayout): void\n /** Height at (x, z) as things stand on it. */\n heightAt(x: number, z: number): number\n /**\n * `heightAt` over a grid, in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what `heightAt` answers there (the same cell, blend and\n * vertices; past the terrain, the host's `baseHeight`). For a reader of many points on a lattice (a physics engine's ground tile), which saves a call per point.\n * Not reentrant: it keeps its scratch between calls, so a `baseHeight` must not call it back.\n */\n heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void\n /**\n * The vertex heights under a rectangle (the cells `heightGrid` reads for any point in it), as plain numbers a worker can read the ground from (`heightPatchGrid`, to the\n * bit what `heightGrid` answers there); null when the rectangle is not wholly inside the terrain (past it the host's `baseHeight` answers). Writes into `into` when it is\n * long enough, else a new array. A 2.4 m square at 10 cm cells is 26 x 26 numbers.\n */\n heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null\n /**\n * The lowest and the highest `heightAt` can answer over the rectangle, exact bounds (the height between vertices is a blend of the four around it, so no\n * point is under the lowest or over the highest vertex of the cells the rectangle covers); null when the rectangle is not wholly inside the terrain, where the ground is the\n * host's `baseHeight` and no bound is known. Costs the vertices the rectangle covers, not a read per sample.\n */\n heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { readonly low: number; readonly high: number } | null\n /** Height of vertex (column, row). */\n vertexHeight(column: number, row: number): number\n /** Material exposed at a vertex. */\n vertexMaterial(column: number, row: number): TerrainMaterial\n columnAt(x: number, z: number): TerrainColumn\n /** The rolling resistance (`TerrainMaterial.rolling`) of the material exposed at (x, z), as `columnAt` reads it, without building the column; undefined: the host's default. */\n rollingAt(x: number, z: number): number | undefined\n /** The rolling damping (`TerrainMaterial.rollingDamping`) of the material exposed at (x, z), read as `rollingAt`; undefined: the host's default. */\n rollingDampingAt(x: number, z: number): number | undefined\n contains(x: number, z: number): boolean\n /** First point of the ground along a ray, or null. */\n raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null\n /** A blow at (x, z). `energy` in joules, `direction` where it travels (it throws the pieces back along it). */\n strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult\n /**\n * Opens a pit in the ground as it stands now (a shaft a blast threw its cover off): the same dig as an excavation of the layout, never less deep than the ground already is there, and\n * no ground loss. The layout is left alone, so the next `reset` closes it with the craters.\n */\n open(excavation: GroundExcavation): void\n /** A shovelful at (x, z): takes the earth down through what a shovel digs, stops at what it does not (concrete, rock), heaps it at `dump`. */\n dig(spec: TerrainDig): TerrainDigResult\n /** Earth thrown back from a heap into a hole: fills what was dug first, then heaps. Returns the cubic metres moved. */\n fill(spec: TerrainFill): number\n /** A flame over a disc for `seconds`. */\n burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void\n /** Applies a world hit (`Hit` of the destruction contract); null when it does nothing to the ground. */\n applyHit(hit: Hit): TerrainBlowResult | null\n /** What stands still on the ground now. Where it stands over bare bars they sag under it, and past what they hold they give way; a slab over a void then opens. True when it opened. */\n bear(loads: readonly TerrainLoad[]): boolean\n /** How much ground is missing under the disc (x, z, radius), measured from the untouched surface. */\n voidUnder(x: number, z: number, radius: number): TerrainVoid\n /** Height a foot stands at: the ground less what it sinks in. */\n footAt(x: number, z: number): number\n /** What is left of the walking speed here, 0..1. */\n walkFactorAt(x: number, z: number): number\n /** The water standing here, or null. */\n waterAt(x: number, z: number): TerrainWaterHere | null\n /** A foot or a wheel on the ground: it leaves its print where the ground keeps one, a ripple in water. False where it leaves nothing. */\n press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean\n /** Rings on the water at (x, z). */\n ripple(x: number, z: number, radius: number): void\n decals(): readonly TerrainDecal[]\n /** Goes up when the decals change. */\n readonly decalsVersion: number\n /** Follow the ground changing: `region` is the disc it changed in. What rests there has lost its support and must look again. Returns the unsubscribe function. */\n onDeform(listener: (region: TerrainRegion) => void): () => void\n /** Moves the pieces, the sliding ground and the fire. */\n update(dt: number): void\n /** Chunks waiting to be redrawn; every chunk at once means the floor was just laid anew (a layout, a reset). */\n readonly dirtyChunkCount: number\n /** Takes up to the budget's chunks that changed since the last call. */\n drainDirtyChunks(max?: number): TerrainChunk[]\n chunk(index: number): TerrainChunk\n marks(): readonly TerrainMark[]\n cracks(): readonly TerrainCrack[]\n /** Changes whenever a crack is added or grows, so a renderer redraws only then. */\n readonly cracksVersion: number\n debris(): readonly TerrainDebris[]\n /** Cells on fire now, as world points. */\n burningPoints(): readonly (readonly [number, number])[]\n /** Goes up when the marks change. */\n readonly marksVersion: number\n stats(): TerrainStats\n /** Back to the untouched ground. */\n reset(): void\n serialize(): TerrainSnapshot\n load(snapshot: TerrainSnapshot): void\n}\n\nexport interface TerrainSnapshot {\n readonly layout: GroundLayout\n readonly dug: readonly (readonly [number, number])[]\n readonly loose: readonly (readonly [number, number])[]\n readonly scorch: readonly (readonly [number, number])[]\n readonly barBend?: readonly (readonly [number, number])[]\n readonly marks: readonly TerrainMark[]\n readonly cracks?: readonly TerrainCrack[]\n readonly decals?: readonly TerrainDecal[]\n}\n","import type { Terrain } from './types'\n\nconst STRIDE = 0.72\nconst FOOT_LENGTH = 0.15\nconst FOOT_APART = 0.11\n\nexport interface Footprints {\n /** Call as the walker moves; it leaves a print each stride, left and right in turn. */\n update(x: number, z: number): void\n reset(): void\n}\n\n/** The trail of something walking: whoever moves on the ground reports where it is, and the ground keeps the prints it can keep. */\nexport function createFootprints(terrain: Terrain, options: { readonly stride?: number; readonly footLength?: number } = {}): Footprints {\n const stride = options.stride ?? STRIDE\n const footLength = options.footLength ?? FOOT_LENGTH\n let lastX: number | null = null\n let lastZ = 0\n let side = 1\n return {\n update(x, z) {\n if (lastX === null) {\n lastX = x\n lastZ = z\n return\n }\n const dx = x - lastX\n const dz = z - lastZ\n const walked = Math.hypot(dx, dz)\n if (walked < stride) return\n lastX = x\n lastZ = z\n // a jump of many strides is a teleport, not a walk\n if (walked > stride * 3) return\n const angle = Math.atan2(dx, dz)\n side = -side\n terrain.press({ x: x + (Math.cos(angle) * FOOT_APART * side), z: z - (Math.sin(angle) * FOOT_APART * side), radius: footLength, angle })\n },\n reset() {\n lastX = null\n },\n }\n}\n","const GRAVITY = 9.81\n/** Per second, the share of a body's speed water takes when it is all under: a body in water bobs once and stops, it does not bounce. */\nconst WATER_DRAG = 9\n/** The liquid does not throw a very light body out: past this many times its weight the push has nothing more to give. */\nconst MAX_LIFT_WEIGHTS = 1.6\n\nexport interface WaterLiftParams {\n /** Kilograms. */\n readonly mass: number\n /** Cubic metres of the whole body. */\n readonly volume: number\n /** Share of the body under the surface, 0..1. */\n readonly submerged: number\n /** Kilograms per cubic metre of the liquid. */\n readonly liquidDensity?: number\n readonly gravity?: number\n}\n\nexport interface WaterLift {\n /** Upward metres per second squared the liquid gives the body. */\n readonly acceleration: number\n /** Per second, the part of the speed the liquid takes. */\n readonly drag: number\n /** Lighter than the liquid it displaces. */\n readonly floats: boolean\n}\n\n/** Archimedes on a body in a liquid: what it displaces lifts it, so a light log floats and a concrete block goes to the bed. */\nexport function waterLift(params: WaterLiftParams): WaterLift {\n const density = params.liquidDensity ?? 1000\n const submerged = Math.max(0, Math.min(1, params.submerged))\n const mass = Math.max(1e-6, params.mass)\n const gravity = params.gravity ?? GRAVITY\n return {\n acceleration: Math.min(MAX_LIFT_WEIGHTS * gravity, (density * params.volume * submerged * gravity) / mass),\n drag: WATER_DRAG * submerged,\n floats: mass / Math.max(1e-9, params.volume) < density,\n }\n}\n","import type * as THREE_NS from 'three'\nimport { TERRAIN_PATTERNS } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\n/** Index of a pattern in the shader's branches. */\nexport const patternIndex = (pattern: string | undefined): number => Math.max(0, TERRAIN_PATTERNS.indexOf((pattern ?? 'plain') as (typeof TERRAIN_PATTERNS)[number]))\n\nconst SURFACE_GLSL = /* glsl */ `\nfloat tsHash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\nfloat tsNoise(vec2 p) {\n vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);\n return mix(mix(tsHash(i), tsHash(i + vec2(1.0, 0.0)), f.x), mix(tsHash(i + vec2(0.0, 1.0)), tsHash(i + vec2(1.0, 1.0)), f.x), f.y);\n}\nfloat tsFbm(vec2 p) { return tsNoise(p) * 0.55 + tsNoise(p * 2.3 + 7.1) * 0.3 + tsNoise(p * 5.1 + 3.3) * 0.15; }\n// a pixel wider than FAR_PIXEL_TO metres shows only the average of the pattern, PATTERN_MEAN of the base colour\nconst float FAR_PIXEL_FROM = 0.03;\nconst float FAR_PIXEL_TO = 0.12;\nconst float PATTERN_MEAN = 0.92;\n// metres one pixel covers on the ground here: a line or a grain finer than that cannot be drawn, only its average can\nfloat tsPixel = 0.0;\nfloat tsLine(float value, float period, float width) {\n float drawn = max(width, tsPixel);\n float d = abs(fract(value / period + 0.5) - 0.5) * period;\n return (1.0 - smoothstep(drawn * 0.6, drawn, d)) * (width / drawn);\n}\nvec3 terrainPattern(vec3 base, vec2 xz, float kind) {\n float k = floor(kind + 0.5);\n if (k < 0.5) return base * (0.86 + 0.28 * tsFbm(xz * 9.0));\n if (k < 1.5) {\n float blades = tsNoise(xz * vec2(70.0, 55.0)) * 0.6 + tsNoise(xz * 22.0) * 0.4;\n float patches = tsFbm(xz * 1.3);\n return base * (0.55 + 0.8 * blades) * mix(vec3(1.25, 1.05, 0.7), vec3(0.8, 1.1, 0.85), patches);\n }\n if (k < 2.5) return base * (0.6 + 0.75 * tsFbm(xz * 6.0)) * (0.82 + 0.36 * tsNoise(xz * 48.0));\n if (k < 3.5) return base * (0.88 + 0.12 * sin(xz.x * 22.0 + tsFbm(xz * 2.0) * 9.0)) * (0.92 + 0.16 * tsNoise(xz * 90.0));\n if (k < 4.5) { float grain = tsNoise(xz * 120.0); return base * (0.55 + 1.1 * grain * grain) * (0.85 + 0.3 * tsFbm(xz * 0.8)); }\n if (k < 5.5) {\n float joint = max(tsLine(xz.x, 3.0, 0.012), tsLine(xz.y, 3.0, 0.012));\n return base * (0.82 + 0.3 * tsFbm(xz * 3.5)) * (0.94 + 0.12 * tsNoise(xz * 130.0)) * (1.0 - 0.6 * joint);\n }\n if (k < 6.5) {\n vec2 cell = floor(xz / 0.6);\n float grout = max(tsLine(xz.x, 0.6, 0.006), tsLine(xz.y, 0.6, 0.006));\n return mix(base * (0.93 + 0.14 * tsHash(cell)) * (0.97 + 0.06 * tsFbm(xz * 7.0)), vec3(0.14, 0.13, 0.12), grout);\n }\n if (k < 7.5) {\n float row = floor(xz.y / 0.14);\n float along = xz.x + tsHash(vec2(row, 3.0)) * 2.4;\n float seam = max(tsLine(xz.y, 0.14, 0.004), tsLine(along, 2.4, 0.004));\n float grain = tsNoise(vec2(along * 3.0, xz.y * 70.0)) * 0.6 + tsNoise(vec2(along * 11.0, xz.y * 180.0)) * 0.4;\n return base * (0.72 + 0.56 * tsHash(vec2(row, floor(along / 2.4)))) * (0.75 + 0.5 * grain) * (1.0 - 0.75 * seam);\n }\n if (k < 8.5) {\n vec2 cell = floor(xz / 0.22);\n float seams = max(tsLine(xz.x, 0.22, 0.012), tsLine(xz.y, 0.22, 0.012));\n return base * (0.7 + 0.6 * tsHash(cell)) * (0.85 + 0.3 * tsFbm(xz * 16.0)) * (1.0 - 0.55 * seams);\n }\n if (k < 9.5) {\n float wet = smoothstep(0.42, 0.62, tsFbm(xz * 2.6));\n return base * (0.65 + 0.7 * tsFbm(xz * 11.0)) * mix(1.25, 0.55, wet);\n }\n if (k < 10.5) {\n vec2 grid = xz / 0.045;\n vec2 cell = floor(grid);\n vec2 inside = fract(grid) - 0.5 + (vec2(tsHash(cell), tsHash(cell + 9.0)) - 0.5) * 0.5;\n float stone = 1.0 - smoothstep(0.22, 0.5, length(inside));\n return base * (0.45 + 1.15 * tsHash(cell + 4.0)) * (0.35 + 0.85 * stone);\n }\n if (k < 11.5) {\n vec2 p = xz / 0.45 + (vec2(tsNoise(xz * 3.0), tsNoise(xz * 3.0 + 5.0)) - 0.5) * 0.7;\n vec2 cell = floor(p);\n float nearest = 8.0;\n float second = 8.0;\n for (int j = -1; j <= 1; j++) {\n for (int i = -1; i <= 1; i++) {\n vec2 other = cell + vec2(float(i), float(j));\n vec2 at = other + vec2(tsHash(other), tsHash(other + 3.0));\n float d = length(at - p);\n if (d < nearest) { second = nearest; nearest = d; } else if (d < second) second = d;\n }\n }\n float crack = 1.0 - smoothstep(0.0, 0.06, second - nearest);\n return base * (0.82 + 0.3 * tsFbm(xz * 9.0)) * (1.0 - 0.78 * crack);\n }\n if (k < 12.5) return min(base * (0.97 + 0.08 * tsFbm(xz * 1.8)) + 0.05 * tsNoise(xz * 140.0), vec3(1.0));\n if (k < 13.5) {\n float row = floor(xz.y / 0.2);\n float along = xz.x - mod(abs(row), 2.0) * 0.1;\n vec2 cell = vec2(floor(along / 0.3), row);\n float seam = max(tsLine(xz.y, 0.2, 0.014), tsLine(along, 0.3, 0.014));\n return base * (0.72 + 0.6 * tsHash(cell)) * (0.82 + 0.36 * tsFbm(xz * 22.0)) * (1.0 - 0.8 * seam);\n }\n if (k < 14.5) {\n float row = floor(xz.y / 0.2);\n float along = xz.x - mod(abs(row), 2.0) * 0.1;\n vec2 cell = vec2(floor(along / 0.2), row);\n float seam = max(tsLine(xz.y, 0.2, 0.008), tsLine(along, 0.2, 0.008));\n return base * (0.86 + 0.26 * tsHash(cell)) * (0.92 + 0.16 * tsNoise(xz * 70.0)) * (1.0 - 0.7 * seam);\n }\n // bare rock: weathered blotches, lichen-dark patches and a few long joints, no grid\n float blotch = tsFbm(xz * 0.9) * 0.6 + tsFbm(xz * 4.0 + 2.0) * 0.4;\n float joint = 1.0 - smoothstep(0.0, 0.035, abs(tsNoise(xz * vec2(0.7, 1.9)) - 0.5));\n float grain = tsNoise(xz * 95.0);\n return base * (0.62 + 0.75 * blotch) * (0.88 + 0.24 * grain) * (1.0 - 0.6 * joint);\n}\n/** The pattern where a pixel can hold it; far off, where a pixel covers more ground than the finest grain, its average, so that the grain does not sparkle as dots. */\nvec3 terrainSurface(vec3 base, vec2 xz, float kind) {\n tsPixel = max(length(dFdx(xz)), length(dFdy(xz)));\n vec3 near = terrainPattern(base, xz, kind);\n return mix(near, base * PATTERN_MEAN, smoothstep(FAR_PIXEL_FROM, FAR_PIXEL_TO, tsPixel));\n}\n`\n\n/** The ground's material: the colour of what is exposed comes per vertex, flat so that the edge between two materials stays sharp, its pattern (blades of grass, grout, planks) is drawn per pixel from the world position so that it never tiles or stretches. */\nexport function createSurfaceMaterial(THREE: ThreeLib): THREE_NS.MeshStandardMaterial {\n const material = new THREE.MeshStandardMaterial({ roughness: 0.95, metalness: 0 })\n material.onBeforeCompile = (shader) => {\n shader.vertexShader = shader.vertexShader\n .replace('#include <common>', '#include <common>\\nattribute float aPattern;\\nattribute vec3 aBase;\\nattribute vec2 aShade;\\nflat varying float vPattern;\\nflat varying vec3 vBase;\\nvarying vec2 vShade;\\nvarying vec2 vGroundXZ;')\n .replace('#include <begin_vertex>', '#include <begin_vertex>\\nvPattern = aPattern;\\nvBase = aBase;\\nvShade = aShade;\\nvGroundXZ = position.xz;')\n shader.fragmentShader = shader.fragmentShader\n .replace('#include <common>', `#include <common>\\nflat varying float vPattern;\\nflat varying vec3 vBase;\\nvarying vec2 vShade;\\nvarying vec2 vGroundXZ;\\n${SURFACE_GLSL}`)\n .replace('#include <color_fragment>', '#include <color_fragment>\\ndiffuseColor.rgb = mix(terrainSurface(vBase, vGroundXZ, vPattern), vec3(0.012, 0.011, 0.01), vShade.y) * vShade.x;')\n }\n material.customProgramCacheKey = () => 'game-terrain-surface'\n return material\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\nimport { patternIndex } from './surface-material'\n\ntype ThreeLib = typeof THREE_NS\n\n/** Metres over which the raw colour of a dug layer darkens: the bottom of a hole gets little light. */\nconst DEPTH_SHADE = 1.6\nconst MIN_DEPTH_LIGHT = 0.55\nconst LOOSE_VISIBLE = 0.004\n/** A skin thinner than this (turf, asphalt) is not what comes out of a hole: what is under it is. */\nconst THIN_SKIN = 0.1\nconst SKIRT_QUADS = 4\nconst BROKEN_DEPTH = 0.004\nconst BROKEN_TONE = 0.62\n\n/** What a vertex shows: the colour and pattern of what is exposed or heaped on it, sharp at the edge between materials, and its light and burn, which blend. */\nfunction vertexLook(terrain: Terrain, column: number, row: number, base: [number, number, number], shade: [number, number]): number {\n const index = row * terrain.stride + column\n let material = terrain.vertexMaterial(column, row)\n if (terrain.loose[index]! > LOOSE_VISIBLE) {\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const first = profile.strata[0]!\n material = terrain.material(first.thickness < THIN_SKIN && profile.strata[1] ? profile.strata[1].material : first.material)\n }\n // dug concrete shows its broken aggregate, not the troweled surface with its joints\n const broken = material.pattern === 'concrete' && terrain.dug[index]! > BROKEN_DEPTH\n const tone = broken ? BROKEN_TONE : 1\n base[0] = material.color[0] * tone\n base[1] = material.color[1] * tone\n base[2] = material.color[2] * tone\n shade[0] = Math.max(MIN_DEPTH_LIGHT, 1 - terrain.dug[index]! / DEPTH_SHADE)\n shade[1] = terrain.scorch[index]!\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const untouched = profile.surfacePattern !== undefined && terrain.dug[index]! <= BROKEN_DEPTH && terrain.loose[index]! <= LOOSE_VISIBLE\n return patternIndex(broken ? 'soil' : untouched ? profile.surfacePattern : material.pattern)\n}\n\n/** How many vertices `buildChunkGeometry` gives the chunk at this step: a geometry of that many can be refilled for it. */\nexport function chunkVertexCount(terrain: Terrain, chunk: TerrainChunk, step: number): number {\n const lastColumn = Math.min(terrain.columns, chunk.column + chunk.cells)\n const lastRow = Math.min(terrain.rows, chunk.row + chunk.cells)\n return (Math.ceil((lastColumn - chunk.column) / step) + 1) * (Math.ceil((lastRow - chunk.row) / step) + 1)\n}\n\nfunction attributeArray(geometry: THREE_NS.BufferGeometry, name: string): Float32Array {\n return geometry.getAttribute(name).array as Float32Array\n}\n\nfunction refreshAttributes(geometry: THREE_NS.BufferGeometry, names: readonly string[]): void {\n for (const name of names) geometry.getAttribute(name).needsUpdate = true\n geometry.boundingSphere = null\n geometry.boundingBox = null\n}\n\nconst LOOK_ATTRIBUTES = ['position', 'normal', 'aBase', 'aShade', 'aPattern'] as const\n\n/**\n * The chunk as a grid with one vertex every `step` cells; the normals come from the height field, so that neighbouring chunks meet without a seam. Given a `reuse` geometry\n * with the right vertex count (`chunkVertexCount`) it writes into that one's buffers instead of making new ones, so a crater costs no GPU allocation.\n */\nexport function buildChunkGeometry(THREE: ThreeLib, terrain: Terrain, chunk: TerrainChunk, step: number, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows } = terrain\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const across = Math.ceil((lastColumn - chunk.column) / step) + 1\n const down = Math.ceil((lastRow - chunk.row) / step) + 1\n const target = reuse && reuse.getAttribute('position').count === across * down ? reuse : undefined\n const positions = target ? attributeArray(target, 'position') : new Float32Array(across * down * 3)\n const normals = target ? attributeArray(target, 'normal') : new Float32Array(across * down * 3)\n const bases = target ? attributeArray(target, 'aBase') : new Float32Array(across * down * 3)\n const shades = target ? attributeArray(target, 'aShade') : new Float32Array(across * down * 2)\n const patterns = target ? attributeArray(target, 'aPattern') : new Float32Array(across * down)\n const base: [number, number, number] = [0, 0, 0]\n const shade: [number, number] = [1, 0]\n let at = 0\n for (let j = 0; j < down; j++) {\n const row = Math.min(lastRow, chunk.row + j * step)\n for (let i = 0; i < across; i++) {\n const column = Math.min(lastColumn, chunk.column + i * step)\n const height = terrain.vertexHeight(column, row)\n positions[at * 3] = x0 + column * cellSize\n positions[at * 3 + 1] = height\n positions[at * 3 + 2] = z0 + row * cellSize\n const left = terrain.vertexHeight(Math.max(0, column - 1), row)\n const right = terrain.vertexHeight(Math.min(columns, column + 1), row)\n const back = terrain.vertexHeight(column, Math.max(0, row - 1))\n const front = terrain.vertexHeight(column, Math.min(rows, row + 1))\n const nx = left - right\n const ny = 2 * cellSize\n const nz = back - front\n const length = Math.hypot(nx, ny, nz)\n normals[at * 3] = nx / length\n normals[at * 3 + 1] = ny / length\n normals[at * 3 + 2] = nz / length\n patterns[at] = vertexLook(terrain, column, row, base, shade)\n bases.set(base, at * 3)\n shades.set(shade, at * 2)\n at++\n }\n }\n if (target) {\n refreshAttributes(target, LOOK_ATTRIBUTES)\n return target\n }\n const indices = new Uint32Array((across - 1) * (down - 1) * 6)\n let cursor = 0\n for (let j = 0; j < down - 1; j++) {\n for (let i = 0; i < across - 1; i++) {\n const a = j * across + i\n const b = a + 1\n const c = a + across\n const d = c + 1\n indices[cursor++] = a\n indices[cursor++] = c\n indices[cursor++] = b\n // both triangles end on `b`: a flat attribute takes the last vertex, so the whole quad has one material and the edge between two is a straight line\n indices[cursor++] = c\n indices[cursor++] = d\n indices[cursor++] = b\n }\n }\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setAttribute('aBase', new THREE.BufferAttribute(bases, 3))\n geometry.setAttribute('aShade', new THREE.BufferAttribute(shades, 2))\n geometry.setAttribute('aPattern', new THREE.BufferAttribute(patterns, 1))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n return geometry\n}\n\n/**\n * Every chunk nothing touched, as one flat quad each in one geometry: the whole floor of an arena is a single draw call until someone digs it. Around them, out to `skirt` metres, the\n * ground goes on as the same surface: what is thrown past the edge lands on something, not on the sky.\n */\nexport function buildPristineGeometry(THREE: ThreeLib, terrain: Terrain, chunks: readonly TerrainChunk[], skirt: number, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows } = terrain\n const [, , x1, z1] = terrain.bounds\n const quads = chunks.length + SKIRT_QUADS\n // room for every chunk, so the same buffers serve however many are still untouched\n const capacity = terrain.chunksX * terrain.chunksZ + SKIRT_QUADS\n const target = reuse && reuse.getAttribute('position').count === capacity * 4 ? reuse : undefined\n const positions = target ? attributeArray(target, 'position') : new Float32Array(capacity * 12)\n const normals = target ? attributeArray(target, 'normal') : new Float32Array(capacity * 12)\n const bases = target ? attributeArray(target, 'aBase') : new Float32Array(capacity * 12)\n const shades = target ? attributeArray(target, 'aShade') : new Float32Array(capacity * 8)\n const patterns = target ? attributeArray(target, 'aPattern') : new Float32Array(capacity * 4)\n const indices = target ? (target.getIndex()!.array as Uint32Array) : new Uint32Array(capacity * 6)\n const base: [number, number, number] = [0, 0, 0]\n const shade: [number, number] = [1, 0]\n chunks.forEach((chunk, n) => {\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const corners = [[chunk.column, chunk.row], [lastColumn, chunk.row], [chunk.column, lastRow], [lastColumn, lastRow]] as const\n const pattern = vertexLook(terrain, chunk.column, chunk.row, base, shade)\n corners.forEach(([column, row], corner) => {\n const at = n * 4 + corner\n positions[at * 3] = x0 + column * cellSize\n positions[at * 3 + 1] = terrain.vertexHeight(column, row)\n positions[at * 3 + 2] = z0 + row * cellSize\n normals[at * 3 + 1] = 1\n bases.set(base, at * 3)\n shades.set(shade, at * 2)\n patterns[at] = pattern\n })\n const first = n * 4\n indices.set([first, first + 2, first + 1, first + 2, first + 3, first + 1], n * 6)\n })\n const surface = terrain.material(terrain.profileList.find((profile) => profile.id === terrain.layout().surface)?.strata[0]?.material ?? terrain.profileList[terrain.profileIndex[0]!]!.strata[0]!.material)\n const rects = [\n [x0 - skirt, z0 - skirt, x1 + skirt, z0],\n [x0 - skirt, z1, x1 + skirt, z1 + skirt],\n [x0 - skirt, z0, x0, z1],\n [x1, z0, x1 + skirt, z1],\n ] as const\n rects.forEach(([ax, az, bx, bz], r) => {\n const n = chunks.length + r\n const corners = [[ax, az], [bx, az], [ax, bz], [bx, bz]] as const\n corners.forEach(([x, z], corner) => {\n const at = n * 4 + corner\n positions[at * 3] = x\n positions[at * 3 + 1] = 0\n positions[at * 3 + 2] = z\n normals[at * 3 + 1] = 1\n bases.set(surface.color, at * 3)\n shades[at * 2] = 1\n patterns[at] = patternIndex(surface.pattern)\n })\n const first = n * 4\n indices.set([first, first + 2, first + 1, first + 2, first + 3, first + 1], n * 6)\n })\n const geometry = target ?? new THREE.BufferGeometry()\n if (target) {\n refreshAttributes(target, LOOK_ATTRIBUTES)\n target.getIndex()!.needsUpdate = true\n } else {\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setAttribute('aBase', new THREE.BufferAttribute(bases, 3))\n geometry.setAttribute('aShade', new THREE.BufferAttribute(shades, 2))\n geometry.setAttribute('aPattern', new THREE.BufferAttribute(patterns, 1))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n }\n geometry.setDrawRange(0, quads * 6)\n return geometry\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainDecal, TerrainDecalKind } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst TEXTURE_SIZE = 128\nconst DECAL_LIFT = 0.008\nconst RIPPLE_SECONDS = 1.6\nconst CRACK_ARMS = 7\nconst DARK_GROUND_PRINT_TONE = 0.1\n/** How dark each kind is against the colour of its material: a crack is a shadow, a splat is the material itself. */\nconst KIND_TONE: Record<TerrainDecalKind, number> = { crack: 0.16, print: 0.55, rut: 0.5, splat: 1, ripple: 3 }\n/** Width over length of what it covers: a print is a sole, a rut a band. */\nconst KIND_ASPECT: Record<TerrainDecalKind, number> = { crack: 1, print: 0.55, rut: 0.5, splat: 1, ripple: 1 }\n\ntype AlphaAt = (u: number, v: number) => number\n\nconst hash = (value: number): number => {\n const raw = Math.sin(value * 91.17) * 43758.5453\n return raw - Math.floor(raw)\n}\nconst ellipse = (u: number, v: number, cu: number, cv: number, ru: number, rv: number): number => Math.hypot((u - cu) / ru, (v - cv) / rv)\n\nfunction segmentDistance(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {\n const dx = bx - ax\n const dy = by - ay\n const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))\n return Math.hypot(px - ax - dx * t, py - ay - dy * t)\n}\n\n/** Arms that leave the blow and fork on the way out. */\nfunction crackSegments(): number[][] {\n const segments: number[][] = []\n for (let arm = 0; arm < CRACK_ARMS; arm++) {\n let angle = (arm / CRACK_ARMS) * 6.283 + hash(arm) * 0.5\n let [x, y] = [0, 0]\n for (let step = 0; step < 5; step++) {\n const length = 0.075 + hash(arm * 7 + step) * 0.05\n const nextX = x + Math.cos(angle) * length\n const nextY = y + Math.sin(angle) * length\n segments.push([x, y, nextX, nextY])\n if (step > 0 && hash(arm * 13 + step) > 0.55) {\n const branch = angle + (hash(arm + step * 3) > 0.5 ? 0.7 : -0.7)\n segments.push([nextX, nextY, nextX + Math.cos(branch) * length * 0.8, nextY + Math.sin(branch) * length * 0.8])\n }\n x = nextX\n y = nextY\n angle += (hash(arm * 3 + step * 11) - 0.5) * 0.9\n }\n }\n return segments\n}\n\nconst SHAPES: Record<TerrainDecalKind, () => AlphaAt> = {\n crack() {\n const segments = crackSegments()\n return (u, v) => {\n let nearest = Infinity\n for (const [ax, ay, bx, by] of segments) nearest = Math.min(nearest, segmentDistance(u, v, ax!, ay!, bx!, by!))\n return 1 - Math.min(1, Math.max(0, (nearest - 0.004) / 0.008))\n }\n },\n print: () => (u, v) => {\n // v runs heel to toe\n const sole = ellipse(u, v, 0, 0.17, 0.42, 0.28)\n const heel = ellipse(u, v, 0, -0.27, 0.32, 0.18)\n const inside = Math.min(sole, heel)\n return inside > 1 ? 0 : 0.85 * (Math.sin(v * 70) > -0.3 ? 1 : 0.55)\n },\n rut: () => (u, v) => (Math.abs(u) > 0.46 || Math.abs(v) > 0.5 ? 0 : Math.sin(v * 44 + Math.abs(u) * 18) > -0.2 ? 0.8 : 0.45),\n splat() {\n return (u, v) => {\n const angle = Math.atan2(v, u)\n const edge = 0.3 + 0.08 * Math.sin(angle * 5) + 0.05 * Math.sin(angle * 13 + 1) + 0.04 * Math.sin(angle * 23 + 2)\n const body = 1 - Math.max(0, Math.min(1, (Math.hypot(u, v) - edge) / 0.03))\n return Math.max(body, ellipse(u, v, 0.38, 0.12, 0.05, 0.04) < 1 || ellipse(u, v, -0.22, -0.36, 0.06, 0.05) < 1 ? 1 : 0)\n }\n },\n ripple: () => (u, v) => {\n const r = Math.hypot(u, v)\n return r > 0.5 ? 0 : Math.max(0, Math.sin(r * 42)) * (1 - r * 2) ** 0.5\n },\n}\n\nfunction createAlphaTexture(THREE: ThreeLib, alphaAt: AlphaAt): THREE_NS.DataTexture {\n const size = TEXTURE_SIZE\n const data = new Uint8Array(size * size * 4)\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n const at = (y * size + x) * 4\n data[at] = data[at + 1] = data[at + 2] = 255\n data[at + 3] = Math.round(Math.max(0, Math.min(1, alphaAt((x + 0.5) / size - 0.5, (y + 0.5) / size - 0.5))) * 255)\n }\n }\n const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat)\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\nconst KINDS = Object.keys(SHAPES) as TerrainDecalKind[]\n\n/** The marks of no depth, one instanced mesh per kind so that each has its shape. */\nexport function createDecalLayers(THREE: ThreeLib, terrain: Terrain): { group: THREE_NS.Group; sync(): void; dispose(): void } {\n const group = new THREE.Group()\n group.name = 'terrain-decals'\n const geometry = new THREE.PlaneGeometry(1, 1)\n geometry.rotateX(-Math.PI / 2)\n const layers = KINDS.map((kind) => {\n const texture = createAlphaTexture(THREE, SHAPES[kind]())\n const material = new THREE.MeshStandardMaterial({ map: texture, transparent: true, depthWrite: false, roughness: kind === 'ripple' ? 0.2 : 1, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxDecals)\n mesh.name = `terrain-decal-${kind}`\n mesh.count = 0\n mesh.frustumCulled = false\n mesh.receiveShadow = true\n mesh.renderOrder = 2\n group.add(mesh)\n return { kind, mesh, material, texture }\n })\n const matrix = new THREE.Matrix4()\n const rotation = new THREE.Matrix4()\n const scale = new THREE.Matrix4()\n const colour = new THREE.Color()\n let seen = -1\n\n const place = (decal: TerrainDecal): boolean => {\n const water = terrain.waterAt(decal.x, decal.z)\n const grow = decal.kind === 'ripple' ? 0.5 + (decal.age / RIPPLE_SECONDS) * 1.5 : 1\n const size = decal.radius * 2 * grow\n rotation.makeRotationY(decal.angle)\n scale.makeScale(size * KIND_ASPECT[decal.kind], 1, size)\n matrix.multiplyMatrices(rotation, scale)\n matrix.setPosition(decal.x, (decal.kind === 'ripple' ? (water?.level ?? terrain.heightAt(decal.x, decal.z)) : terrain.heightAt(decal.x, decal.z)) + DECAL_LIFT, decal.z)\n return true\n }\n\n return {\n group,\n sync() {\n const decals = terrain.decals()\n const rippling = decals.some((decal) => decal.kind === 'ripple')\n if (seen === terrain.decalsVersion && !rippling) return\n seen = terrain.decalsVersion\n for (const layer of layers) {\n let count = 0\n for (const decal of decals) {\n if (decal.kind !== layer.kind || !place(decal)) continue\n layer.mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(decal.material).color\n const fade = decal.kind === 'ripple' ? Math.max(0, 1 - decal.age / RIPPLE_SECONDS) : 1\n // a print is a shadow: on a pale ground it greys, on a dark one it has to go nearly black to show\n const tone = (decal.kind === 'print' || decal.kind === 'rut') && r < 0.5 ? DARK_GROUND_PRINT_TONE : KIND_TONE[decal.kind]\n layer.mesh.setColorAt(count, colour.setRGB(Math.min(1, r * tone + (decal.kind === 'ripple' ? 0.5 : 0)) * fade, Math.min(1, g * tone + (decal.kind === 'ripple' ? 0.55 : 0)) * fade, Math.min(1, b * tone + (decal.kind === 'ripple' ? 0.6 : 0)) * fade))\n count++\n }\n layer.mesh.count = count\n layer.mesh.instanceMatrix.needsUpdate = true\n if (layer.mesh.instanceColor) layer.mesh.instanceColor.needsUpdate = true\n }\n },\n dispose() {\n geometry.dispose()\n for (const layer of layers) {\n layer.material.dispose()\n layer.texture.dispose()\n }\n group.removeFromParent()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport { crackLines } from '@adatechnology/game-terrain'\nimport type { Terrain, TerrainDebrisKind } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst MARK_LIFT = 0.006\nconst MARK_REACH = 1.5\nconst MARK_TEXTURE_SIZE = 64\nconst MARK_DARKEN = 0.85\n/** How a piece of each kind is stretched: a shard is a flake, a splinter a long sliver. */\nconst PIECE_SHAPE: Record<TerrainDebrisKind, readonly [number, number, number]> = { clods: [1, 0.85, 1], chips: [1, 0.6, 0.8], shards: [1.3, 0.2, 1], splinters: [0.3, 0.25, 2.4], dust: [1, 0.8, 1], blocks: [1, 0.42, 0.65] }\n\n/** A pock as an alpha disc: dark in the middle, a broken lighter ring where the surface chipped. */\nfunction createMarkTexture(THREE: ThreeLib): THREE_NS.DataTexture {\n const size = MARK_TEXTURE_SIZE\n const data = new Uint8Array(size * size * 4)\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n const u = (x + 0.5) / size - 0.5\n const v = (y + 0.5) / size - 0.5\n const angle = Math.atan2(v, u)\n const lobes = 0.86 + 0.09 * Math.sin(angle * 5) + 0.05 * Math.sin(angle * 13 + 1)\n const q = Math.hypot(u, v) / (0.5 * lobes)\n const shade = q < 0.55 ? 0.42 + q * 0.5 : 0.7 + (q - 0.55) * 0.8\n const at = (y * size + x) * 4\n data[at] = data[at + 1] = data[at + 2] = Math.round(Math.min(1, shade) * 255)\n data[at + 3] = q < 0.8 ? 255 : q < 1 ? Math.round((1 - (q - 0.8) / 0.2) * 255) : 0\n }\n }\n const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat)\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\nexport function createMarkLayer(THREE: ThreeLib, terrain: Terrain, drawDistance: number): { mesh: THREE_NS.InstancedMesh; sync(camera: { x: number; z: number }): void; dispose(): void } {\n const geometry = new THREE.PlaneGeometry(1, 1)\n geometry.rotateX(-Math.PI / 2)\n const texture = createMarkTexture(THREE)\n const material = new THREE.MeshStandardMaterial({ map: texture, transparent: true, depthWrite: false, roughness: 1, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxMarks)\n mesh.name = 'terrain-marks'\n mesh.count = 0\n mesh.frustumCulled = false\n mesh.receiveShadow = true\n mesh.renderOrder = 1\n // the colour attribute is part of the program key: made on the first mark it would link the program in the middle of the game\n mesh.setColorAt(0, new THREE.Color(1, 1, 1))\n const matrix = new THREE.Matrix4()\n const rotation = new THREE.Matrix4()\n const scale = new THREE.Matrix4()\n const colour = new THREE.Color()\n let seen = ''\n let cameraX = Infinity\n let cameraZ = Infinity\n return {\n mesh,\n sync(camera) {\n const marks = terrain.marks()\n let blows = 0\n for (const mark of marks) blows += mark.count\n const stamp = `${terrain.marksVersion}:${blows}`\n if (stamp === seen && Math.hypot(camera.x - cameraX, camera.z - cameraZ) < 5) return\n seen = stamp\n cameraX = camera.x\n cameraZ = camera.z\n let count = 0\n for (const mark of marks) {\n if (Math.hypot(mark.x - camera.x, mark.z - camera.z) > drawDistance) continue\n const size = mark.radius * 2 * MARK_REACH\n rotation.makeRotationY(mark.id * 2.399)\n scale.makeScale(size, 1, size)\n matrix.multiplyMatrices(rotation, scale)\n matrix.setPosition(mark.x, terrain.heightAt(mark.x, mark.z) + MARK_LIFT, mark.z)\n mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(mark.material).color\n colour.setRGB(r * MARK_DARKEN + 0.04, g * MARK_DARKEN + 0.04, b * MARK_DARKEN + 0.04)\n mesh.setColorAt(count, colour)\n count++\n }\n mesh.count = count\n mesh.instanceMatrix.needsUpdate = true\n if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n },\n dispose() {\n geometry.dispose()\n material.dispose()\n texture.dispose()\n mesh.removeFromParent()\n },\n }\n}\n\nexport function createDebrisLayer(THREE: ThreeLib, terrain: Terrain): { mesh: THREE_NS.InstancedMesh; sync(): void; dispose(): void } {\n const geometry = new THREE.IcosahedronGeometry(1, 0)\n const material = new THREE.MeshStandardMaterial({ roughness: 0.95, flatShading: true })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxDebris)\n mesh.name = 'terrain-debris'\n mesh.count = 0\n mesh.castShadow = true\n mesh.frustumCulled = false\n mesh.setColorAt(0, new THREE.Color(1, 1, 1))\n const matrix = new THREE.Matrix4()\n const position = new THREE.Vector3()\n const scale = new THREE.Vector3()\n const quaternion = new THREE.Quaternion()\n const euler = new THREE.Euler()\n const colour = new THREE.Color()\n return {\n mesh,\n sync() {\n const pieces = terrain.debris()\n let count = 0\n for (const piece of pieces) {\n const [x, y, z] = piece.position\n // the turn follows the distance travelled, so that a piece at rest stays as it landed\n const travelled = x * 1.7 + z * 1.3 + y\n euler.set(piece.spin[0] * travelled * 0.2 + piece.id, piece.spin[1] * travelled * 0.2, piece.spin[2] * travelled * 0.2)\n const shape = PIECE_SHAPE[piece.kind]\n scale.set(shape[0] * piece.radius, shape[1] * piece.radius, shape[2] * piece.radius)\n matrix.compose(position.set(x, y, z), quaternion.setFromEuler(euler), scale)\n mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(piece.material).color\n const tone = 0.85 + ((piece.id * 37) % 30) / 100\n mesh.setColorAt(count, colour.setRGB(r * tone, g * tone, b * tone))\n count++\n }\n mesh.count = count\n mesh.instanceMatrix.needsUpdate = true\n if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n },\n dispose() {\n geometry.dispose()\n material.dispose()\n mesh.removeFromParent()\n },\n }\n}\n\nconst CRACK_LIFT = 0.004\n/** Quads all the cracks of the terrain can take at once; past it the farthest stars are left out. */\nconst MAX_CRACK_QUADS = 8192\n/** A crack shows the material's own colour, much darker: the shadow inside the line. */\nconst CRACK_SHADE = 0.22\n/** Under this luminance a surface is dark (asphalt) and its cracks are drawn lighter than it. */\nconst DARK_SURFACE = 0.1\nconst DUST_LIFT = 2\nconst DUST_GREY = 0.12\n\n/**\n * The cracks of rigid ground (`Terrain.cracks`) as thin ribbons on the surface, wide at the point and thin at the tips, in one draw call. The geometry is rebuilt only when a crack\n * is added or grows, or the ground under them moves, never per frame.\n */\nexport function createCrackLayer(THREE: ThreeLib, terrain: Terrain): { mesh: THREE_NS.Mesh; sync(): void; dispose(): void } {\n const positions = new Float32Array(MAX_CRACK_QUADS * 4 * 3)\n const colours = new Float32Array(MAX_CRACK_QUADS * 4 * 3)\n const indices = new Uint32Array(MAX_CRACK_QUADS * 6)\n for (let quad = 0; quad < MAX_CRACK_QUADS; quad++) {\n const first = quad * 4\n indices.set([first, first + 2, first + 1, first + 1, first + 2, first + 3], quad * 6)\n }\n const geometry = new THREE.BufferGeometry()\n const position = new THREE.BufferAttribute(positions, 3)\n const colour = new THREE.BufferAttribute(colours, 3)\n position.setUsage(THREE.DynamicDrawUsage)\n colour.setUsage(THREE.DynamicDrawUsage)\n geometry.setAttribute('position', position)\n geometry.setAttribute('color', colour)\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n geometry.setDrawRange(0, 0)\n const material = new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.9, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 })\n const mesh = new THREE.Mesh(geometry, material)\n mesh.name = 'terrain-cracks'\n mesh.frustumCulled = false\n mesh.renderOrder = 2\n let seen = -1\n let groundMoved = false\n const stopListening = terrain.onDeform(() => {\n groundMoved = true\n })\n const lift = (x: number, z: number): number => terrain.heightAt(x, z) + CRACK_LIFT\n return {\n mesh,\n sync() {\n const cracks = terrain.cracks()\n if (seen === terrain.cracksVersion && !(groundMoved && cracks.length > 0)) return\n seen = terrain.cracksVersion\n groundMoved = false\n let quad = 0\n // the newest first: when the buffer is full, it is the old hairlines that go unseen\n for (let n = cracks.length - 1; n >= 0 && quad < MAX_CRACK_QUADS; n--) {\n const crack = cracks[n]!\n const tone = terrain.material(crack.material).color\n // on a dark surface (asphalt) a crack reads by the grey dust of the broken binder at its lips, not by a shadow darker than black\n const dark = tone[0] * 0.3 + tone[1] * 0.59 + tone[2] * 0.11 < DARK_SURFACE\n const k = dark ? DUST_LIFT : CRACK_SHADE\n const r = dark ? Math.min(1, tone[0] * k + DUST_GREY) : tone[0] * k\n const g = dark ? Math.min(1, tone[1] * k + DUST_GREY) : tone[1] * k\n const b = dark ? Math.min(1, tone[2] * k + DUST_GREY) : tone[2] * k\n for (const s of crackLines(crack)) {\n if (quad >= MAX_CRACK_QUADS) break\n if (!terrain.contains(s.x0, s.z0) || !terrain.contains(s.x1, s.z1)) continue\n const length = Math.hypot(s.x1 - s.x0, s.z1 - s.z0)\n if (length < 1e-5) continue\n // across the line, half the width each side\n const ax = -(s.z1 - s.z0) / length\n const az = (s.x1 - s.x0) / length\n const corners = [\n [s.x0 + ax * s.w0 * 0.5, s.z0 + az * s.w0 * 0.5],\n [s.x0 - ax * s.w0 * 0.5, s.z0 - az * s.w0 * 0.5],\n [s.x1 + ax * s.w1 * 0.5, s.z1 + az * s.w1 * 0.5],\n [s.x1 - ax * s.w1 * 0.5, s.z1 - az * s.w1 * 0.5],\n ] as const\n corners.forEach(([x, z], corner) => {\n const at = (quad * 4 + corner) * 3\n positions[at] = x\n positions[at + 1] = lift(x, z)\n positions[at + 2] = z\n colours[at] = r\n colours[at + 1] = g\n colours[at + 2] = b\n })\n quad++\n }\n }\n position.needsUpdate = true\n colour.needsUpdate = true\n geometry.setDrawRange(0, quad * 6)\n },\n dispose() {\n stopListening()\n geometry.dispose()\n material.dispose()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport type { GroundLayout } from '@adatechnology/game-contracts'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { Terrain } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst LABEL_LIFT = 0.025\nconst LABEL_HEIGHT = 0.42\nconst LABEL_MAX_WIDTH = 3\nconst WATER_COLOUR = 0x2c5a68\nconst WATER_OPACITY = 0.62\nconst WATER_ROUGHNESS = 0.08\nconst WAVE_SIZE = 64\nconst WAVE_TILES_PER_METRE = 0.6\nconst WAVE_SPEED = 0.012\n\nfunction buildSign(THREE: ThreeLib, text: string): THREE_NS.Mesh | null {\n if (typeof document === 'undefined') return null\n const canvas = document.createElement('canvas')\n canvas.width = 512\n canvas.height = 72\n const context = canvas.getContext('2d')\n if (!context) return null\n context.fillStyle = 'rgba(0,0,0,0.65)'\n context.fillRect(0, 0, 512, 72)\n context.fillStyle = '#fff'\n context.font = 'bold 46px sans-serif'\n context.textAlign = 'center'\n context.textBaseline = 'middle'\n context.fillText(text, 256, 38)\n const mesh = new THREE.Mesh(new THREE.PlaneGeometry(LABEL_MAX_WIDTH, LABEL_HEIGHT), new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(canvas), transparent: true, depthWrite: false }))\n mesh.rotation.x = -Math.PI / 2\n return mesh\n}\n\n/** A gentle bump map as normals, tiled over the water: it moves in `sync`. */\nfunction createWaveTexture(THREE: ThreeLib): THREE_NS.DataTexture {\n const data = new Uint8Array(WAVE_SIZE * WAVE_SIZE * 4)\n const tau = Math.PI * 2 / WAVE_SIZE\n for (let y = 0; y < WAVE_SIZE; y++) {\n for (let x = 0; x < WAVE_SIZE; x++) {\n const dx = Math.cos(x * tau * 2 + y * tau) * 0.5 + Math.cos(x * tau * 5 - y * tau * 2) * 0.3\n const dy = Math.cos(y * tau * 3 + x * tau) * 0.5 + Math.cos(y * tau * 4 - x * tau * 3) * 0.3\n const at = (y * WAVE_SIZE + x) * 4\n data[at] = Math.round((dx * 0.25 + 0.5) * 255)\n data[at + 1] = Math.round((dy * 0.25 + 0.5) * 255)\n data[at + 2] = 255\n data[at + 3] = 255\n }\n }\n const texture = new THREE.DataTexture(data, WAVE_SIZE, WAVE_SIZE, THREE.RGBAFormat)\n texture.wrapS = texture.wrapT = THREE.RepeatWrapping\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\n/** What a layout lays over the ground: the water of the zones that have it and the sign of the zones that say what they are. Follows the layout as it changes. */\nexport function createZoneLayer(THREE: ThreeLib, terrain: Terrain): { group: THREE_NS.Group; sync(): void; dispose(): void } {\n const group = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'ground' })\n group.name = 'terrain-zones'\n const waves = createWaveTexture(THREE)\n // where the water meets the bed at its edge the two lie on one plane: the offset draws the water in front instead of flickering\n const water = new THREE.MeshStandardMaterial({ color: WATER_COLOUR, transparent: true, opacity: WATER_OPACITY, roughness: WATER_ROUGHNESS, metalness: 0.1, normalMap: waves, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 })\n let drawnFor: GroundLayout | null = null\n const throwAway = (): void => {\n for (const child of [...group.children]) {\n group.remove(child)\n const mesh = child as THREE_NS.Mesh\n mesh.geometry.dispose()\n if (mesh.material !== water) {\n const material = mesh.material as THREE_NS.MeshBasicMaterial\n material.map?.dispose()\n material.dispose()\n }\n }\n }\n const isWater = (surface: string): boolean => terrain.profileList.some((profile) => profile.id === surface && profile.water)\n const draw = (layout: GroundLayout): void => {\n throwAway()\n const [x0, z0, x1, z1] = terrain.bounds\n const rects: (readonly [number, number, number, number])[] = isWater(layout.surface) ? [[x0, z0, x1, z1]] : []\n for (const zone of layout.zones ?? []) {\n if (isWater(zone.surface)) rects.push(zone.rect)\n if (!zone.label) continue\n const sign = buildSign(THREE, zone.label)\n if (!sign) continue\n const [ax, , bx, bz] = zone.rect\n sign.scale.x = Math.min(1, (bx - ax - 0.1) / LABEL_MAX_WIDTH)\n sign.position.set((ax + bx) / 2, LABEL_LIFT, bz - LABEL_HEIGHT / 2 - 0.03)\n sign.renderOrder = 3\n group.add(sign)\n }\n for (const [ax, az, bx, bz] of rects) {\n const plane = new THREE.PlaneGeometry(bx - ax, bz - az)\n plane.rotateX(-Math.PI / 2)\n const uv = plane.getAttribute('uv') as THREE_NS.BufferAttribute\n for (let i = 0; i < uv.count; i++) uv.setXY(i, uv.getX(i) * (bx - ax) * WAVE_TILES_PER_METRE, uv.getY(i) * (bz - az) * WAVE_TILES_PER_METRE)\n const mesh = new THREE.Mesh(plane, water)\n mesh.name = 'terrain-water'\n mesh.position.set((ax + bx) / 2, terrain.waterAt((ax + bx) / 2, (az + bz) / 2)?.level ?? 0, (az + bz) / 2)\n mesh.renderOrder = 1\n group.add(mesh)\n }\n }\n return {\n group,\n sync() {\n const layout = terrain.layout()\n if (layout !== drawnFor) {\n drawnFor = layout\n draw(layout)\n }\n const shift = (Date.now() % 1_000_000) * 0.001 * WAVE_SPEED\n waves.offset.set(shift, shift * 0.7)\n },\n dispose() {\n throwAway()\n water.dispose()\n waves.dispose()\n group.removeFromParent()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst BAR_RADIUS = 0.006\nconst EXPOSED_MARGIN = 0.002\n/** Metres a bar hangs just before it gives way. */\nconst MAX_SAG = 0.07\n\n/** Bars a fresh geometry has room for at least, so that a chunk whose bars grow a little keeps its buffers. */\nconst MIN_BAR_CAPACITY = 32\n\nfunction barCapacity(count: number): number {\n let capacity = MIN_BAR_CAPACITY\n while (capacity < count) capacity *= 2\n return capacity\n}\n\n/**\n * The bars of a reinforced layer where the digging passed their cover: a mesh of the chunk, or null when none is showing. A `reuse` geometry with room for them is written into\n * (and only its draw range changes) instead of making new buffers.\n */\nexport function buildRebarGeometry(THREE: ThreeLib, terrain: Terrain, chunk: TerrainChunk, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry | null {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows, stride } = terrain\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const boxes: number[] = []\n const coverOf = (index: number): { depth: number; spacing: number } | null => {\n let top = 0\n for (const stratum of terrain.profileList[terrain.profileIndex[index]!]!.strata) {\n if (stratum.reinforcement) return { depth: top + stratum.reinforcement.cover, spacing: stratum.reinforcement.spacing }\n top += stratum.thickness\n }\n return null\n }\n // past the bottom of its strata the slab has opened: the bars are gone there and stay bent around the hole\n const showing = (index: number, depth: number): boolean => {\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const limit = profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n return terrain.dug[index]! > depth + EXPOSED_MARGIN && terrain.dug[index]! <= limit + EXPOSED_MARGIN\n }\n const onBar = (coordinate: number, spacing: number): boolean => Math.floor(coordinate / spacing) !== Math.floor((coordinate + cellSize) / spacing)\n const addBox = (ax: number, az: number, bx: number, bz: number, y: number): void => {\n boxes.push(Math.min(ax, bx) - BAR_RADIUS, y - BAR_RADIUS, Math.min(az, bz) - BAR_RADIUS, Math.max(ax, bx) + BAR_RADIUS, y + BAR_RADIUS, Math.max(az, bz) + BAR_RADIUS)\n }\n for (let row = chunk.row; row <= lastRow; row++) {\n for (let column = chunk.column; column <= lastColumn; column++) {\n const index = row * stride + column\n const cover = coverOf(index)\n if (!cover || !showing(index, cover.depth)) continue\n const x = x0 + column * cellSize\n const z = z0 + row * cellSize\n const y = -cover.depth - BAR_RADIUS - Math.min(1, terrain.barBend[index]!) * MAX_SAG\n if (onBar(z, cover.spacing) && column < lastColumn && showing(index + 1, cover.depth)) addBox(x, z, x + cellSize, z, y)\n if (onBar(x, cover.spacing) && row < lastRow && showing(index + stride, cover.depth)) addBox(x, z, x, z + cellSize, y)\n }\n }\n if (boxes.length === 0) return null\n const count = boxes.length / 6\n const target = reuse && reuse.getAttribute('position').count >= count * 24 ? reuse : undefined\n const capacity = target ? target.getAttribute('position').count / 24 : barCapacity(count)\n const positions = target ? (target.getAttribute('position').array as Float32Array) : new Float32Array(capacity * 24 * 3)\n const normals = target ? (target.getAttribute('normal').array as Float32Array) : new Float32Array(capacity * 24 * 3)\n const indices = target ? (target.getIndex()!.array as Uint32Array) : new Uint32Array(capacity * 36)\n const FACES: readonly (readonly [readonly number[], readonly [number, number, number]])[] = [\n [[0, 4, 2, 0, 4, 5, 3, 4, 5, 3, 4, 2], [0, 1, 0]],\n [[0, 1, 5, 0, 1, 2, 3, 1, 2, 3, 1, 5], [0, -1, 0]],\n [[0, 1, 5, 3, 1, 5, 3, 4, 5, 0, 4, 5], [0, 0, 1]],\n [[3, 1, 2, 0, 1, 2, 0, 4, 2, 3, 4, 2], [0, 0, -1]],\n [[3, 1, 5, 3, 1, 2, 3, 4, 2, 3, 4, 5], [1, 0, 0]],\n [[0, 1, 2, 0, 1, 5, 0, 4, 5, 0, 4, 2], [-1, 0, 0]],\n ]\n let vertex = 0\n let cursor = 0\n for (let n = 0; n < count; n++) {\n const box = boxes.slice(n * 6, n * 6 + 6)\n for (const [corners, normal] of FACES) {\n const first = vertex\n for (let c = 0; c < 4; c++) {\n positions[vertex * 3] = box[corners[c * 3]!]!\n positions[vertex * 3 + 1] = box[corners[c * 3 + 1]!]!\n positions[vertex * 3 + 2] = box[corners[c * 3 + 2]!]!\n normals.set(normal, vertex * 3)\n vertex++\n }\n indices.set([first, first + 1, first + 2, first, first + 2, first + 3], cursor)\n cursor += 6\n }\n }\n if (target) {\n target.getAttribute('position').needsUpdate = true\n target.getAttribute('normal').needsUpdate = true\n target.getIndex()!.needsUpdate = true\n target.boundingSphere = null\n target.boundingBox = null\n target.setDrawRange(0, count * 36)\n return target\n }\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n geometry.setDrawRange(0, count * 36)\n return geometry\n}\n","import type * as THREE_NS from 'three'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\nimport { buildChunkGeometry, buildPristineGeometry, chunkVertexCount } from './chunk-geometry'\nimport { createDecalLayers } from './decal-layers'\nimport { createCrackLayer, createDebrisLayer, createMarkLayer } from './layers'\nimport { createZoneLayer } from './zone-layer'\nimport { buildRebarGeometry } from './rebar'\nimport { createSurfaceMaterial } from './surface-material'\n\ntype ThreeLib = typeof THREE_NS\n\nexport interface TerrainRendererOptions {\n readonly terrain: Terrain\n /** Beyond this distance in metres a dug chunk draws half its vertices (default 30), twice this a quarter. */\n readonly lodDistance?: number\n /** Marks farther than this in metres are not drawn (default 45). */\n readonly markDistance?: number\n /** Metres the untouched ground goes on beyond the terrain, so that it has no edge in sight (default 300). */\n readonly skirt?: number\n}\n\nexport interface TerrainRenderer {\n readonly group: THREE_NS.Group\n /** Call every frame with the camera's position. Redraws at most the terrain's budget of chunks. */\n sync(camera: { readonly x: number; readonly y: number; readonly z: number }): void\n /** What is on the screen, for a bench. */\n stats(): { readonly chunkMeshes: number; readonly pristineChunks: number; readonly marksDrawn: number; readonly debrisDrawn: number; readonly crackQuads: number }\n dispose(): void\n}\n\nconst DEFAULT_LOD_DISTANCE = 30\nconst DEFAULT_MARK_DISTANCE = 45\nconst DEFAULT_SKIRT = 300\nconst LOD_CHECK_METRES = 4\nconst REBAR_COLOUR = 0x4a3528\n/** Geometries of chunks that went back to pristine or changed detail, kept to be refilled for the next dug chunk. */\nconst MAX_SPARE_GEOMETRIES = 24\n\ninterface DrawnChunk {\n mesh: THREE_NS.Mesh\n rebar: THREE_NS.Mesh | null\n step: number\n}\n\n/** The ground of a `Terrain`: chunks nobody touched share one flat geometry, a dug one gets a mesh of its own that gets simpler far away. */\nexport function createTerrainRenderer(THREE: ThreeLib, options: TerrainRendererOptions): TerrainRenderer {\n const { terrain } = options\n const lodDistance = options.lodDistance ?? DEFAULT_LOD_DISTANCE\n const skirt = options.skirt ?? DEFAULT_SKIRT\n const group = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'ground' })\n group.name = 'floor'\n const surface = createSurfaceMaterial(THREE)\n const rebarMaterial = new THREE.MeshStandardMaterial({ color: REBAR_COLOUR, roughness: 0.75, metalness: 0.35 })\n const pristineMesh = new THREE.Mesh(new THREE.BufferGeometry(), surface)\n pristineMesh.receiveShadow = true\n pristineMesh.name = 'terrain-pristine'\n pristineMesh.frustumCulled = false\n group.add(pristineMesh)\n const drawn = new Map<number, DrawnChunk>()\n const marks = createMarkLayer(THREE, terrain, options.markDistance ?? DEFAULT_MARK_DISTANCE)\n const debris = createDebrisLayer(THREE, terrain)\n const cracks = createCrackLayer(THREE, terrain)\n const decals = createDecalLayers(THREE, terrain)\n const zones = createZoneLayer(THREE, terrain)\n group.add(marks.mesh, cracks.mesh, debris.mesh, decals.group, zones.group)\n let pristineStale = true\n let pristineBuilt = false\n let pristineCount = 0\n let lodX = Infinity\n let lodZ = Infinity\n let firstSync = true\n\n const distanceTo = (chunk: TerrainChunk, camera: { x: number; z: number }): number => {\n const half = (chunk.cells * terrain.cellSize) / 2\n const centreX = terrain.bounds[0] + chunk.column * terrain.cellSize + half\n const centreZ = terrain.bounds[1] + chunk.row * terrain.cellSize + half\n return Math.hypot(centreX - camera.x, centreZ - camera.z)\n }\n const stepFor = (distance: number): number => (distance > lodDistance * 2 ? 4 : distance > lodDistance ? 2 : 1)\n\n const spareGeometries: THREE_NS.BufferGeometry[] = []\n\n function keepSpare(geometry: THREE_NS.BufferGeometry): void {\n if (spareGeometries.length < MAX_SPARE_GEOMETRIES) spareGeometries.push(geometry)\n else geometry.dispose()\n }\n\n function takeSpare(chunk: TerrainChunk, step: number): THREE_NS.BufferGeometry | undefined {\n const count = chunkVertexCount(terrain, chunk, step)\n const found = spareGeometries.findIndex((geometry) => geometry.getAttribute('position').count === count)\n return found < 0 ? undefined : spareGeometries.splice(found, 1)[0]\n }\n\n function drop(index: number): void {\n const entry = drawn.get(index)\n if (!entry) return\n group.remove(entry.mesh)\n keepSpare(entry.mesh.geometry)\n if (entry.rebar) {\n group.remove(entry.rebar)\n entry.rebar.geometry.dispose()\n }\n drawn.delete(index)\n }\n\n function drawRebar(chunk: TerrainChunk, entry: DrawnChunk): void {\n const bars = buildRebarGeometry(THREE, terrain, chunk, entry.rebar?.geometry)\n if (!bars) {\n if (entry.rebar) entry.rebar.visible = false\n return\n }\n if (entry.rebar && entry.rebar.geometry === bars) {\n entry.rebar.visible = true\n return\n }\n if (entry.rebar) {\n group.remove(entry.rebar)\n entry.rebar.geometry.dispose()\n }\n entry.rebar = new THREE.Mesh(bars, rebarMaterial)\n entry.rebar.castShadow = true\n group.add(entry.rebar)\n }\n\n function draw(chunk: TerrainChunk, camera: { x: number; z: number }): void {\n const step = stepFor(distanceTo(chunk, camera))\n let entry = drawn.get(chunk.index)\n if (!entry) {\n const mesh = new THREE.Mesh(buildChunkGeometry(THREE, terrain, chunk, step, takeSpare(chunk, step)), surface)\n mesh.receiveShadow = true\n group.add(mesh)\n entry = { mesh, rebar: null, step }\n drawn.set(chunk.index, entry)\n } else {\n const previous = entry.mesh.geometry\n const sameDetail = previous.getAttribute('position').count === chunkVertexCount(terrain, chunk, step)\n entry.mesh.geometry = buildChunkGeometry(THREE, terrain, chunk, step, sameDetail ? previous : takeSpare(chunk, step))\n if (entry.mesh.geometry !== previous) keepSpare(previous)\n entry.step = step\n }\n drawRebar(chunk, entry)\n }\n\n function rebuildPristine(): void {\n const chunks: TerrainChunk[] = []\n for (let index = 0; index < terrain.chunksX * terrain.chunksZ; index++) {\n const chunk = terrain.chunk(index)\n if (chunk.pristine) chunks.push(chunk)\n }\n if (!pristineBuilt) pristineMesh.geometry.dispose()\n pristineMesh.geometry = buildPristineGeometry(THREE, terrain, chunks, skirt, pristineBuilt ? pristineMesh.geometry : undefined)\n pristineBuilt = true\n pristineCount = chunks.length\n pristineStale = false\n }\n\n return {\n group,\n sync(camera) {\n // the first picture and a floor just laid (a new layout, a reset) have every chunk dirty: pristine ones need no work of their own, the rest are drawn at once, since the\n // pristine floor is rebuilt without them in the same frame and a chunk left for later would be a hole to the sky until its turn came\n const laidAnew = terrain.dirtyChunkCount >= terrain.chunksX * terrain.chunksZ\n const limit = firstSync || laidAnew ? Infinity : undefined\n firstSync = false\n for (const chunk of terrain.drainDirtyChunks(limit)) {\n if (chunk.pristine) {\n if (drawn.has(chunk.index)) drop(chunk.index)\n pristineStale = true\n } else {\n if (!drawn.has(chunk.index)) pristineStale = true\n draw(chunk, camera)\n }\n }\n if (pristineStale) rebuildPristine()\n if (Math.hypot(camera.x - lodX, camera.z - lodZ) > LOD_CHECK_METRES) {\n lodX = camera.x\n lodZ = camera.z\n for (const [index, entry] of drawn) {\n const chunk = terrain.chunk(index)\n if (stepFor(distanceTo(chunk, camera)) !== entry.step) draw(chunk, camera)\n }\n }\n marks.sync(camera)\n cracks.sync()\n debris.sync()\n decals.sync()\n zones.sync()\n },\n stats: () => ({ chunkMeshes: drawn.size, pristineChunks: pristineCount, marksDrawn: marks.mesh.count, debrisDrawn: debris.mesh.count, crackQuads: cracks.mesh.geometry.drawRange.count / 6 }),\n dispose() {\n for (const index of [...drawn.keys()]) drop(index)\n for (const geometry of spareGeometries) geometry.dispose()\n pristineMesh.geometry.dispose()\n surface.dispose()\n rebarMaterial.dispose()\n marks.dispose()\n cracks.dispose()\n debris.dispose()\n decals.dispose()\n zones.dispose()\n group.removeFromParent()\n },\n }\n}\n","import type { TERRAIN_STRIPS } from './test-module'\n\n/** The ground profiles of the catalogue (`TERRAIN_PROFILES` of game-terrain) by name, for a HUD that says what the floor under the aim is. */\nconst PROFILE_NAMES: Record<string, Record<string, string>> = {\n en: { lawn: 'Lawn', dirt: 'Dirt', sand: 'Sand', road: 'Asphalt road', concrete_slab: 'Concrete slab', sidewalk: 'Sidewalk', suspended_slab: 'Slab over a void', tile_floor: 'Tile floor', wood_floor: 'Wood floor', stone_paving: 'Stone paving', mud: 'Mud', gravel_bed: 'Gravel', dry_clay: 'Dry clay', snow: 'Snow', cobblestone: 'Cobblestones', paver_floor: 'Concrete pavers', shallow_water: 'Shallow water', bedrock: 'Bare rock', pond: 'Pond' },\n 'pt-BR': { lawn: 'Grama', dirt: 'Terra', sand: 'Areia', road: 'Asfalto', concrete_slab: 'Laje de concreto', sidewalk: 'Calçada', suspended_slab: 'Laje sobre vão', tile_floor: 'Piso cerâmico', wood_floor: 'Assoalho', stone_paving: 'Calçamento de pedra', mud: 'Lama', gravel_bed: 'Cascalho', dry_clay: 'Barro seco', snow: 'Neve', cobblestone: 'Paralelepípedo', paver_floor: 'Bloquete', shallow_water: 'Água rasa', bedrock: 'Rocha', pond: 'Lago' },\n}\n\n/** The name of a ground profile in the locale (`en` when the locale is unknown); a profile a game added without a name answers its id. */\nexport function terrainProfileName(profileId: string, localeId: string): string {\n return (PROFILE_NAMES[localeId] ?? PROFILE_NAMES.en!)[profileId] ?? profileId\n}\n\ninterface TerrainText {\n readonly name: string\n readonly group: string\n readonly weight: string\n readonly surfaces: Record<(typeof TERRAIN_STRIPS)[number], string>\n}\n\nconst LOCALES: Record<string, TerrainText> = {\n en: {\n name: 'Terrain',\n group: 'Terrain',\n weight: 'Concrete block (60 kg)',\n surfaces: { dirt: 'Dirt', lawn: 'Lawn', sand: 'Sand', road: 'Asphalt', concrete_slab: 'Concrete slab', suspended_slab: 'Slab over a void', wood_floor: 'Wood floor', tile_floor: 'Tile', stone_paving: 'Stone paving', mud: 'Mud', gravel_bed: 'Gravel', dry_clay: 'Dry clay', snow: 'Snow', cobblestone: 'Cobblestones', paver_floor: 'Concrete pavers', shallow_water: 'Shallow water', bedrock: 'Bare rock', pond: 'Pond' },\n },\n 'pt-BR': {\n name: 'Terreno',\n group: 'Terreno',\n weight: 'Bloco de concreto (60 kg)',\n surfaces: { dirt: 'Terra', lawn: 'Grama', sand: 'Areia', road: 'Asfalto', concrete_slab: 'Laje de concreto', suspended_slab: 'Laje sobre vão', wood_floor: 'Assoalho', tile_floor: 'Cerâmica', stone_paving: 'Pedra', mud: 'Lama', gravel_bed: 'Cascalho', dry_clay: 'Barro seco', snow: 'Neve', cobblestone: 'Paralelepípedo', paver_floor: 'Bloquete', shallow_water: 'Água rasa', bedrock: 'Rocha', pond: 'Lago' },\n },\n}\n\nexport const locale = (id: string): TerrainText => LOCALES[id] ?? LOCALES.en!\n","import type * as THREE_NS from 'three'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { DestructibleSpec, GroundLayout, ModuleArea, TestableItem, TestableModule } from '@adatechnology/game-contracts'\nimport { locale as localeTable } from './locale'\n\ntype ThreeLib = typeof THREE_NS\n\n/** The lots of the area, side by side in two rows, one of each ground: the soft and wet ones in the back row, rock and the built ones in front. */\nexport const TERRAIN_STRIPS = ['lawn', 'dirt', 'sand', 'mud', 'dry_clay', 'gravel_bed', 'snow', 'shallow_water', 'pond', 'bedrock', 'road', 'cobblestone', 'paver_floor', 'stone_paving', 'concrete_slab', 'suspended_slab', 'tile_floor', 'wood_floor'] as const\nconst LOT_WIDTH = 3\nconst LOT_DEPTH = 3.8\nconst LOTS_PER_ROW = 9\n/** Between the target wall and the table of the room: what the player sees on arriving, and clear of the furniture. */\nconst LOTS_Z1 = -1.4\nconst lotRect = (index: number): readonly [number, number, number, number] => {\n const row = Math.floor(index / LOTS_PER_ROW)\n const x0 = ((index % LOTS_PER_ROW) - LOTS_PER_ROW / 2) * LOT_WIDTH\n // the first row is the far one\n const z1 = LOTS_Z1 - (1 - row) * LOT_DEPTH\n return [x0, z1 - LOT_DEPTH, x0 + LOT_WIDTH, z1]\n}\n\n/** A lot of each ground, with its sign. A host lays it to give a room every ground to try (`createTestRoom`'s `ground`). */\nexport function terrainLotsGround(locale = 'en'): GroundLayout {\n const text = localeTable(locale)\n return { surface: 'concrete_slab', zones: TERRAIN_STRIPS.map((surface, index) => ({ rect: lotRect(index), surface, label: text.surfaces[surface] })) }\n}\nexport const TERRAIN_AREA_GROUND: GroundLayout = terrainLotsGround()\n\nconst WEIGHT_SIDE = 0.32\nconst WEIGHT_HEIGHT = 4\n\nfunction weightSpec(): DestructibleSpec {\n return { name: 'Weight', parts: [{ id: 'block', material: 'concrete', shape: { kind: 'box', size: [WEIGHT_SIDE, WEIGHT_SIDE, WEIGHT_SIDE] }, position: [0, WEIGHT_SIDE / 2, 0] }], joints: [] }\n}\n\nfunction buildWeight(THREE: ThreeLib): THREE_NS.Object3D {\n const mesh = new THREE.Mesh(new THREE.BoxGeometry(WEIGHT_SIDE, WEIGHT_SIDE, WEIGHT_SIDE), new THREE.MeshStandardMaterial({ color: 0xb4b4ae, roughness: 0.9 }))\n mesh.name = 'block'\n mesh.position.y = WEIGHT_SIDE / 2\n mesh.castShadow = true\n const root = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'item' })\n root.add(mesh)\n return root\n}\n\n/**\n * The ground bench: a lot of each surface side by side to shoot, blow up, burn and drop weights on. Opening the area lays the lots with their signs (`ground`) and drops a concrete block\n * on each from four metres.\n */\nexport function createTerrainTestModule(options: { readonly locale?: string } = {}): TestableModule {\n const text = localeTable(options.locale ?? 'en')\n return {\n id: 'terrain',\n name: text.name,\n group: text.group,\n ground: terrainLotsGround(options.locale ?? 'en'),\n items(): TestableItem[] {\n return [{ id: 'terrain_weight', name: text.weight, build: (THREE) => buildWeight(THREE as ThreeLib), spec: weightSpec, movable: true }]\n },\n area(): ModuleArea {\n return {\n placements: TERRAIN_STRIPS.map((_, index) => {\n const [x0, z0] = lotRect(index)\n return { item: 'terrain_weight', position: [x0 + LOT_WIDTH / 2, WEIGHT_HEIGHT, z0 + 1.2] }\n }),\n view: { eye: [0, 1.7, 1.5], target: [0, 0, -6] },\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,MAAM,wBAAiE,EAAE,UAAU,KAAK,MAAM,MAAM,UAAU,KAAK,aAAa,OAAO,IAAO;AKVrJ,MAAM,gCAAgC,OAAO;AYmCtC,MAAM,oBAAoB;IAC/B,oBAAoB;IACpB,cAAc;IACd,YAAY;IACZ,cAAc;IACd,gBAAgB;IAChB,iBAAiB;IACjB,YAAY;IACZ,mBAAmB;IACnB,eAAe;IACf,cAAc;IACd,sBAAsB;IACtB,yBAAyB;IACzB,oBAAoB;IACpB,oBAAoB;EACtB;AAGO,MAAM,oBAAoB;IAC/B,CAAC,kBAAkB,kBAAkB,GAAG,EAAE,UAAU,KAAK,OAAO,UAAU;;IAE1E,CAAC,kBAAkB,UAAU,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACrF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACvF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,WAAW,EAAE;IAC/E,CAAC,kBAAkB,eAAe,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,gBAAgB,EAAE;IAC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AAM,OAAO,IAAI,MAAM,KAAK,IAAI,MAAM,YAAY,aAAa,aAAa,WAAW,GAAG,IAAI,MAAM,qBAAqB,EAAE,OAAO,UAAU,WAAW,IAAI,CAAC,CAAC;AAC7J,SAAK,OAAO;AACZ,SAAK,SAAS,IAAI,cAAc;AAChC,SAAK,aAAa;AAClB,UAAM,OAAO,cAAc,IAAI,MAAM,MAAM,GAAG,EAAE,OAAO,sBAAsB,MAAM,OAAO,CAAC;AAC3F,SAAK,IAAI,IAAI;AACb,WAAO;AAAA,EACT;AAMO,WAAS,wBAAwB,UAAwC,CAAC,GAAmB;AAClG,UAAM,OAAO,OAAY,QAAQ,UAAU,IAAI;AAC/C,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,MAAM,KAAK;AAAA,MACX,OAAO,KAAK;AAAA,MACZ,QAAQ,kBAAkB,QAAQ,UAAU,IAAI;AAAA,MAChD,QAAwB;AACtB,eAAO,CAAC,EAAE,IAAI,kBAAkB,MAAM,KAAK,QAAQ,OAAO,CAAC,UAAU,YAAY,KAAiB,GAAG,MAAM,YAAY,SAAS,KAAK,CAAC;AAAA,MACxI;AAAA,MACA,OAAmB;AACjB,eAAO;AAAA,UACL,YAAY,eAAe,IAAI,CAAC,GAAG,UAAU;AAC3C,kBAAM,CAAC,IAAI,EAAE,IAAI,QAAQ,KAAK;AAC9B,mBAAO,EAAE,MAAM,kBAAkB,UAAU,CAAC,KAAK,YAAY,GAAG,eAAe,KAAK,GAAG,EAAE;AAAA,UAC3F,CAAC;AAAA,UACD,MAAM,EAAE,KAAK,CAAC,GAAG,KAAK,GAAG,GAAG,QAAQ,CAAC,GAAG,GAAG,EAAE,EAAE;AAAA,QACjD;AAAA,MACF;AAAA,IACF;AAAA,EACF;","names":["profile","locale"]}
1
+ {"version":3,"sources":["../src/index.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/fireball.ts","../../game-contracts/src/blast-wave.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/body-measures.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/rain-cover.ts","../../game-contracts/src/nav-obstacles.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/workers.ts","../../game-contracts/src/index.ts","../../game-terrain/src/terrain.ts","../../game-terrain/src/catalog.ts","../../game-terrain/src/random.ts","../../game-terrain/src/cracks.ts","../../game-terrain/src/debris.ts","../../game-terrain/src/ground-loss.ts","../../game-terrain/src/height-patch.ts","../../game-terrain/src/marks.ts","../../game-terrain/src/impl.ts","../../game-terrain/src/types.ts","../../game-terrain/src/footprints.ts","../../game-terrain/src/buoyancy.ts","../src/surface-material.ts","../src/chunk-geometry.ts","../src/decal-layers.ts","../src/layers.ts","../src/zone-layer.ts","../src/rebar.ts","../src/renderer.ts","../src/test-area/locale.ts","../src/test-area/test-module.ts"],"sourcesContent":["export { createTerrainRenderer } from './renderer'\nexport type { TerrainRenderer, TerrainRendererOptions } from './renderer'\nexport { createSurfaceMaterial } from './surface-material'\n/** @deprecated import from '@adatechnology/game-terrain-three/testing' */\nexport { createTerrainTestModule, terrainLotsGround, TERRAIN_AREA_GROUND, TERRAIN_STRIPS } from './testing'\nexport { terrainProfileName } from './test-area/locale'\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 by default: inside it the charge is in contact and the body is torn apart anyway (a caller that loads a part next to the charge passes a smaller `nearest`). */\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, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, nearest) / w3\n // products, not `**` past 2: V8 gives `x ** 3` a different last bit on Node 22 and 24, and the goldens must agree on both\n const near = (z / 0.23) * (z / 0.23)\n const far = z / 1.55\n const scaled = (0.067 * Math.sqrt(1 + near * near)) / (z * z * Math.cbrt(1 + far * far * far))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/** Sea-level atmospheric pressure, Pa. */\nconst ATMOSPHERE = 101325\n\n/**\n * Peak side-on (incident) overpressure of the wave, in Pa, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `Ps/Pa = 808 (1 + (Z/4.5)^2) / (sqrt(1 + (Z/0.048)^2) sqrt(1 + (Z/0.32)^2) sqrt(1 + (Z/1.35)^2))`, with the scaled distance `Z = R / W^(1/3)` (m/kg^(1/3)).\n * What a wall takes from a blast is read against it: about 7 kPa cracks plaster and breaks windows, 14 to 20 kPa knocks parts of a brick wall out, 35 kPa and over brings an\n * unreinforced brick wall down (Glasstone and Dolan, \"The Effects of Nuclear Weapons\", 1977, table 5.139; UFC 3-340-02).\n */\nexport function sideOnOverpressure(tnt: number, distance: number, nearest = NEAREST): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, nearest) / Math.cbrt(tnt)\n const ratio = (808 * (1 + (z / 4.5) ** 2)) / (Math.sqrt(1 + (z / 0.048) ** 2) * Math.sqrt(1 + (z / 0.32) ** 2) * Math.sqrt(1 + (z / 1.35) ** 2))\n return ratio * ATMOSPHERE\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 { bodyImpulse, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport 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 * A target that says its `area` (m2 it shows the wave) is pushed by the blast wave itself instead (`bodyImpulse`: Kinney-Graham impulse of the charge `blast.tnt`, or of `energy` by\n * `tntPerJoule`, reflected on that area, divided by the mass): a 2 kg shovel 0.8 m from a hand grenade gets a few m/s, not the cap. `maxSpeed` still caps it (a light thing next to the charge would otherwise tunnel through what stands in its way); `coupling` and `falloffPower` do not apply.\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; readonly area?: 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 =\n target.area !== undefined\n ? Math.min(o.maxSpeed, (bodyImpulse(blast.tnt ?? blast.energy * DEFAULT_BLAST_IMPULSE.tntPerJoule, distance) * target.area * reach) / mass)\n : 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 heat of a blast, from the size and life of its fireball and not from the game radius of the blast. Pure functions in SI units (m, s, W/m2, J/m2).\n *\n * A condensed charge (TNT, Composition B, C4) makes a small fireball that lives milliseconds: its radius and its life both grow as the cube root of the charge\n * (Hopkinson-Cranz scaling, as the wave does). A burning fuel (the gas of a cylinder that bursts, petrol) makes a fireball metres wide that lives about a second:\n * the BLEVE correlations of the CCPS guidelines, `D = 5.8 M^(1/3)` m and `t = 0.45 M^(1/3)` s for `M` kg of fuel, with a surface emissive power of a few hundred kW/m2.\n * What a surface takes is the heat per square metre over the life of the fireball: the whole flux inside it, and outside it the share a sphere of radius `R` sends to a\n * surface that faces it at `d` from its centre (the view factor `(R / d)^2`). A surface catches fire when that dose passes what its material needs (`ignitionDose`).\n */\n\n/** The fireball of a blast: how wide, how long and how hot it burns on what it touches. */\nexport interface Fireball {\n /** Metres. */\n readonly radius: number\n /** Seconds the fireball lives. */\n readonly seconds: number\n /** W/m2 it puts on a surface inside it (radiation and the hot gases together). */\n readonly flux: number\n}\n\n/** m/kg^(1/3): radius of the luminous fireball of a condensed charge (an engineering estimate; the M67, 0.24 kg of TNT, is 0.8 m). */\nconst CHARGE_RADIUS = 1.3\n/** s/kg^(1/3): its life (the M67 burns 6 ms). */\nconst CHARGE_SECONDS = 0.01\n/** W/m2 on a surface inside the fireball of a condensed charge: detonation products at some 2500 K, radiation and convection. */\nconst CHARGE_FLUX = 1.5e6\n/** m/kg^(1/3): radius of a fuel fireball, half of the CCPS diameter 5.8 M^(1/3). */\nconst FUEL_RADIUS = 2.9\n/** s/kg^(1/3): life of a fuel fireball (CCPS, below 30 t of fuel). */\nconst FUEL_SECONDS = 0.45\n/** W/m2: surface emissive power of a hydrocarbon fireball (CCPS gives 200 to 350). */\nconst FUEL_FLUX = 250e3\n/** J/m2 per degree between the room and the ignition temperature: the dose a solid needs to light under a brief heat (paper at 230 °C takes 63 kJ/m2, hard wood at 330 °C 93). */\nconst DOSE_PER_DEGREE = 300\n\n/** The fireball of `tnt` kg of TNT equivalent of a condensed charge. */\nexport function chargeFireball(tnt: number): Fireball {\n const cube = Math.cbrt(Math.max(0, tnt))\n return { radius: CHARGE_RADIUS * cube, seconds: CHARGE_SECONDS * cube, flux: CHARGE_FLUX }\n}\n\n/** The fireball of `fuel` kg of a burning hydrocarbon (the gas of a cylinder, petrol). */\nexport function fuelFireball(fuel: number): Fireball {\n const cube = Math.cbrt(Math.max(0, fuel))\n return { radius: FUEL_RADIUS * cube, seconds: FUEL_SECONDS * cube, flux: FUEL_FLUX }\n}\n\n/** J/m2 a surface facing the fireball takes at `distance` metres from its centre: the whole flux inside it, the view factor `(R / d)^2` of the sphere outside. */\nexport function fireballDose(fireball: Fireball, distance: number): number {\n const share = distance <= fireball.radius ? 1 : (fireball.radius / distance) ** 2\n return fireball.flux * fireball.seconds * share\n}\n\n/** J/m2 a surface of a material that ignites at `ignitionC` needs to catch fire from a brief heat, starting at `ambientC`. */\nexport function ignitionDose(ignitionC: number, ambientC = 20): number {\n return DOSE_PER_DEGREE * Math.max(1, ignitionC - ambientC)\n}\n","import { sideOnImpulse, sideOnOverpressure } from './blast-impulse'\n\n/**\n * The blast wave on a part, from Hopkinson-Cranz scaling: the reflected load of a charge of TNT equivalent at a distance (Kinney and Graham's side-on fits, reflected by\n * Rankine-Hugoniot for the pressure and the Kingery-Bulmash ratio for the impulse), and the work it puts into a part of a given area, mass and thickness (the smaller\n * asymptote of its pressure-impulse diagram, Baker et al. 1983). Shared by the destruction world and every module that takes blasts on its own parts (vehicles).\n */\n\n/** Pa */\nconst ATMOSPHERE = 101325\n/** Scaled distance (m/kg^(1/3)) below which the far-field fits are held: closer is a charge in contact, where the fits stop being the wave. */\nconst NEAREST_SCALED = 0.2\n/** m: a charge's near field and the size of a charge add this much to the standoff when the area the wave loads evenly is taken. */\nconst LOADED_MARGIN = 0.15\n/** J/kg: the TNT equivalent's definition. */\nexport const TNT_JOULES = 4.184e6\n/**\n * Share of the charge energy that a target crushes and spalls when the charge is in contact with it, at the scaled distance 0 (an engineering estimate of the cratering efficiency of\n * contact charges in concrete and masonry: a few percent of the energy goes into breaking the material, the rest into air and ground shock).\n */\nconst SHOCK_COUPLING = 0.04\n/** m/kg^(1/3): scaled distance at which the crushing and spalling of a surface is a quarter of that at contact (they fall off as `(1 + (Z / Z0)^2)^-2`; spalling of concrete stops near Z = 1.5). */\nconst SHOCK_SCALED = 0.6\n\n/** The wave on a face that looks at the charge: reflected peak overpressure (Pa) and reflected positive impulse (Pa s). */\nexport interface WaveLoad {\n readonly pressure: number\n readonly impulse: number\n}\n\n/** The reflected load at `distance` m from `tnt` kg of TNT. */\nexport function reflectedLoad(tnt: number, distance: number): WaveLoad {\n if (!(tnt > 0)) return { pressure: 0, impulse: 0 }\n const cube = Math.cbrt(tnt)\n const nearest = NEAREST_SCALED * cube\n const side = sideOnOverpressure(tnt, distance, nearest)\n const z = Math.max(distance, nearest) / cube\n // ideal gas, normal reflection: Pr = 2 Ps (7 Pa + 4 Ps) / (7 Pa + Ps), 2 for a weak wave, up to 8 for a strong one\n const pressure = (2 * side * (7 * ATMOSPHERE + 4 * side)) / (7 * ATMOSPHERE + side)\n const impulse = sideOnImpulse(tnt, distance, nearest) * (2 + 4 / (1 + z * z))\n return { pressure, impulse }\n}\n\n\nexport interface WaveWorkInput {\n /** Kilograms of TNT. */\n readonly tnt: number\n /** Metres from the charge to the nearest point of the part. */\n readonly distance: number\n /** 0..1: the share of the wave that gets through what stands in between. */\n readonly reach: number\n /** m2 the part shows the charge. */\n readonly area: number\n readonly mass: number\n /** m: how far the part moves under the wave before it fails (its own thickness). */\n readonly thickness: number\n}\n\nexport interface WaveWork {\n /** m2 the wave loads evenly. */\n readonly loaded: number\n /** Joules the wave puts into the part as a whole (it moves and bends, the P-I work). */\n readonly energy: number\n /** Joules that crush and spall the face next to the charge (`shockWork`), on top of `energy`. */\n readonly shock: number\n /** Reflected peak overpressure on the part (Pa), after cover. */\n readonly pressure: number\n}\n\n/**\n * What a blast puts into a part: `min(J^2 / 2 m, P A d)` with the load `P`, `J / A` of `reflectedLoad` cut by `reach`, over the area the wave loads evenly (a disc as wide as the\n * standoff, so a wall 10 m wide is not loaded as one block by a charge 1 m from it) and the mass of the piece of the part under that area. A 2 mm steel blade 0.8 m from an M67 gets\n * about 75 J (a dent); a 2 tonne wall 1.5 m away gets about 120 J (a scuff), so the damage depends on how much the part weighs for the area it shows.\n */\nexport function waveWork(input: WaveWorkInput): WaveWork {\n const load = reflectedLoad(input.tnt, input.distance)\n const reach = Math.min(1, Math.max(0, input.reach))\n const pressure = load.pressure * reach\n if (!(input.area > 0) || !(input.mass > 0) || pressure <= 0) return { energy: 0, shock: 0, pressure, loaded: 0 }\n const loaded = Math.min(input.area, Math.PI * (input.distance + LOADED_MARGIN) ** 2)\n const mass = input.mass * (loaded / input.area)\n const impulse = load.impulse * reach * loaded\n const impulsive = (impulse * impulse) / (2 * mass)\n const quasiStatic = pressure * loaded * Math.max(input.thickness, 1e-4)\n return { energy: Math.min(impulsive, quasiStatic), shock: shockWork(input), pressure, loaded }\n}\n\n/**\n * Crushing and spalling of the face next to a charge, which the far-field fits do not see: the charge energy `W * 4.184 MJ`, times the share that crushes material at that scaled\n * distance (`SHOCK_COUPLING (1 + (Z / 0.6)^2)^-2`), times the share of the sphere around the charge that the part intercepts (`A / 4 pi (R + r_c)^2`, at most a half: a face on the charge).\n * A grenade 0.8 m from a blade gives it about 1 J of this; a block of C4 against a wall gives it tens of kilojoules.\n */\nfunction shockWork(input: WaveWorkInput): number {\n const cube = Math.cbrt(input.tnt)\n if (!(cube > 0) || !(input.area > 0)) return 0\n const z = Math.max(input.distance, 0) / cube\n const radius = Math.cbrt((3 * input.tnt) / (4 * Math.PI * 1600))\n const share = Math.min(0.5, input.area / (4 * Math.PI * (input.distance + radius) ** 2))\n // products, not `**` past 2: V8 gives `x ** -2` a different last bit on Node 22 and 24, and the goldens must agree on both\n const falloff = 1 + (z / SHOCK_SCALED) * (z / SHOCK_SCALED)\n const reach = Math.min(1, Math.max(0, input.reach))\n return (SHOCK_COUPLING * input.tnt * TNT_JOULES * share * reach * reach) / (falloff * falloff)\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\n/**\n * One drawn piece of a hosted body as a solid for a physics engine, in the impl's frame (`DestructibleImpl.colliders`): a box turned as drawn where a box fits the piece\n * (every corner within 1 cm of a vertex), else the piece's triangles (`mesh`, with the box around them). `id` is the part of `describe()` the piece is.\n * A piece handed back is never changed in place: a piece that changed is a new object (the world reuses what it made of an object it has seen, `hostedSolids`).\n */\nexport interface DrawnCollider {\n readonly id: string\n /** Names the piece across lists (a piece measured again is the same piece): without it, the place in the list. */\n readonly key?: string\n readonly center: Vec3\n readonly half: Vec3\n readonly rotation: [number, number, number, number]\n readonly mesh?: { readonly vertices: Float32Array; readonly indices: Uint32Array }\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 /**\n * The pieces the impl draws, as what an engine collides with in their place (in the frame `describe()` answers in): one per drawn piece, none for a part that broke or\n * came off. Without it the engine takes the boxes of `describe()`. Same cost contract as `describe()`: the world asks again only when state, place or a pose changes.\n */\n colliders?(): readonly DrawnCollider[]\n /** True while `colliders()` still has pieces to make (a vehicle that just spawned fills in over several updates): the world asks again at the next update. */\n collidersPending?(): boolean\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', 'pieces'], 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 if (hit.pieces !== undefined && !(Number.isFinite(hit.pieces) && hit.pieces >= 1)) out.push(`${hit.type} hit \"pieces\" must be a finite number of at least 1`)\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 { Vec3 } from './destruction'\n\n/** Anthropometric measures of a standing/seated body derived from stature and lateral build (metres). */\nexport type BodyMeasures = {\n /** Standing stature from sole to top of skull (excluding hair/hat), in metres. */\n readonly heightMetres: number\n /** Lateral build multiplier (1.0 = reference adult). */\n readonly build: number\n /** Vertical distance from seat surface (H-point) to top of skull, in metres. */\n readonly seatedHeightMetres: number\n /** Vertical distance from seat surface (H-point) to eye level, in metres. */\n readonly seatedEyeHeightMetres: number\n /** Bideltoid shoulder width, in metres. */\n readonly shoulderWidthMetres: number\n /** Horizontal buttock-to-knee length (hip to front of knee), in metres. */\n readonly thighLengthMetres: number\n /** Vertical knee-to-sole length (popliteal/knee height), in metres. */\n readonly shinLengthMetres: number\n}\n\n/** Functional roles a vehicle seat can play. */\nexport const SEAT_ROLES = ['driver', 'front_passenger', 'rear', 'cargo', 'rider', 'pilot', 'crew'] as const\n\n/** Functional role of a vehicle seat. */\nexport type SeatRole = (typeof SEAT_ROLES)[number]\n\n/** Usable interior clearance of one seat in vehicle local coordinates (+x front, +y up, +z right), in metres. */\nexport type SeatSpace = {\n /** Stable seat identifier within the vehicle (e.g. 'driver', 'front_right', 'rear_left', 'rider'). */\n readonly id: string\n /** Functional role of the seat. */\n readonly role: SeatRole\n /** Seat hip point (H-point, cushion top centre) in vehicle local coordinates, in metres. */\n readonly hipPoint: Vec3\n /** Clear vertical height from hipPoint to headliner/roof (minimum of 5 rays). `Infinity` for open vehicles/bikes/boats. */\n readonly headroomMetres: number\n /** Clear longitudinal knee/leg space from hipPoint along seat facing direction to first obstruction. `Infinity` if open. */\n readonly legroomMetres: number\n /** Available lateral width at shoulder height for this seat, in metres. `Infinity` for open-sided seats. */\n readonly widthMetres: number\n /** Id of the door opening that serves this seat (matches `DoorOpening.id`); `undefined` for open entry. */\n readonly doorId?: string\n}\n\n/** Clear opening of a vehicle door or hatch, in metres. */\nexport type DoorOpening = {\n /** Matches the vehicle door zone id (e.g. 'door_front_left', 'hatch_commander'). */\n readonly id: string\n /** Clear horizontal opening width, in metres. `Infinity` if open entry. */\n readonly widthMetres: number\n /** Clear vertical opening height, in metres. `Infinity` if open entry. */\n readonly heightMetres: number\n}\n\n/** Canonical reasons a body cannot fit a seat/door pair (Spec 012 D2). */\nexport const FIT_REJECT_REASONS = ['head', 'legs', 'shoulders', 'door'] as const\n\n/** Why a body does not fit a seat/door pair (binary with reason). */\nexport type FitRejectReason = (typeof FIT_REJECT_REASONS)[number]\n\n/** Result of checking whether a body fits a seat (and optionally its access door). */\nexport type FitResult =\n | { readonly fits: true }\n | { readonly fits: false; readonly reason: FitRejectReason }\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 /**\n * The shaft of a two-handed tool (a shovel, an axe, a sledgehammer) the left hand may slide along, world space: a left grip out of the arm's reach is taken at the nearest point of\n * this segment the hand reaches, the hand still closed on the shaft, as one shortens the grip on a handle. Absent, the left hand goes to `L` or stops short of it.\n */\n slideL?: { readonly from: Vec3; readonly to: Vec3 } | 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 /** The same for the left hand (its index on the trigger of a tool of its own, with a tool in each hand); absent, the left hand's fingers all follow `gripL`. */\n fingersL?: { 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/** A hand of the body: `R` the right, `L` the left. A tool in one hand alone is in the right; the left holds one of its own only with a tool in each hand (`HostTool.offHand`). */\nexport type ToolHand = 'R' | 'L'\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). `hand` is the hand that fired (absent: the right one); a source that draws\n * one tool only answers the same for both.\n */\nexport type MuzzleSource = (hand?: ToolHand) => 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 /** The queue runs to empty in the drain of its phase, outside the frame deadline and the budget (the blow's visible effect). Counted apart. Default false. */\n readonly mustDrain?: boolean\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 BREACH_CUT: 'floorplan.breach-cut',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n AUDIO_OCCLUSION: 'audio.occlusion',\n FLUID_FILM: 'fluids.film',\n VEHICLE_LOD_BATCH: 'vehicles.lod-batch',\n SETTLED_BATCH: 'destruction.settled-batch',\n STATIC_BATCH: 'render.static-batch',\n ANIMALS_STATIC_BATCH: 'animals.static-batch',\n CHARACTERS_STATIC_BATCH: 'characters.static-batch',\n HOUSE_SHADOW_BATCH: 'floorplan.shadow-batch',\n DESTRUCTION_PREFIT: 'destruction.prefit',\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 // every frame: the walls cut since the last frame are painted once each, and a hole must show in the frame of the blast\n [DEFERRED_QUEUE_ID.BREACH_CUT]: { priority: 260, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present', minEveryFrames: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.AUDIO_OCCLUSION]: { priority: 190, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.FLUID_FILM]: { priority: 120, phase: 'idle', minEveryFrames: 2 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n [DEFERRED_QUEUE_ID.VEHICLE_LOD_BATCH]: { priority: 90, phase: 'idle', minEveryFrames: 4 },\n [DEFERRED_QUEUE_ID.SETTLED_BATCH]: { priority: 70, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.ANIMALS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.CHARACTERS_STATIC_BATCH]: { priority: 60, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.HOUSE_SHADOW_BATCH]: { priority: 50, phase: 'idle', minEveryFrames: 8 },\n [DEFERRED_QUEUE_ID.DESTRUCTION_PREFIT]: { priority: 40, phase: 'idle', minEveryFrames: 30 },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\n/** The queues that may register with `mustDrain: true`: a new one needs the owner's decision (CLAUDE.md §15), and `budget.register` throws for any other. */\nexport const MUST_DRAIN_QUEUE_IDS: ReadonlySet<string> = new Set([DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS, DEFERRED_QUEUE_ID.BREACH_CUT])\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\n/** Drains a queue no budget registered (D2): runs it until `budgetMs` from now. The one place outside game-runtime that times deferred work. */\nexport function drainDetached(queue: DeferredQueue, budgetMs: number, clock: () => number = () => performance.now()): number {\n return queue.run(clock() + budgetMs, clock)\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 picture of the real thing the card is about, with its author and licence: the host shows it on the card, linked to `page`. */\n readonly image?: { readonly url: string; readonly alt: string; readonly credit?: string; readonly page?: 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","/** A world rectangle `[x0, z0, x1, z1]`, metres. */\nexport type RainCoverBounds = readonly [x0: number, z0: number, x1: number, z1: number]\n\n/**\n * Something with a roof or a slab over it (a house, a shed, a bus stop, a car): it says, for a point on the ground plan, how high the cover over it is.\n * The rain asks before it falls, splashes or wets the ground: under a cover there is none.\n */\nexport interface RainCoverSource {\n /** Where the source may cover anything; a point outside is never asked. */\n bounds(): RainCoverBounds\n /** Top (world y, metres) of the highest intact roof or slab over (x, z); `undefined` for open sky, or for a hole a blast or a collapse opened. */\n coverTopAt(x: number, z: number): number | undefined\n /** Grows whenever the covers change (a roof panel broke, a hole opened): whoever caches reads it. */\n version(): number\n}\n\n/** What the rain reads (`ModuleHost.rainCover`): every source of the host together. */\nexport interface RainCover {\n /** The highest cover over (x, z) among the sources, or `undefined` for open sky. */\n coverTopAt(x: number, z: number): number | undefined\n /** Changes whenever a source is added or removed or one of them changes. */\n version(): number\n /** True while there is no source: the rain skips the test. */\n isEmpty(): boolean\n /** Adds a source; returns the function that takes it away. */\n add(source: RainCoverSource): () => void\n}\n\nexport function createRainCover(): RainCover {\n const sources = new Set<RainCoverSource>()\n let list: RainCoverSource[] = []\n let membership = 0\n return {\n coverTopAt(x, z) {\n let top: number | undefined\n for (const source of list) {\n const [x0, z0, x1, z1] = source.bounds()\n if (x < x0 || x > x1 || z < z0 || z > z1) continue\n const value = source.coverTopAt(x, z)\n if (value !== undefined && (top === undefined || value > top)) top = value\n }\n return top\n },\n version() {\n let sum = membership\n for (const source of list) sum += source.version()\n return sum\n },\n isEmpty: () => list.length === 0,\n add(source) {\n sources.add(source)\n list = [...sources]\n membership++\n return () => {\n if (!sources.delete(source)) return\n list = [...sources]\n membership++\n }\n },\n }\n}\n\nexport type GridRainCoverOptions = {\n readonly bounds: RainCoverBounds\n /** Side of a cell, metres (default 0.25: a blast hole is bigger). */\n readonly cellSize?: number\n /** The exact answer at a cell centre; called again for every cell only after `invalidate`. */\n readonly coverTopAt: (x: number, z: number) => number | undefined\n}\n\nexport type GridRainCoverSource = RainCoverSource & {\n /** The covers changed (a roof panel broke): the grid is cut again on the next question, and `version` grows. */\n invalidate(): void\n}\n\nconst NO_COVER = -Infinity\n\n/** A source answered from a grid cut once from `coverTopAt`: a question is two array reads, however many panels the roof has. */\nexport function createGridRainCover(options: GridRainCoverOptions): GridRainCoverSource {\n const [x0, z0, x1, z1] = options.bounds\n const cell = options.cellSize ?? 0.25\n const columns = Math.max(1, Math.ceil((x1 - x0) / cell))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cell))\n const cells = new Float32Array(columns * rows)\n let revision = 0\n let isCut = false\n const cut = (): void => {\n for (let row = 0; row < rows; row++) {\n for (let column = 0; column < columns; column++) {\n const top = options.coverTopAt(x0 + (column + 0.5) * cell, z0 + (row + 0.5) * cell)\n cells[row * columns + column] = top === undefined ? NO_COVER : top\n }\n }\n isCut = true\n }\n return {\n bounds: () => options.bounds,\n coverTopAt(x, z) {\n if (!isCut) cut()\n const column = Math.floor((x - x0) / cell)\n const row = Math.floor((z - z0) / cell)\n if (column < 0 || row < 0 || column >= columns || row >= rows) return undefined\n const top = cells[row * columns + column]!\n return top === NO_COVER ? undefined : top\n },\n version: () => revision,\n invalidate() {\n isCut = false\n revision++\n },\n }\n}\n\n/** A roof or slab seen from above: the rectangle it covers and the height of its top. */\nexport type RainCoverRect = { readonly bounds: RainCoverBounds; readonly top: number }\n\n/** A round opening in a cover (a blast hole), centre and radius in the ground plan. */\nexport type RainCoverHole = { readonly x: number; readonly z: number; readonly radius: number }\n\n/** The exact answer for a list of rectangles with holes: the highest rectangle over the point whose hole does not take the point. */\nexport function rainCoverTopOf(rects: readonly RainCoverRect[], holes: readonly RainCoverHole[], x: number, z: number): number | undefined {\n let top: number | undefined\n for (const rect of rects) {\n if (x < rect.bounds[0] || x > rect.bounds[2] || z < rect.bounds[1] || z > rect.bounds[3]) continue\n if (top !== undefined && rect.top <= top) continue\n if (holes.some((hole) => (x - hole.x) ** 2 + (z - hole.z) ** 2 <= hole.radius ** 2)) continue\n top = rect.top\n }\n return top\n}\n\n/** A roof seen from above as a turned rectangle: its centre on the ground plan, half sides along its own axes, the turn about y and the height of its top. */\nexport type RainCoverFootprint = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly yaw: number; readonly top: number }\n\nexport type FootprintRainCoverSource = RainCoverSource & {\n /**\n * Puts the roofs and the openings where they are now (a car moved, a window broke). The answer follows at once; the version grows only with `bumpVersion`,\n * which a mover asks once it has gone far enough for whoever caches (the far curtain) to cut again.\n */\n set(footprints: readonly RainCoverFootprint[], openings: readonly RainCoverFootprint[], bumpVersion: boolean): void\n}\n\ntype Prepared = { readonly x: number; readonly z: number; readonly halfX: number; readonly halfZ: number; readonly cos: number; readonly sin: number; readonly top: number }\n\nconst prepare = (f: RainCoverFootprint): Prepared => ({ x: f.x, z: f.z, halfX: f.halfX, halfZ: f.halfZ, cos: Math.cos(f.yaw), sin: Math.sin(f.yaw), top: f.top })\n\nconst insideTurned = (f: Prepared, x: number, z: number): boolean => {\n const dx = x - f.x\n const dz = z - f.z\n return Math.abs(dx * f.cos + dz * f.sin) <= f.halfX && Math.abs(-dx * f.sin + dz * f.cos) <= f.halfZ\n}\n\n/**\n * A source of turned rectangles with openings (a car's cabin, a tent, a kiosk): a question is a few multiplications per rectangle, no allocation, so the near rain\n * asks it for every drop. `set` moves the rectangles whenever the thing moves; nothing else is cut or cached.\n */\nexport function createFootprintRainCover(): FootprintRainCoverSource {\n let roofs: Prepared[] = []\n let openings: Prepared[] = []\n let bounds: RainCoverBounds = [0, 0, 0, 0]\n let revision = 0\n return {\n bounds: () => bounds,\n version: () => revision,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) {\n if ((top !== undefined && roof.top <= top) || !insideTurned(roof, x, z)) continue\n top = roof.top\n }\n if (top === undefined) return undefined\n for (const opening of openings) if (insideTurned(opening, x, z)) return undefined\n return top\n },\n set(footprints, cutouts, bumpVersion) {\n roofs = footprints.map(prepare)\n openings = cutouts.map(prepare)\n let x0 = Infinity\n let z0 = Infinity\n let x1 = -Infinity\n let z1 = -Infinity\n for (const roof of roofs) {\n const reach = Math.abs(roof.halfX * roof.cos) + Math.abs(roof.halfZ * roof.sin)\n const reachZ = Math.abs(roof.halfX * roof.sin) + Math.abs(roof.halfZ * roof.cos)\n x0 = Math.min(x0, roof.x - reach)\n x1 = Math.max(x1, roof.x + reach)\n z0 = Math.min(z0, roof.z - reachZ)\n z1 = Math.max(z1, roof.z + reachZ)\n }\n bounds = roofs.length === 0 ? [0, 0, 0, 0] : [x0, z0, x1, z1]\n if (bumpVersion) revision++\n },\n }\n}\n\n/** The most cells a fixed footprint cover cuts: a wide district gets a coarser cell instead of a bigger grid. */\nconst FIXED_COVER_MAX_CELLS = 1_000_000\n\n/** A source of turned rectangles that never move (the buildings of a district, a tent, a kiosk): answered from a grid cut once, two array reads a question however many roofs there are. */\nexport function createFixedFootprintRainCover(footprints: readonly RainCoverFootprint[], cellSize = 0.5): RainCoverSource {\n const roofs = footprints.map(prepare)\n if (roofs.length === 0) return { bounds: () => [0, 0, 0, 0], coverTopAt: () => undefined, version: () => 0 }\n const x0 = Math.min(...roofs.map((r) => r.x - Math.abs(r.halfX * r.cos) - Math.abs(r.halfZ * r.sin)))\n const x1 = Math.max(...roofs.map((r) => r.x + Math.abs(r.halfX * r.cos) + Math.abs(r.halfZ * r.sin)))\n const z0 = Math.min(...roofs.map((r) => r.z - Math.abs(r.halfX * r.sin) - Math.abs(r.halfZ * r.cos)))\n const z1 = Math.max(...roofs.map((r) => r.z + Math.abs(r.halfX * r.sin) + Math.abs(r.halfZ * r.cos)))\n const cell = Math.max(cellSize, Math.sqrt(((x1 - x0) * (z1 - z0)) / FIXED_COVER_MAX_CELLS))\n return createGridRainCover({\n bounds: [x0, z0, x1, z1],\n cellSize: cell,\n coverTopAt(x, z) {\n let top: number | undefined\n for (const roof of roofs) if ((top === undefined || roof.top > top) && insideTurned(roof, x, z)) top = roof.top\n return top\n },\n })\n}\n","/** What an obstacle on the ground is to a walker: a solid (a wall, a lot wall, a fence, a board) or a door (a door or a gate, which opens and can be broken). */\nexport const NAV_OBSTACLE_KIND = { SOLID: 'solid', DOOR: 'door' } as const\nexport type NavObstacleKind = (typeof NAV_OBSTACLE_KIND)[keyof typeof NAV_OBSTACLE_KIND]\n\n/** A box of an obstacle on the ground: world metres `[x0, z0, x1, z1]` and how high it stands over the ground (a low remnant of a wall can be climbed). */\nexport type NavObstacleBox = {\n readonly rect: readonly [number, number, number, number]\n readonly height: number\n}\n\n/**\n * One thing that stops a walker on the ground, as the SDK that builds it publishes it for a navigation grid (the crowd's): a whole wall is one box, a wall a blast\n * cut stands in the boxes of what is left of it, a wall that is gone has none. A door is one box, passable while `open`.\n */\nexport type NavObstacle = {\n /** Stable for the life of the source: a change names the same obstacle again. */\n readonly id: string\n readonly kind: NavObstacleKind\n readonly boxes: readonly NavObstacleBox[]\n /** A door or a gate that lets walkers through now (always false for a solid). */\n readonly open: boolean\n /** A door the barricade's boards cover, each making it harder to break (0 for none). */\n readonly boards: number\n}\n\n/**\n * The obstacles one or more SDKs put on the ground (the houses' walls, doors, lot walls and gates), for whoever keeps a navigation grid. Pulled once per fixed step, so a\n * grid that follows it changes at the same step on every run.\n */\nexport type NavObstacleSource = {\n /** Every obstacle as it stands now. */\n obstacles(): readonly NavObstacle[]\n /** The obstacles that changed since the last call (a door opened or closed, a wall cut or gone); empty when none did. */\n changes(): readonly NavObstacle[]\n /** A walker broke the door `id` open (the horde hit it until it gave way): the owner shows it open. */\n breakDoor(id: string): void\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 laterite: 'gravel',\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 * The worker coordinator as the packages see it: a package declares its heavy work as a task kind (a pure function of plain data) or a\n * resident kind (an instance pinned to one worker), and takes a `WorkerCoordinator` through its options. The implementation is\n * `@adatechnology/game-workers`; nothing in a package makes a `Worker` of its own (CLAUDE.md §14).\n */\n\n/**\n * The pools a kind runs in. `sim`: physics and anything the next frames read; the result is applied in a fixed frame and computed on the\n * main thread when the worker is late, so it is the same whichever thread made it. `build`: generation at load (shapes, colliders,\n * normals), no frame deadline. `background`: the living world far from the player, the lowest priority, never takes a `sim` worker.\n */\nexport const WORKER_LANES = ['sim', 'build', 'background'] as const\nexport type WorkerLane = (typeof WORKER_LANES)[number]\n\n/**\n * What happens when no worker answers in time (or there is none). `sync`: the main thread runs the same kernel and the late answer is\n * thrown away (the only rule of the `sim` lane). `drop`: the job is given up and its promise rejects with `WorkerTaskDropped`.\n * `keep-waiting`: it waits for a worker (a fresh one after a crash); with no worker at all it runs on the main thread.\n */\nexport const WORKER_LATE_RULES = ['sync', 'drop', 'keep-waiting'] as const\nexport type WorkerLateRule = (typeof WORKER_LATE_RULES)[number]\n\n/** How a kind is scheduled: the defaults the kind declares, any of which a game may override by id (`CoordinatorOptions.kinds`). */\nexport interface WorkerKindSchedule {\n readonly lane: WorkerLane\n /** Higher runs first, as `DEFERRED_PRIORITY`. */\n readonly priority: number\n /** Frames between the frame a job is submitted in and the frame its result is applied in (`sim` lane; default 1). */\n readonly latencyFrames?: number\n readonly late: WorkerLateRule\n}\n\n/**\n * A job with no state: plain data in, plain data out, through `run`, the same function in the worker and on the main thread. `run` reads\n * nothing but its input (a seed travels inside it), so the bytes out are the same whichever thread ran it.\n */\nexport interface TaskKind<In, Out> extends WorkerKindSchedule {\n /** `package.thing`, unique in a coordinator: `destruction.ground-tiles`. */\n readonly id: string\n readonly kind: 'task'\n run(input: In): Out\n /** The buffers of the output to transfer back (zero copy). The input is copied, never transferred, when `late` is `sync` (unless `transferAwaitedInput`): the main thread may still need it. */\n transferOutput?(value: Out): readonly ArrayBuffer[]\n /** The buffers of the input to transfer when `late` is not `sync` (and on awaited jobs of a `sync` kind with `transferAwaitedInput`). */\n transferInput?(value: In): readonly ArrayBuffer[]\n /**\n * With `late: 'sync'`, transfer the input (`transferInput`) on awaited jobs (`run`) too, instead of copying it: for a caller that keeps its own copy of the input for its\n * own fallback (the ground tiles). Once sent, such a job is never run on the main thread (its input is gone): a worker that dies holding it rejects its promise with an\n * error named `WORKER_INPUT_LOST` (`isWorkerInputLost`: the caller makes it from its own copy), one that answers with an error rejects with that error. Jobs read through\n * `submit`/`collect` still copy their input.\n * Needs `transferInput`.\n */\n readonly transferAwaitedInput?: boolean\n /** One input each worker runs once at `warm` (the JIT compiles the kernel before the first real job). */\n readonly warmup?: In\n}\n\n/** One instance of a resident kind: built from `init` once per worker, then stepped. */\nexport interface ResidentInstance<Step, Result> {\n step(input: Step): Result\n dispose?(): void\n}\n\n/**\n * A kind with an instance pinned to one worker (the crowd physics, a region of the world). With `late: 'sync'` the step must be a pure\n * function of `init` and the step's input (the state lives on the main thread and travels each step), so a main-thread instance gives the\n * same result; a resident that keeps its own state in the worker uses `drop` or `keep-waiting`.\n */\nexport interface ResidentKind<Init, Step, Result> extends WorkerKindSchedule {\n readonly id: string\n readonly kind: 'resident'\n create(init: Init): ResidentInstance<Step, Result>\n transferOutput?(value: Result): readonly ArrayBuffer[]\n transferInput?(value: Step): readonly ArrayBuffer[]\n}\n\n/** A kind of any input and output, for registries (the methods are bivariant, so every `TaskKind<In, Out>` is one). */\nexport type AnyTaskKind = TaskKind<unknown, unknown>\nexport type AnyResidentKind = ResidentKind<unknown, unknown, unknown>\nexport type AnyWorkerKind = AnyTaskKind | AnyResidentKind\n\n/** Where a result came from. `worker`: on time. `main`: the main thread ran it (late worker, crash, or no worker). */\nexport type WorkerResultSource = 'worker' | 'main'\n\n/** A job of the `sim` lane: its result is read in `dueFrame`, never before, whichever thread made it. */\nexport interface TaskHandle<Out> {\n readonly dueFrame: number\n /**\n * The result in `frame` (>= `dueFrame`, an error before it): the worker's when it is back, otherwise the kernel run here now and the\n * late answer thrown away. The same value on every later call.\n */\n collect(frame: number): Out\n /** Resolves when the result exists (worker or main thread); for the `build` and `background` lanes. */\n readonly promise: Promise<Out>\n /** Where the collected result came from; `null` before `collect` or the promise settles. */\n readonly source: WorkerResultSource | null\n /** Drops a job not yet collected: it leaves the queue, or its answer is thrown away. */\n cancel(): void\n}\n\nexport interface ResidentHandle<Step, Result> {\n readonly id: string\n /** Steps the instance with `input` in `frame`; read the result with `collect(dueFrame)`. The input is the coordinator's from here on. */\n step(input: Step, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Result>\n dispose(): void\n}\n\nexport interface WorkerKindStats {\n readonly id: string\n readonly lane: WorkerLane\n readonly submitted: number\n /** Answers that came back from a worker, on time or late. */\n readonly answered: number\n /** Results that came from a worker before they were needed. */\n readonly onTime: number\n /** Results the main thread computed (late worker, crash, no worker). */\n readonly fallback: number\n readonly dropped: number\n readonly cancelled: number\n readonly failed: number\n /** Milliseconds inside the worker, summed over `answered`. */\n readonly workerMs: number\n /** Milliseconds on the main thread, summed (fallbacks). */\n readonly mainMs: number\n /** Milliseconds waiting in the queue before a worker took the job, summed. */\n readonly queueMs: number\n}\n\nexport interface WorkerCoordinatorStats {\n readonly workers: number\n readonly lanes: Readonly<Record<WorkerLane, number>>\n readonly queued: number\n readonly running: number\n readonly respawned: number\n readonly kinds: readonly WorkerKindStats[]\n}\n\nexport interface WorkerCoordinator {\n /** A `sim` job submitted in `at.frame` (default: the last `tick`), due `latencyFrames` later. The input is the coordinator's from here on: do not change it. */\n submit<In, Out>(kind: TaskKind<In, Out>, input: In, at?: { readonly frame?: number; readonly latencyFrames?: number }): TaskHandle<Out>\n /**\n * A job awaited instead of collected: a `build` or `background` job, or a `sim` job in the simulation thread (which may wait; with no worker\n * it runs on this thread). A promise, cancelled through `signal`.\n */\n run<In, Out>(kind: TaskKind<In, Out>, input: In, signal?: AbortSignal): Promise<Out>\n /** An instance of a resident kind on one worker (or on the main thread when there is none). */\n resident<Init, Step, Result>(kind: ResidentKind<Init, Step, Result>, init: Init): ResidentHandle<Step, Result>\n /** The frame now; the runtime calls it at the start of each fixed step. Jobs are ordered by priority, then by the nearest due frame. */\n tick(frame: number): void\n /** Starts the workers and runs each kind's `warmup` in every worker; rejects when a worker does not know one of the kinds. */\n warm(kinds: readonly AnyWorkerKind[]): Promise<void>\n /** The schedule a kind runs with here (its own, with the game's overrides). */\n scheduleOf(kind: AnyWorkerKind): WorkerKindSchedule\n stats(): WorkerCoordinatorStats\n dispose(): void\n}\n\n/** The ids of the kit's kinds (`TaskKind.id` / `ResidentKind.id`), what `WORKER_KIND_DEFAULTS` is keyed by. */\nexport const WORKER_KIND_ID = {\n GROUND_TILES: 'destruction.ground-tiles',\n CROWD_PHYSICS: 'crowd.physics',\n PIECE_BOXES: 'destruction.piece-boxes',\n STATIC_COLLIDERS: 'destruction.static-colliders',\n SHAPES_GENERATE: 'shapes.generate',\n WORLD_REGION: 'world.region',\n VEHICLE_HULL_PLAN: 'vehicles.hull-plan',\n} as const\n\n/** Default schedule of the kit's kinds; each kind carries its own copy, a game overrides any of them by id. */\nexport const WORKER_KIND_DEFAULTS = {\n [WORKER_KIND_ID.GROUND_TILES]: { lane: 'sim', priority: 300, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.CROWD_PHYSICS]: { lane: 'sim', priority: 250, latencyFrames: 1, late: 'sync' },\n [WORKER_KIND_ID.PIECE_BOXES]: { lane: 'sim', priority: 200, latencyFrames: 2, late: 'sync' },\n [WORKER_KIND_ID.STATIC_COLLIDERS]: { lane: 'build', priority: 150, late: 'sync' },\n [WORKER_KIND_ID.SHAPES_GENERATE]: { lane: 'build', priority: 100, late: 'sync' },\n [WORKER_KIND_ID.WORLD_REGION]: { lane: 'background', priority: 10, latencyFrames: 10, late: 'drop' },\n [WORKER_KIND_ID.VEHICLE_HULL_PLAN]: { lane: 'build', priority: 120, late: 'keep-waiting' },\n} as const satisfies Readonly<Record<string, WorkerKindSchedule>>\n\n/** The name of the error an awaited job with a transferred input (`transferAwaitedInput`) rejects with when its worker died holding it. */\nexport const WORKER_INPUT_LOST = 'WorkerTaskInputLost'\n\n/** Whether a rejection is that of a job whose transferred input was lost with its worker (`WORKER_INPUT_LOST`): the caller's own fallback makes it, nothing else is wrong. */\nexport const isWorkerInputLost = (error: unknown): boolean => error instanceof Error && error.name === WORKER_INPUT_LOST\n\n/*\n * The simulation thread (spec 009, T22): a game's whole fixed step in one worker that may wait. A package declares its simulation as a\n * `SimModule`; `@adatechnology/game-workers` runs it (`installSimThread`, `startSimThread`, `runSimInline`).\n */\n\n/** One running simulation, built in the simulation thread from the start message's `init`. */\nexport interface SimInstance {\n /**\n * One fixed step. It may return a promise: the loop waits for it (jobs handed to the coordinator are awaited, not raced against a frame),\n * so the result never depends on how fast the other workers were.\n */\n step(frame: number, dt: number, commands: readonly Float64Array[]): void | Promise<void>\n /** Writes the state the page draws into `out` (the snapshot's bytes, `snapshotBytes` long). */\n write(out: Uint8Array, frame: number): void\n dispose?(): void\n}\n\n/** What the simulation thread can build, by id (the worker's file registers every module the game starts). */\nexport interface SimModule<Init> {\n /** `package.thing`: `crowd.horde`. */\n readonly id: string\n create(init: Init): SimInstance | Promise<SimInstance>\n}\nexport type AnySimModule = SimModule<unknown>\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 BendHinge,\n Dent,\n DestructibleSpec,\n BlastCasing,\n BlastCharge,\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 PartAperture,\n PartShape,\n PartSpec,\n CarryHands,\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 GroundLoss,\n PartSettlement,\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 { chargeFireball, fireballDose, fuelFireball, ignitionDose } from './fireball'\nexport { TNT_JOULES, reflectedLoad, waveWork } from './blast-wave'\nexport type { WaveLoad, WaveWork, WaveWorkInput } from './blast-wave'\nexport type { Fireball } from './fireball'\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, sideOnOverpressure } 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, DrawnCollider, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport type { ToolCondition } from './tool-condition'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { FIT_REJECT_REASONS, SEAT_ROLES } from './body-measures'\nexport type { BodyMeasures, DoorOpening, FitRejectReason, FitResult, SeatRole, SeatSpace } from './body-measures'\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, ToolHand } from './hands'\nexport { FIRST_PERSON_LAYER } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectPose, 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, MUST_DRAIN_QUEUE_IDS, checkDeferredQueue, drainDetached } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundExcavation, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, CornerImage, ModuleArea, ModuleHost, HostMovable, HostShove, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach, HostTakenItem, HostTap } 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 { createFixedFootprintRainCover, createFootprintRainCover, createGridRainCover, createRainCover, rainCoverTopOf } from './rain-cover'\nexport type { FootprintRainCoverSource, GridRainCoverOptions, GridRainCoverSource, RainCover, RainCoverBounds, RainCoverFootprint, RainCoverHole, RainCoverRect, RainCoverSource } from './rain-cover'\nexport type { UtilityConnection, UtilityNetwork } from './utility'\nexport type { Footprint, FootprintObject } from './footprint'\nexport { NAV_OBSTACLE_KIND } from './nav-obstacles'\nexport type { NavObstacle, NavObstacleBox, NavObstacleKind, NavObstacleSource } from './nav-obstacles'\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'\nexport { WORKER_INPUT_LOST, WORKER_KIND_DEFAULTS, WORKER_KIND_ID, WORKER_LANES, WORKER_LATE_RULES, isWorkerInputLost } from './workers'\nexport type { AnyResidentKind, AnySimModule, AnyTaskKind, AnyWorkerKind, ResidentHandle, ResidentInstance, ResidentKind, SimInstance, SimModule, TaskHandle, TaskKind, WorkerCoordinator, WorkerCoordinatorStats, WorkerKindSchedule, WorkerKindStats, WorkerLane, WorkerLateRule, WorkerResultSource } from './workers'\n","import { TNT_JOULES } from '@adatechnology/game-contracts'\nimport type { Hit } from '@adatechnology/game-contracts'\nimport { DEFAULT_BAR_DIAMETER, DEFAULT_BAR_YIELD_JOULES, DEFAULT_BAR_YIELD_PA, DEFAULT_PROFILE, TERRAIN_MATERIALS, TERRAIN_PROFILES } from './catalog'\nimport { createCrackStore, CRACK_REFERENCE_JOULES } from './cracks'\nimport { createDebrisStore } from './debris'\nimport { lossOf, SLIDE_LOSS_MIN_LOWERING, tallyLowered, voidUnder } from './ground-loss'\nimport type { HeightGrid, LossTally } from './ground-loss'\nimport { blendHeights, cellCoordinate as cellCoordinateOf } from './height-patch'\nimport type { HeightPatch } from './height-patch'\nimport { createMarkStore } from './marks'\nimport { createRandom } from './random'\nimport type { GroundExcavation, GroundLayout, Terrain, TerrainDig, TerrainDigResult, TerrainFill, TerrainBlow, TerrainBlowResult, TerrainBudget, TerrainChunk, TerrainColumn, TerrainDebris, TerrainDecal, TerrainLoad, TerrainMark, TerrainMaterial, TerrainOptions, TerrainProfile, TerrainRegion, TerrainSnapshot, TerrainStratum, TerrainStrike } from './types'\n\nexport const DEFAULT_TERRAIN_BUDGET: TerrainBudget = {\n markAreaSize: 2,\n maxMarksPerArea: 24,\n maxMarks: 800,\n maxDirtyChunksPerFrame: 6,\n maxDebris: 400,\n maxDebrisPerBlow: 36,\n maxSlideCellsPerFrame: 2500,\n maxBurningCells: 300,\n maxCracks: 120,\n maxDecals: 300,\n}\n\nconst GRAVITY = 9.81\n/** A bowl narrower than this many cells cannot be drawn by the height field: it stays a fine mark. */\nconst FINE_CELLS = 1.5\n/** A hole deeper than this many cells is no longer a mark on the surface. */\nconst FINE_DEPTH_CELLS = 0.4\nconst RIGID_WIDENING = 2.5\n/** Calibre (mm) a round's crater has the material's own shape at: a thinner round goes deeper and opens less for the same energy, a thicker one opens more. */\nconst REFERENCE_CALIBER = 7.62\n/** How far a calibre bends the crater's depth over its radius: (reference / calibre) to this power, kept within `CALIBER_ASPECT_RANGE`. */\nconst CALIBER_ASPECT_POWER = 0.5\nconst CALIBER_ASPECT_RANGE = [0.6, 1.6] as const\n/** A round's crater is at least this many calibres across. */\nconst CALIBERS_ACROSS = 2.5\n\n/** Depth-over-radius factor of a round's crater: 1 without a calibre or at the reference one. */\nconst caliberAspect = (caliber: number | undefined): number =>\n caliber && caliber > 0 ? Math.min(CALIBER_ASPECT_RANGE[1], Math.max(CALIBER_ASPECT_RANGE[0], (REFERENCE_CALIBER / caliber) ** CALIBER_ASPECT_POWER)) : 1\n/** The smallest crater radius (m) a round of `caliber` mm leaves. */\nconst caliberRadius = (caliber: number | undefined): number => (caliber && caliber > 0 ? (caliber / 1000) * CALIBERS_ACROSS / 2 : 0)\n/** Bars alone do not drop a slab that still has this share of its concrete to lose. */\nconst COLLAPSE_DEPTH_SHARE = 0.75\nconst COLLAPSE_SPREAD_BEND = 0.5\n/** Metres around a weight over which bare bars share it with the weights beside it. */\nconst BARS_SHARE_REACH = 0.6\nconst RIM_REACH = 1.45\n/** Under this temperature (°C) a flame does nothing to the ground. */\nconst FLAME_MINIMUM = 200\n/** How far over the ground a flame still touches it, beyond its radius. */\nconst FLAME_REACH = 0.6\n/** How far a blast above the ground still reaches it, as a share of its radius. */\nconst BLAST_HEIGHT_REACH = 0.35\n/**\n * Metres of ground the fireball of a 1 MJ blast blackens, growing with the cube root of the energy (a frag grenade, 200 kJ: about 0.7 m), and the share of\n * the material's darkest char (`TerrainFireResponse.maxScorch`) it leaves at the centre, fading to the edge: concrete only soots, turf chars.\n */\nconst BLAST_SOOT_REACH = 1.2\nconst BLAST_SOOT = 0.9\n/** Share of a blow's energy that throws the pieces. */\nconst THROW_SHARE = 0.02\n/** Side of a square of ground that burns as one, in metres. */\nconst FIRE_CELL = 0.5\nconst FIRE_SECONDS = 7\nconst FIRE_SPREAD_PER_SECOND = 0.35\nconst SLIDE_SHARE = 0.4\nconst SLIDE_EPSILON = 0.002\n/** Radius of a thrown piece per kind: a clod is a fist of soil, a chip is a thumb of concrete. */\nconst PIECE_RADIUS: Record<TerrainMaterial['debris'], number> = { clods: 0.045, chips: 0.022, shards: 0.028, splinters: 0.02, dust: 0.012, blocks: 0.08 }\n/** Metres per second the fastest piece of a blow leaves at: a blast throws, a dropped weight only kicks. */\nconst MAX_PIECE_SPEED: Record<TerrainBlow, number> = { explosive: 14, ballistic: 5, blunt: 2.5, slash: 1.5 }\n\n/** Cells the bed takes to go from the bank down to the full depth, so that a body wades in instead of falling. */\nconst BANK_CELLS = 6\nconst CRACK_MIN_RADIUS = 0.18\nconst RIPPLE_SECONDS = 1.6\n/** Water thinner than this at the bank neither splashes nor floats anything. */\nconst WATER_MINIMUM = 0.02\n\nconst clampIndex = (value: number, max: number): number => Math.max(0, Math.min(max, value))\nconst sparse = (array: Float32Array): [number, number][] => {\n const entries: [number, number][] = []\n array.forEach((value, index) => {\n if (value !== 0) entries.push([index, value])\n })\n return entries\n}\nconst fillSparse = (array: Float32Array, entries: readonly (readonly [number, number])[]): void => {\n array.fill(0)\n for (const [index, value] of entries) array[index] = value\n}\n\n/** Layer a depth falls in; past the end, the last one. */\nfunction stratumAtDepth(profile: TerrainProfile, depth: number): { index: number; stratum: TerrainStratum; top: number } {\n let top = 0\n for (let index = 0; index < profile.strata.length; index++) {\n const stratum = profile.strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return { index, stratum, top }\n top += stratum.thickness\n }\n const index = profile.strata.length - 1\n const stratum = profile.strata[index]!\n return { index, stratum, top: top - stratum.thickness }\n}\n\n/** Same stratum as `stratumAtDepth`, without allocating: per-read paths (state(), fire per vertex) must not create garbage. */\nfunction stratumMaterialAtDepth(profile: TerrainProfile, depth: number): string {\n const strata = profile.strata\n let top = 0\n for (let index = 0; index < strata.length; index++) {\n const stratum = strata[index]!\n if (depth < top + stratum.thickness - 1e-6) return stratum.material\n top += stratum.thickness\n }\n return strata[strata.length - 1]!.material\n}\nconst totalThickness = (profile: TerrainProfile): number => profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n\nexport function createTerrain(options: TerrainOptions): Terrain {\n const [x0, z0, x1, z1] = options.bounds\n const cellSize = options.cellSize ?? 0.1\n const chunkCells = options.chunkCells ?? 32\n const columns = Math.max(1, Math.ceil((x1 - x0) / cellSize))\n const rows = Math.max(1, Math.ceil((z1 - z0) / cellSize))\n const stride = columns + 1\n const vertexCount = stride * (rows + 1)\n const chunksX = Math.ceil(columns / chunkCells)\n const chunksZ = Math.ceil(rows / chunkCells)\n const budget: TerrainBudget = { ...DEFAULT_TERRAIN_BUDGET, ...options.budget }\n const gravity = options.gravity ?? GRAVITY\n const materials = new Map<string, TerrainMaterial>([...TERRAIN_MATERIALS, ...(options.materials ?? [])].map((material) => [material.id, material]))\n const profileMap = new Map<string, TerrainProfile>([...TERRAIN_PROFILES, ...(options.profiles ?? [])].map((profile) => [profile.id, profile]))\n const profileList = [...profileMap.values()]\n for (const profile of profileList) {\n for (const stratum of profile.strata) if (!materials.has(stratum.material)) throw new Error(`game-terrain: profile \"${profile.id}\" uses material \"${stratum.material}\", which has no ground behaviour`)\n }\n const indexOfProfile = new Map(profileList.map((profile, index) => [profile.id, index]))\n const maxDepthOf = profileList.map(totalThickness)\n\n // `surface` is the ground as the map has it; `base` is that less the water standing on it, so that everything that stands on the ground stands on the bed\n const surface = new Float32Array(vertexCount)\n if (options.baseHeight) {\n for (let row = 0; row <= rows; row++) for (let column = 0; column <= columns; column++) surface[row * stride + column] = options.baseHeight(x0 + column * cellSize, z0 + row * cellSize)\n }\n const base = Float32Array.from(surface)\n const hasWater = profileList.some((profile) => profile.water)\n const dug = new Float32Array(vertexCount)\n const loose = new Float32Array(vertexCount)\n const scorch = new Float32Array(vertexCount)\n const barBend = new Float32Array(vertexCount)\n const profileIndex = new Uint8Array(vertexCount)\n const touched = new Uint8Array(chunksX * chunksZ)\n const mixed = new Uint8Array(chunksX * chunksZ)\n const dirty = new Set<number>()\n const marks = createMarkStore(budget)\n const cracks = createCrackStore()\n const decalList: TerrainDecal[] = []\n let decalSerial = 0\n let decalsVersion = 0\n const unitDamage = new Map<string, number>()\n const debrisStore = createDebrisStore(() => budget.maxDebris)\n const sliding = new Set<number>()\n const burning = new Map<number, number>()\n const seed = options.seed ?? 1\n let random = createRandom(seed)\n let currentLayout: GroundLayout = options.layout ?? { surface: DEFAULT_PROFILE }\n\n const deformListeners = new Set<(region: TerrainRegion) => void>()\n const emitDeform = (x: number, z: number, radius: number): void => {\n for (const listener of deformListeners) listener({ x, z, radius })\n }\n const grid: HeightGrid = { x0, z0, cellSize, stride, columns, rows, dug }\n /** Sand that is still sliding: what it lowered so far, told once it comes to rest. */\n const slideTally: LossTally = new Map()\n const emitGroundLoss = (tally: LossTally, source: string, minLowering: number): void => {\n if (!options.onGroundLoss) return\n const loss = lossOf(grid, tally, { source, minLowering, shape: source === 'slab' ? 'flat' : 'bowl' })\n if (loss) options.onGroundLoss(loss)\n }\n /** Lowers a vertex to `depth` under the untouched surface, counting it in `tally`. */\n const dropVertex = (index: number, depth: number, tally: LossTally): void => {\n tallyLowered(tally, index, depth - dug[index]!)\n dug[index] = depth\n }\n\n const chunkOfVertex = (column: number, row: number): number => Math.min(chunksZ - 1, Math.floor(row / chunkCells)) * chunksX + Math.min(chunksX - 1, Math.floor(column / chunkCells))\n /** A vertex on a chunk's edge belongs to its neighbours as well. */\n function touchVertex(column: number, row: number): void {\n const chunk = chunkOfVertex(column, row)\n touched[chunk] = 1\n dirty.add(chunk)\n if (column % chunkCells === 0 && column > 0) markChunk(chunk - 1)\n if (row % chunkCells === 0 && row > 0) markChunk(chunk - chunksX)\n if (column % chunkCells === 0 && row % chunkCells === 0 && column > 0 && row > 0) markChunk(chunk - chunksX - 1)\n }\n function markChunk(chunk: number): void {\n touched[chunk] = 1\n dirty.add(chunk)\n }\n\n const profileId = (id: string): number => indexOfProfile.get(id) ?? indexOfProfile.get(DEFAULT_PROFILE) ?? 0\n\n function applyLayout(layout: GroundLayout): void {\n currentLayout = layout\n profileIndex.fill(profileId(layout.surface))\n for (const zone of layout.zones ?? []) {\n const index = profileId(zone.surface)\n const [zx0, zz0, zx1, zz1] = zone.rect\n const column0 = clampIndex(Math.round((zx0 - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((zx1 - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((zz0 - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((zz1 - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) profileIndex.fill(index, row * stride + column0, row * stride + column1 + 1)\n }\n if (hasWater) layBeds()\n for (let chunkZ = 0; chunkZ < chunksZ; chunkZ++) {\n for (let chunkX = 0; chunkX < chunksX; chunkX++) {\n const chunk = chunkZ * chunksX + chunkX\n const first = profileIndex[(chunkZ * chunkCells) * stride + chunkX * chunkCells]\n const firstDrop = surface[(chunkZ * chunkCells) * stride + chunkX * chunkCells]! - base[(chunkZ * chunkCells) * stride + chunkX * chunkCells]!\n let isMixed = 0\n const lastRow = Math.min(rows, (chunkZ + 1) * chunkCells)\n const lastColumn = Math.min(columns, (chunkX + 1) * chunkCells)\n for (let row = chunkZ * chunkCells; row <= lastRow && !isMixed; row++) {\n for (let column = chunkX * chunkCells; column <= lastColumn; column++) {\n if (profileIndex[row * stride + column] !== first || surface[row * stride + column]! - base[row * stride + column]! !== firstDrop) {\n isMixed = 1\n break\n }\n }\n }\n mixed[chunk] = isMixed\n dirty.add(chunk)\n }\n }\n for (const excavation of layout.excavations ?? []) excavate(excavation)\n }\n\n /**\n * Digs a construction's trench or pit: every vertex over the rectangle (the cell it starts in to the one it ends in, so the full depth spans the whole\n * rectangle and the wall slopes in the cell outside it) down to its depth, never less deep than it already was. A planned dig is no ground loss.\n */\n function excavate(excavation: GroundExcavation): void {\n const [ex0, ez0, ex1, ez1] = excavation.rect\n const column0 = clampIndex(Math.floor((ex0 - x0) / cellSize + 1e-6), columns)\n const column1 = clampIndex(Math.ceil((ex1 - x0) / cellSize - 1e-6), columns)\n const row0 = clampIndex(Math.floor((ez0 - z0) / cellSize + 1e-6), rows)\n const row1 = clampIndex(Math.ceil((ez1 - z0) / cellSize - 1e-6), rows)\n const alongX = (excavation.along ?? (ex1 - ex0 >= ez1 - ez0 ? 'x' : 'z')) === 'x'\n const from = alongX ? ex0 : ez0, length = Math.max(1e-6, alongX ? ex1 - ex0 : ez1 - ez0)\n const far = excavation.toDepth ?? excavation.depth\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const at = alongX ? x0 + column * cellSize : z0 + row * cellSize\n const t = Math.max(0, Math.min(1, (at - from) / length))\n const depth = excavation.depth + (far - excavation.depth) * t\n if (depth <= dug[index]!) continue\n dug[index] = depth\n touchVertex(column, row)\n }\n }\n }\n\n /** Lowers the ground under the water, in a bank from the edge of each pool. */\n function layBeds(): void {\n const steps = new Uint8Array(vertexCount)\n for (let index = 0; index < vertexCount; index++) steps[index] = profileList[profileIndex[index]!]!.water ? BANK_CELLS : 0\n for (let pass = 0; pass < BANK_CELLS; pass++) {\n for (let row = 0; row <= rows; row++) {\n for (let column = 0; column <= columns; column++) {\n const index = row * stride + column\n if (steps[index] === 0) continue\n const lowest = Math.min(column > 0 ? steps[index - 1]! : BANK_CELLS, column < columns ? steps[index + 1]! : BANK_CELLS, row > 0 ? steps[index - stride]! : BANK_CELLS, row < rows ? steps[index + stride]! : BANK_CELLS)\n steps[index] = Math.min(steps[index]!, lowest + 1)\n }\n }\n }\n for (let index = 0; index < vertexCount; index++) base[index] = surface[index]! - (profileList[profileIndex[index]!]!.water?.depth ?? 0) * (steps[index]! / BANK_CELLS)\n }\n\n const vertexHeight = (column: number, row: number): number => {\n const index = row * stride + column\n return base[index]! - dug[index]! + loose[index]!\n }\n const contains = (x: number, z: number): boolean => x >= x0 && x <= x1 && z >= z0 && z <= z1\n\n function addDecal(spec: Omit<TerrainDecal, 'id' | 'age'>): void {\n if (decalList.length >= budget.maxDecals) decalList.shift()\n decalList.push({ ...spec, id: ++decalSerial, age: 0 })\n decalsVersion++\n }\n function clearDecalsInside(x: number, z: number, radius: number): void {\n const before = decalList.length\n for (let i = before - 1; i >= 0; i--) {\n const decal = decalList[i]!\n if (decal.kind !== 'ripple' && decal.kind !== 'splat' && decal.kind !== 'crack' && Math.hypot(decal.x - x, decal.z - z) < radius) decalList.splice(i, 1)\n }\n if (decalList.length !== before) decalsVersion++\n }\n\n // `heightAt` and `heightGrid` are twins: both find a point's cell with `cellCoordinate` and blend its corners with `blendCell`, so the grid answers what the point does, to the bit\n /** Where `v` falls along an axis of `count` cells from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\n // the blend and the cell are `height-patch`'s, so a patch read anywhere (`heightPatchGrid`) answers what these do\n const cellCoordinate = (v: number, origin: number, count: number): number => cellCoordinateOf(v, origin, count, cellSize)\n const heightOfVertex = (index: number): number => base[index]! - dug[index]! + loose[index]!\n /** The ground in the cell whose first corner is vertex `index`, `tx` and `tz` across it. */\n const blendCell = (index: number, tx: number, tz: number): number =>\n blendHeights(blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx), blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx), tz)\n\n function heightAt(x: number, z: number): number {\n // beyond the terrain the ground is untouched: no blow can dig it and a piece thrown out lands on it\n if (!contains(x, z)) return options.baseHeight?.(x, z) ?? 0\n const fx = cellCoordinate(x, x0, columns)\n const fz = cellCoordinate(z, z0, rows)\n const column = fx | 0\n const row = fz | 0\n return blendCell(row * stride + column, fx - column, fz - row)\n }\n\n // the cell and the blend of each column and row a grid reads, kept between grids so a read costs no new arrays\n let gridColumns = new Int32Array(0)\n let gridBlendX = new Float64Array(0)\n let gridRows = new Int32Array(0)\n let gridBlendZ = new Float64Array(0)\n let gridNear = new Float64Array(0)\n let gridFar = new Float64Array(0)\n\n function heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n if (gridColumns.length < width) {\n gridColumns = new Int32Array(width)\n gridBlendX = new Float64Array(width)\n }\n if (gridRows.length < depth) {\n gridRows = new Int32Array(depth)\n gridBlendZ = new Float64Array(depth)\n }\n // each column and row as `heightAt` finds it (-1: past the terrain, where the host's `baseHeight` answers), so every height is the one `heightAt` gives, to the bit\n for (let i = 0; i < width; i++) {\n const x = xs[i]!\n const fx = cellCoordinate(x, x0, columns)\n gridColumns[i] = x >= x0 && x <= x1 ? fx | 0 : -1\n gridBlendX[i] = fx - (fx | 0)\n }\n for (let j = 0; j < depth; j++) {\n const z = zs[j]!\n const fz = cellCoordinate(z, z0, rows)\n gridRows[j] = z >= z0 && z <= z1 ? fz | 0 : -1\n gridBlendZ[j] = fz - (fz | 0)\n }\n // `blendCell` blends along x first, then along z: the two x blends of a column depend on its row only, so they are made once per row of cells and\n // each point is then the same last step `blendCell` takes, on the same numbers (the same bits); a lattice finer than the cells reads each row many times\n if (gridNear.length < width) {\n gridNear = new Float64Array(width)\n gridFar = new Float64Array(width)\n }\n let blended = -2\n for (let j = 0; j < depth; j++) {\n const row = gridRows[j]!\n const tz = gridBlendZ[j]!\n if (row < 0) {\n for (let i = 0; i < width; i++) out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const column = gridColumns[i]!\n if (column < 0) continue\n const index = row * stride + column\n const tx = gridBlendX[i]!\n gridNear[i] = blendHeights(heightOfVertex(index), heightOfVertex(index + 1), tx)\n gridFar[i] = blendHeights(heightOfVertex(index + stride), heightOfVertex(index + stride + 1), tx)\n }\n }\n for (let i = 0; i < width; i++) {\n if (gridColumns[i]! < 0) {\n out[j * width + i] = options.baseHeight?.(xs[i]!, zs[j]!) ?? 0\n continue\n }\n out[j * width + i] = blendHeights(gridNear[i]!, gridFar[i]!, tz)\n }\n }\n }\n\n function heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null {\n // the same test `heightGrid` makes of each point: a rectangle wholly inside reads no `baseHeight`\n if (!(minX >= x0 && maxX <= x1 && minZ >= z0 && maxZ <= z1)) return null\n const column0 = cellCoordinate(minX, x0, columns) | 0\n const row0 = cellCoordinate(minZ, z0, rows) | 0\n const width = (cellCoordinate(maxX, x0, columns) | 0) + 2 - column0\n const depth = (cellCoordinate(maxZ, z0, rows) | 0) + 2 - row0\n const heights = into && into.length >= width * depth ? into : new Float64Array(width * depth)\n for (let j = 0; j < depth; j++) {\n const from = (row0 + j) * stride + column0\n for (let i = 0; i < width; i++) heights[j * width + i] = heightOfVertex(from + i)\n }\n return { cellSize, originX: x0, originZ: z0, columns, rows, column0, row0, width, depth, heights }\n }\n\n function heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { low: number; high: number } | null {\n if (!contains(minX, minZ) || !contains(maxX, maxZ)) return null\n const cellOf = (v: number, origin: number, count: number): number => Math.floor(Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize)))\n const column0 = cellOf(minX, x0, columns)\n const column1 = cellOf(maxX, x0, columns) + 1\n const row0 = cellOf(minZ, z0, rows)\n const row1 = cellOf(maxZ, z0, rows) + 1\n let low = Infinity\n let high = -Infinity\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n const h = base[index]! - dug[index]! + loose[index]!\n if (h < low) low = h\n if (h > high) high = h\n }\n }\n return { low, high }\n }\n\n const vertexOf = (x: number, z: number): { column: number; row: number; index: number } => {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n return { column, row, index: row * stride + column }\n }\n\n function waterAt(x: number, z: number): { liquid: string; level: number; depth: number } | null {\n if (!hasWater || !contains(x, z)) return null\n const { index } = vertexOf(x, z)\n const water = profileList[profileIndex[index]!]!.water\n if (!water) return null\n const level = surface[index]!\n const depth = level - heightAt(x, z)\n return depth > WATER_MINIMUM ? { liquid: water.liquid, level, depth } : null\n }\n const exposedAt = (x: number, z: number): TerrainMaterial => {\n const { column, row } = vertexOf(x, z)\n return vertexMaterial(column, row)\n }\n const footAt = (x: number, z: number): number => {\n if (!contains(x, z)) return heightAt(x, z)\n return heightAt(x, z) - (exposedAt(x, z).footing?.sink ?? 0)\n }\n function walkFactorAt(x: number, z: number): number {\n if (!contains(x, z)) return 1\n const water = waterAt(x, z) ? profileList[profileIndex[vertexOf(x, z).index]!]!.water : null\n return Math.min(water?.drag ?? 1, exposedAt(x, z).footing?.drag ?? 1)\n }\n function ripple(x: number, z: number, radius: number): void {\n addDecal({ kind: 'ripple', x, z, radius, angle: 0, material: exposedAt(x, z).id })\n }\n function press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean {\n if (!contains(spec.x, spec.z)) return false\n if (waterAt(spec.x, spec.z)) {\n ripple(spec.x, spec.z, spec.radius * 2)\n return true\n }\n const material = exposedAt(spec.x, spec.z)\n if (!material.footing?.prints) return false\n addDecal({ kind: spec.kind ?? 'print', x: spec.x, z: spec.z, radius: spec.radius, angle: spec.angle ?? 0, material: material.id })\n return true\n }\n\n function vertexMaterial(column: number, row: number): TerrainMaterial {\n const index = row * stride + column\n return materials.get(stratumMaterialAtDepth(profileList[profileIndex[index]!]!, dug[index]!))!\n }\n\n /** `material(columnAt(x, z).material)` without building the column: the pieces ask it for every round contact. */\n function surfaceMaterialAt(x: number, z: number): TerrainMaterial {\n const column = clampIndex(Math.round((x - x0) / cellSize), columns)\n const row = clampIndex(Math.round((z - z0) / cellSize), rows)\n const index = row * stride + column\n const which = profileIndex[index]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n return materials.get(stratumMaterialAtDepth(profileList[which]!, depth))!\n }\n\n function rollingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rolling\n }\n\n function rollingDampingAt(x: number, z: number): number | undefined {\n return surfaceMaterialAt(x, z).rollingDamping\n }\n\n function columnAt(x: number, z: number): TerrainColumn {\n const { index } = vertexOf(x, z)\n const which = profileIndex[index]!\n const profile = profileList[which]!\n const depth = Math.min(maxDepthOf[which]!, dug[index]! + marks.depthAt(x, z))\n const layer = stratumAtDepth(profile, depth)\n return { profile: profile.id, material: layer.stratum.material, stratum: layer.index, depth, remaining: maxDepthOf[which]! - depth, scorch: scorch[index]!, loose: loose[index]! }\n }\n\n /** Removes from a vertex: what is heaped first, then the column, never past its limit. Returns what came off. */\n function removeFromVertex(index: number, amount: number): number {\n const fromLoose = Math.min(loose[index]!, amount)\n loose[index] = loose[index]! - fromLoose\n const fromColumn = Math.min(maxDepthOf[profileIndex[index]!]! - dug[index]!, amount - fromLoose)\n if (fromColumn > 0) dug[index] = dug[index]! + fromColumn\n return fromLoose + Math.max(0, fromColumn)\n }\n /** Adds to a vertex: a soft floor fills what was dug, then heaps; on a rigid one the rubble just heaps. */\n function addToVertex(index: number, amount: number, fillsColumn: boolean): void {\n const filled = fillsColumn ? Math.min(dug[index]!, amount) : 0\n dug[index] = dug[index]! - filled\n loose[index] = loose[index]! + amount - filled\n }\n const isSoftExposed = (index: number): boolean => materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!.reposeDegrees !== undefined\n\n /** The vertices under a rectangle centred at (x, z): the cells a blade of that size bites. */\n function verticesUnder(x: number, z: number, size: readonly [number, number]): number[] {\n // as many vertices across as the size has cells (each vertex stands for its cell's area), centred on (x, z)\n const nu = Math.max(1, Math.round(size[0] / cellSize)), nv = Math.max(1, Math.round(size[1] / cellSize))\n const column0 = clampIndex(Math.round((x - x0) / cellSize - (nu - 1) / 2), columns), column1 = clampIndex(column0 + nu - 1, columns)\n const row0 = clampIndex(Math.round((z - z0) / cellSize - (nv - 1) / 2), rows), row1 = clampIndex(row0 + nv - 1, rows)\n const out: number[] = []\n for (let row = row0; row <= row1; row++) for (let column = column0; column <= column1; column++) out.push(row * stride + column)\n return out\n }\n const touchIndex = (index: number): void => touchVertex(index % stride, Math.floor(index / stride))\n /** The material a shovel meets at a vertex: the loose earth heaped there, else the stratum at the depth dug so far. */\n const materialAtVertex = (index: number): TerrainMaterial =>\n loose[index]! > 1e-4 ? materials.get('soil')! : materials.get(stratumAtDepth(profileList[profileIndex[index]!]!, dug[index]!).stratum.material)!\n\n /** Lowers a vertex by up to `depth` through what a shovel digs (heaped earth first), stopping at what it does not. Returns how far it went. */\n function digVertex(index: number, depth: number): number {\n let left = depth\n while (left > 1e-6) {\n if (loose[index]! > 1e-6) {\n const take = Math.min(loose[index]!, left)\n loose[index] = loose[index]! - take\n left -= take\n continue\n }\n const profile = profileList[profileIndex[index]!]!\n const layer = stratumAtDepth(profile, dug[index]!)\n if (!materials.get(layer.stratum.material)?.dig || dug[index]! >= maxDepthOf[profileIndex[index]!]! - 1e-6) break\n const take = Math.min(left, layer.top + layer.stratum.thickness - dug[index]!)\n if (take <= 1e-6) break\n dug[index] = dug[index]! + take\n left -= take\n }\n return depth - left\n }\n\n /** Heaps `volume` of earth round (x, z), highest in the middle, and lets it settle to its slope. */\n function heapAt(x: number, z: number, volume: number): void {\n if (volume <= 0) return\n const radius = Math.max(cellSize * 2, Math.cbrt(volume) * 1.6)\n const indices = verticesUnder(x, z, [2 * radius, 2 * radius])\n const weight = (index: number): number => {\n const px = x0 + (index % stride) * cellSize, pz = z0 + Math.floor(index / stride) * cellSize\n const q = Math.hypot(px - x, pz - z) / radius\n return q < 1 ? 1 - q * q : 0\n }\n const total = indices.reduce((sum, i) => sum + weight(i), 0)\n if (total <= 0) return\n const cellArea = cellSize * cellSize\n for (const index of indices) {\n const w = weight(index)\n if (w <= 0) continue\n loose[index] = loose[index]! + (volume * w) / (total * cellArea)\n sliding.add(index)\n touchIndex(index)\n }\n emitDeform(x, z, radius)\n }\n\n function dig(spec: TerrainDig): TerrainDigResult {\n const size = spec.size ?? [0.3, 0.3], depth = spec.depth ?? 0.2\n const centre = vertexOf(spec.x, spec.z).index\n // under water a shovel brings nothing up\n if (profileList[profileIndex[centre]!]!.water) return { volume: 0, material: 'water', effort: 0, refused: 'water' }\n const met = materialAtVertex(centre)\n if (!met.dig) return { volume: 0, material: met.id, effort: 0, refused: met.id }\n if (met.dig.closes) return { volume: 0, material: met.id, effort: met.dig.effort, closes: true }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n let volume = 0\n for (const index of verticesUnder(spec.x, spec.z, size)) {\n const before = dug[index]!\n const went = digVertex(index, depth)\n if (went <= 0) continue\n tallyLowered(tally, index, dug[index]! - before)\n volume += went * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n marks.removeInside(spec.x, spec.z, Math.max(size[0], size[1]) / 2)\n emitDeform(spec.x, spec.z, Math.max(size[0], size[1]))\n // what the blade took from under a footing is ground lost under it: the structure feels it\n emitGroundLoss(tally, 'dig', 0)\n if (spec.dump) heapAt(spec.dump.x, spec.dump.z, volume)\n return { volume, material: met.id, effort: volume > 0 ? met.dig.effort : 0 }\n }\n\n function fill(spec: TerrainFill): number {\n const cellArea = cellSize * cellSize\n // the earth of the heap round `from`, nearest first, up to the volume asked\n let taken = 0\n const source = verticesUnder(spec.from.x, spec.from.z, [2 * spec.from.radius, 2 * spec.from.radius]).filter((i) => loose[i]! > 1e-6)\n for (const index of source) {\n if (taken >= spec.volume) break\n const take = Math.min(loose[index]!, (spec.volume - taken) / cellArea)\n loose[index] = loose[index]! - take\n taken += take * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (taken <= 0) return 0\n emitDeform(spec.from.x, spec.from.z, spec.from.radius)\n // laid in the hole: the deepest vertices of the bite first, so the hole closes level\n const target = verticesUnder(spec.x, spec.z, spec.size ?? [0.3, 0.3]).sort((a, b) => dug[b]! - dug[a]!)\n let left = taken\n for (const index of target) {\n if (left <= 1e-9) break\n const amount = Math.min(left / cellArea, Math.max(dug[index]!, (left / cellArea) / target.length))\n addToVertex(index, amount, true)\n left -= amount * cellArea\n sliding.add(index)\n touchIndex(index)\n }\n if (left > 1e-9) heapAt(spec.x, spec.z, left)\n emitDeform(spec.x, spec.z, Math.max(...(spec.size ?? [0.3, 0.3])))\n return taken\n }\n\n /** Digs a lobed bowl into the height field, heaps the rim share around it. */\n function stampBowl(x: number, z: number, radius: number, depth: number, rimVolume: number, lossSource: string | null = 'crater'): void {\n const reach = radius * RIM_REACH\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const phaseA = random() * 6.283\n const phaseB = random() * 6.283\n const shapeOf = (px: number, pz: number): number => {\n const angle = Math.atan2(pz - z, px - x)\n return Math.hypot(px - x, pz - z) / (radius * (1 + 0.12 * Math.sin(angle * 5 + phaseA) + 0.06 * Math.sin(angle * 11 + phaseB)))\n }\n let rimWeight = 0\n if (rimVolume > 0) {\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n if (q >= 1 && q < RIM_REACH) rimWeight += Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)\n }\n }\n }\n const cellArea = cellSize * cellSize\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const q = shapeOf(x0 + column * cellSize, z0 + row * cellSize)\n const index = row * stride + column\n if (q < 1) {\n const before = dug[index]!\n removeFromVertex(index, depth * (1 - q * q) * (0.92 + random() * 0.16))\n tallyLowered(tally, index, dug[index]! - before)\n sliding.add(index)\n touchVertex(column, row)\n } else if (q < RIM_REACH && rimWeight > 0) {\n loose[index] = loose[index]! + (rimVolume * Math.sin(((q - 1) / (RIM_REACH - 1)) * Math.PI)) / (rimWeight * cellArea)\n sliding.add(index)\n touchVertex(column, row)\n }\n }\n }\n marks.removeInside(x, z, radius)\n clearDecalsInside(x, z, radius)\n emitDeform(x, z, reach)\n if (lossSource) emitGroundLoss(tally, lossSource, 0)\n }\n\n function throwPieces(spec: { x: number; y: number; z: number; volume: number; material: TerrainMaterial; energy: number; direction?: readonly number[]; quota: number; bowlRadius: number; blow: TerrainBlow }): void {\n const radius = PIECE_RADIUS[spec.material.debris]\n const pieceVolume = (4 / 3) * Math.PI * radius ** 3\n const count = Math.min(spec.quota, Math.max(1, Math.round(spec.volume / pieceVolume)))\n const mass = Math.max(1e-3, spec.volume * 1500)\n const launch = Math.min(MAX_PIECE_SPEED[spec.blow], Math.sqrt((2 * spec.energy * THROW_SHARE) / mass))\n for (let i = 0; i < count; i++) {\n const angle = random() * 6.283\n const out = spec.bowlRadius * Math.sqrt(random()) * 0.8\n const speed = launch * (0.5 + random() * 0.7)\n const spread = 0.35 + random() * 0.65\n const backX = spec.direction ? -(spec.direction[0] ?? 0) * 0.4 : 0\n const backZ = spec.direction ? -(spec.direction[2] ?? 0) * 0.4 : 0\n debrisStore.throwPiece({\n material: spec.material.id,\n kind: spec.material.debris,\n radius: radius * (0.6 + random() * 0.9),\n position: [spec.x + Math.cos(angle) * out, spec.y + 0.03, spec.z + Math.sin(angle) * out],\n velocity: [(Math.cos(angle) * spread + backX) * speed, (0.6 + random() * 0.7) * speed, (Math.sin(angle) * spread + backZ) * speed],\n spin: [(random() - 0.5) * 14, (random() - 0.5) * 14, (random() - 0.5) * 14],\n })\n }\n }\n\n function strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult {\n const { x, z } = spec\n const start = columnAt(x, z)\n const profile = profileMap.get(start.profile)!\n const waterHere = waterAt(x, z)\n const waterResult = waterHere ? { water: { liquid: waterHere.liquid, level: waterHere.level } } : {}\n if (waterHere) ripple(x, z, Math.min(1.5, 0.15 + Math.cbrt(spec.energy) / 40))\n const removed: { material: string; volume: number }[] = []\n const point: [number, number, number] = [x, heightAt(x, z), z]\n const startLayer = stratumAtDepth(profile, start.depth)\n if (start.loose <= 0 && materials.get(startLayer.stratum.material)!.units) return strikeUnits(blow, spec, startLayer, profile, point)\n const blowEnergy = spec.energy * (waterHere ? (profile.water?.blowShare[blow] ?? 1) : 1)\n let energy = blowEnergy\n let depth = start.depth\n let radius = 0\n let carved = 0\n let breached = false\n const firstMaterial = materials.get(start.material)!\n if (start.loose <= 0) {\n for (;;) {\n const layer = stratumAtDepth(profile, depth)\n const bottom = layer.top + layer.stratum.thickness\n const room = bottom - depth\n if (room <= 1e-6) break\n const material = materials.get(layer.stratum.material)!\n const response = material.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) break\n const bars = layer.stratum.reinforcement\n // a contact charge with enough for the whole thickness of a rigid layer breaks it right through: the shock spalls the far face and the layer goes in one piece, bars or not\n const breach = blow === 'explosive' ? material.breach : undefined\n const breachJoules = breach ? breach.joulesPerCubedThickness * layer.stratum.thickness ** 3 : Infinity\n if (breach && depth <= layer.top + 1e-6 && energy >= breachJoules) {\n const takenRadius = layer.stratum.thickness * breach.radiusOverThickness * Math.cbrt(energy / breachJoules)\n const takenVolume = (Math.PI * takenRadius * takenRadius * room) / 2\n energy -= breachJoules\n depth += room\n carved += room\n breached = true\n radius = Math.max(radius, takenRadius)\n removed.push({ material: material.id, volume: takenVolume })\n continue\n }\n const pastCover = bars !== undefined && depth - layer.top >= bars.cover - 1e-6\n const specificEnergy = response.specificEnergy * (pastCover ? bars.resistance : 1)\n const limit = bars && !pastCover ? Math.min(room, layer.top + bars.cover - depth) : room\n const aspect = response.aspect * caliberAspect(spec.caliber)\n const volume = energy / specificEnergy\n const wanted = Math.cbrt((2 * volume) / (Math.PI * aspect))\n const wantedDepth = wanted * aspect\n const takenDepth = Math.min(wantedDepth, limit)\n const takenRadius = takenDepth < wantedDepth ? takenDepth / aspect : wanted\n const takenVolume = (Math.PI * takenRadius * takenRadius * takenDepth) / 2\n energy -= takenVolume * specificEnergy\n depth += takenDepth\n carved += takenDepth\n radius = Math.max(radius, takenRadius, response.minRadius ?? 0, spec.contactRadius ?? 0, caliberRadius(spec.caliber))\n const last = removed[removed.length - 1]\n if (last?.material === material.id) (last as { volume: number }).volume += takenVolume\n else removed.push({ material: material.id, volume: takenVolume })\n if (energy <= 1e-6 || takenDepth >= wantedDepth - 1e-9) break\n }\n } else {\n // a loose heap has no strength: it takes the blow as soft ground before the column does\n const response = firstMaterial.hits[blow]\n if (response && energy >= (response.thresholdJoules ?? 0)) {\n const volume = energy / response.specificEnergy\n radius = Math.cbrt((2 * volume) / (Math.PI * response.aspect))\n carved = radius * response.aspect\n removed.push({ material: firstMaterial.id, volume })\n }\n }\n let collapsed = loadBars(blow, spec.energy, x, z, profile)\n const crack = crackAround(blow, spec.energy, x, z, start.loose > 0 ? undefined : firstMaterial)\n const extra = { ...(crack ? { crack } : {}), ...(breached ? { breached } : {}), ...waterResult }\n // a weight that lands flat (its contact as wide as the dent) presses the ground down: it packs the soil under it, it does not take it away\n const pressed = spec.contactRadius !== undefined && spec.contactRadius >= radius\n if (radius <= 0) return { point, radius: 0, depth: 0, totalDepth: columnAt(x, z).depth, removed: [], exposed: start.material, atLimit: start.remaining <= 1e-6, rebarExposed: rebarShowing(profile, start.depth), collapsed, fine: true, ...extra }\n\n // a rigid floor cannot go down any more where it is already deep: the next blow breaks the edge of the hole, so a hole in a slab opens as it deepens\n if (firstMaterial.reposeDegrees === undefined && start.loose <= 0) radius *= 1 + RIGID_WIDENING * (start.depth / maxDepthOfProfile(profile))\n\n const volumeTotal = removed.reduce((sum, entry) => sum + entry.volume, 0)\n const fine = radius < cellSize * FINE_CELLS\n if (fine) depositMark({ x, z, radius, depth: carved, blow, profile, cap: maxDepthOfProfile(profile) })\n else {\n const rimShare = materials.get(removed[0]!.material)!.rimShare ?? 0\n stampBowl(x, z, radius, carved, volumeTotal * rimShare, pressed ? null : 'crater')\n }\n if (firstMaterial.cracks) addDecal({ kind: 'crack', x, z, radius: Math.max(CRACK_MIN_RADIUS, radius * firstMaterial.cracks), angle: random() * 6.283, material: firstMaterial.id })\n // under water what comes off stays a cloud at the bottom, unless a blast opens the water\n let quota = waterHere && blow !== 'explosive' ? 0 : budget.maxDebrisPerBlow\n for (const entry of removed) {\n const material = materials.get(entry.material)!\n const thrown = entry.volume * (1 - (fine ? 0 : (material.rimShare ?? 0)))\n if (thrown <= 0 || quota <= 0) continue\n const share = Math.max(1, Math.round((quota * entry.volume) / volumeTotal))\n throwPieces({ x, y: point[1], z, volume: thrown, material, energy: spec.energy * (entry.volume / volumeTotal), direction: spec.direction, quota: share, bowlRadius: radius, blow })\n quota -= share\n }\n // a breach bares the bars under the same blow that broke the concrete, so they take that blow's load at once and, over a void, may let the floor go\n if (breached) collapsed = loadBars(blow, spec.energy, x, z, profile) || collapsed\n const after = columnAt(x, z)\n return { point, radius, depth: carved, totalDepth: after.depth, removed, exposed: after.material, atLimit: after.remaining <= 1e-4, rebarExposed: rebarShowing(profile, after.depth), collapsed, fine, ...extra }\n }\n\n /** A rigid surface cracks around a hard enough blow, the lines running out with the cube root of the energy; a soft one (soil, sand, turf) only gives way. */\n function crackAround(blow: TerrainBlow, energy: number, x: number, z: number, material: TerrainMaterial | undefined): ReturnType<typeof cracks.add> | undefined {\n const response = material?.crack\n if (!material || !response || energy < response.thresholdJoules) return undefined\n // a cut does not crack a slab; a bullet, a hammer and a blast do\n if (blow === 'slash') return undefined\n const scale = Math.cbrt(energy / CRACK_REFERENCE_JOULES)\n return cracks.add({ x, z, reach: response.reach * scale, width: response.width * scale, material: material.id, seed: Math.floor(random() * 2 ** 31) }, budget.maxCracks)\n }\n\n /**\n * A floor of separate pieces: a blow does not dig them, it shakes them. Each takes the energy that reaches it, added blow by blow, and past its limit it comes off the bed whole and is thrown.\n * Under the limit the blow only chips it.\n */\n function strikeUnits(blow: TerrainBlow, spec: TerrainStrike, layer: { stratum: TerrainStratum; top: number }, profile: TerrainProfile, point: [number, number, number]): TerrainBlowResult {\n const { x, z, energy } = spec\n const material = materials.get(layer.stratum.material)!\n const units = material.units!\n const response = material.hits[blow]\n const bottom = layer.top + layer.stratum.thickness\n const miss: TerrainBlowResult = { point, radius: 0, depth: 0, totalDepth: layer.top, removed: [], exposed: material.id, atLimit: false, rebarExposed: false, collapsed: false, fine: true }\n if (!response || energy < (response.thresholdJoules ?? 0)) return miss\n const reach = Math.max(spec.contactRadius ?? 0, response.minRadius ?? 0, caliberRadius(spec.caliber), Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect * caliberAspect(spec.caliber))))\n const rowFirst = Math.floor((z - reach) / units.width)\n const rowLast = Math.floor((z + reach) / units.width)\n let loosened = 0\n for (let row = rowFirst; row <= rowLast; row++) {\n const shift = Math.abs(row % 2) * cellSize\n const unitFirst = Math.floor((x - reach - shift) / units.length)\n const unitLast = Math.floor((x + reach - shift) / units.length)\n for (let unit = unitFirst; unit <= unitLast; unit++) {\n const minX = unit * units.length + shift\n const minZ = row * units.width\n const near = Math.hypot(Math.max(minX - x, 0, x - minX - units.length), Math.max(minZ - z, 0, z - minZ - units.width))\n if (near > reach) continue\n const key = `${unit}:${row}`\n const taken = (unitDamage.get(key) ?? 0) + energy * (1 - (near / (reach + 1e-6)) ** 2)\n unitDamage.set(key, taken)\n if (taken >= units.looseJoules && liftUnit(minX, minZ, units, bottom, material, profile)) {\n loosened++\n const speed = Math.min(MAX_PIECE_SPEED[blow], Math.sqrt((2 * energy * THROW_SHARE) / Math.max(1, loosened * 15)))\n const angle = random() * 6.283\n debrisStore.throwPiece({ material: material.id, kind: 'blocks', radius: units.length / 2, position: [minX + units.length / 2, point[1] + 0.05, minZ + units.width / 2], velocity: [Math.cos(angle) * speed * 0.6, speed * (0.5 + random() * 0.5), Math.sin(angle) * speed * 0.6], spin: [(random() - 0.5) * 8, (random() - 0.5) * 8, (random() - 0.5) * 8] })\n }\n }\n }\n if (loosened === 0) {\n // not enough to lift a piece: a chip off its face and a hairline\n addDecal({ kind: 'crack', x, z, radius: Math.max(0.05, reach * 2), angle: random() * 6.283, material: material.id })\n throwPieces({ x, y: point[1], z, volume: 1e-5, material: { ...material, debris: 'chips' }, energy, ...(spec.direction ? { direction: spec.direction } : {}), quota: 3, bowlRadius: 0.02, blow })\n return { ...miss, radius: Math.max(0.02, Math.min(reach, 0.06)) }\n }\n emitDeform(x, z, reach + units.length)\n clearDecalsInside(x, z, reach)\n const volume = loosened * units.length * units.width * layer.stratum.thickness\n const after = columnAt(x, z)\n return { point, radius: reach, depth: layer.stratum.thickness, totalDepth: after.depth, removed: [{ material: material.id, volume }], exposed: after.material, atLimit: false, rebarExposed: false, collapsed: false, fine: false }\n }\n\n /** Takes one piece off its bed. False when it had already gone. */\n function liftUnit(minX: number, minZ: number, units: { length: number; width: number }, bottom: number, material: TerrainMaterial, profile: TerrainProfile): boolean {\n const column0 = clampIndex(Math.round((minX - x0) / cellSize), columns)\n const column1 = clampIndex(Math.round((minX + units.length - x0) / cellSize), columns)\n const row0 = clampIndex(Math.round((minZ - z0) / cellSize), rows)\n const row1 = clampIndex(Math.round((minZ + units.width - z0) / cellSize), rows)\n let lifted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (profileList[profileIndex[index]!]!.id !== profile.id || dug[index]! >= bottom) continue\n if (materials.get(stratumAtDepth(profile, dug[index]!).stratum.material) !== material) continue\n dug[index] = bottom\n lifted = true\n touchVertex(column, row)\n }\n }\n return lifted\n }\n\n /**\n * A blow loads the bars that are bare around it: they bend, and past their limit they give way. The bowl a blow would open tells how far it reaches. Where the slab has nothing under it, the floor goes with them.\n */\n function loadBars(blow: TerrainBlow, energy: number, x: number, z: number, profile: TerrainProfile): boolean {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return false\n const response = materials.get(bars.material)!.hits[blow]\n if (!response || energy < (response.thresholdJoules ?? 0)) return false\n const yieldJoules = bars.reinforcement.yieldJoules ?? DEFAULT_BAR_YIELD_JOULES\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n const reach = Math.max(cellSize * FINE_CELLS, Math.cbrt((2 * energy) / response.specificEnergy / (Math.PI * response.aspect)) * (1 + RIGID_WIDENING))\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n const limit = maxDepthOfProfile(profile)\n let collapsed = false\n const tally: LossTally = new Map()\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (dug[index]! < cover) continue\n const q = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z) / reach\n if (q >= 1) continue\n barBend[index] = barBend[index]! + (energy / yieldJoules) * (1 - q * q)\n touchVertex(column, row)\n if (barBend[index]! >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n collapsed = true\n }\n }\n }\n if (collapsed) giveWay({ x, z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return collapsed\n }\n\n /** What gave way takes down what was already bending around it, and what stood there must look again. */\n function giveWay(spec: { x: number; z: number; reach: number; profile: TerrainProfile; tally: LossTally }): void {\n const { x, z, reach, profile, tally } = spec\n emitDeform(x, z, reach)\n if (profile.drop === undefined) return\n const limit = maxDepthOfProfile(profile)\n const column0 = clampIndex(Math.floor((x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + reach - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const index = row * stride + column\n if (barBend[index]! >= COLLAPSE_SPREAD_BEND && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n touchVertex(column, row)\n }\n }\n }\n }\n\n /** Depth under the surface of the bars of a profile, and the stratum that holds them. */\n function barsOf(profile: TerrainProfile): { stratum: TerrainStratum; cover: number } | null {\n const bars = profile.strata.find((stratum) => stratum.reinforcement)\n if (!bars?.reinforcement) return null\n let cover = bars.reinforcement.cover\n for (const stratum of profile.strata) {\n if (stratum === bars) break\n cover += stratum.thickness\n }\n return { stratum: bars, cover }\n }\n\n /**\n * Weights on bare bars. Each bar over the hole works as a beam that yields at its plastic moment fy·d³/6; the bars of a mesh crossing a hole of any size hold 8·Mp/spacing\n * on a spot, so the bend is the weight over that. Weights over the same bars add up (a stack, things side by side). The share of a footprint on intact concrete is carried\n * by the concrete. Bars do not spring back: the bend only grows.\n */\n function bearAll(loads: readonly TerrainLoad[]): boolean {\n const bends = new Map<number, number>()\n const touched: { load: TerrainLoad; reach: number; profile: TerrainProfile }[] = []\n for (const load of loads) {\n const spread = spreadLoad(load, bends)\n if (spread) touched.push({ load, ...spread })\n }\n let opened = false\n const tally: LossTally = new Map()\n for (const [index, bend] of bends) {\n if (barBend[index]! >= bend) continue\n barBend[index] = bend\n const column = index % stride\n const row = (index - column) / stride\n touchVertex(column, row)\n const profile = profileList[profileIndex[index]!]!\n const limit = maxDepthOfProfile(profile)\n if (bend >= 1 && profile.drop !== undefined && dug[index]! >= limit * COLLAPSE_DEPTH_SHARE && dug[index]! < limit + profile.drop) {\n dropVertex(index, limit + profile.drop, tally)\n opened = true\n }\n }\n if (opened) for (const { load, reach, profile } of touched) giveWay({ x: load.x, z: load.z, reach, profile, tally })\n emitGroundLoss(tally, 'slab', 0)\n return opened\n }\n\n /** Adds the bend one weight gives the bare bars under it to `bends`; null where it stands on no bare bars. */\n function spreadLoad(load: TerrainLoad, bends: Map<number, number>): { reach: number; profile: TerrainProfile } | null {\n if (!contains(load.x, load.z) || load.newtons <= 0) return null\n const profile = profileList[profileIndex[vertexOf(load.x, load.z).index]!]!\n const bars = barsOf(profile)\n if (!bars) return null\n const reinforcement = bars.stratum.reinforcement!\n const moment = ((reinforcement.yieldPa ?? DEFAULT_BAR_YIELD_PA) * (reinforcement.diameter ?? DEFAULT_BAR_DIAMETER) ** 3) / 6\n const holds = (8 * moment) / reinforcement.spacing\n // the footprint of a box reaches its corners: a disc of its half side would leave them standing on the slab\n const footprint = load.radius * Math.SQRT2 + cellSize\n // and the bars of a hole carry together what stands on it: weights side by side add up as a stack does\n const reach = Math.max(footprint, BARS_SHARE_REACH)\n const column0 = clampIndex(Math.floor((load.x - reach - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((load.x + reach - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((load.z - reach - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((load.z + reach - z0) / cellSize), rows)\n const bare: number[] = []\n let under = 0\n let onBars = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - load.x, z0 + row * cellSize - load.z)\n if (distance >= reach) continue\n const index = row * stride + column\n const isBare = dug[index]! >= bars.cover\n if (isBare) bare.push(index)\n if (distance >= footprint) continue\n under++\n if (isBare) onBars++\n }\n }\n if (onBars === 0) return null\n const bend = (load.newtons * (onBars / under)) / holds\n for (const index of bare) bends.set(index, (bends.get(index) ?? 0) + bend)\n return { reach, profile }\n }\n\n const maxDepthOfProfile = (profile: TerrainProfile): number => maxDepthOf[indexOfProfile.get(profile.id)!]!\n function rebarShowing(profile: TerrainProfile, depth: number): boolean {\n const layer = stratumAtDepth(profile, depth)\n return layer.stratum.reinforcement !== undefined && depth - layer.top >= layer.stratum.reinforcement.cover - 1e-6\n }\n\n function depositMark(spec: { x: number; z: number; radius: number; depth: number; blow: TerrainBlow; profile: TerrainProfile; cap: number }): void {\n const { x, z, radius, depth, blow, profile, cap } = spec\n const dugHere = dug[vertexOf(x, z).index]!\n const existing = marks.near(x, z, radius)\n let mark: TerrainMark\n if (existing) {\n existing.radius = Math.hypot(existing.radius, radius)\n existing.depth = Math.min(cap - dugHere, existing.depth + depth)\n existing.count++\n existing.blow = blow\n mark = existing\n } else {\n mark = marks.add({ x, z, radius, depth: Math.min(cap - dugHere, depth), blow, material: '' })\n }\n mark.material = stratumAtDepth(profile, dugHere + mark.depth - 1e-6).stratum.material\n if (mark.radius >= cellSize * FINE_CELLS || mark.depth >= cellSize * FINE_DEPTH_CELLS) {\n const bowlRadius = Math.max(mark.radius, cellSize * FINE_CELLS)\n const bowlDepth = mark.depth\n marks.remove(mark)\n stampBowl(mark.x, mark.z, bowlRadius, bowlDepth, 0)\n }\n }\n\n function burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void {\n if (spec.temperature < FLAME_MINIMUM) return\n const column0 = clampIndex(Math.floor((spec.x - spec.radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((spec.x + spec.radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((spec.z - spec.radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((spec.z + spec.radius - z0) / cellSize), rows)\n let melted = false\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(x0 + column * cellSize - spec.x, z0 + row * cellSize - spec.z) > spec.radius) continue\n // water does not catch: only what floats on it could burn\n if (hasWater && base[row * stride + column]! < surface[row * stride + column]!) continue\n melted = burnVertex(column, row, spec.seconds) || melted\n }\n }\n if (melted) emitDeform(spec.x, spec.z, spec.radius)\n }\n\n /** The soot of a blast's fireball within `radius` of (x, z): darkest at the centre, by what each material takes (`fire.maxScorch`); it lights nothing. */\n function soot(x: number, z: number, radius: number): void {\n if (radius <= 0) return\n const column0 = clampIndex(Math.floor((x - radius - x0) / cellSize), columns)\n const column1 = clampIndex(Math.ceil((x + radius - x0) / cellSize), columns)\n const row0 = clampIndex(Math.floor((z - radius - z0) / cellSize), rows)\n const row1 = clampIndex(Math.ceil((z + radius - z0) / cellSize), rows)\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n const distance = Math.hypot(x0 + column * cellSize - x, z0 + row * cellSize - z)\n const response = distance < radius ? vertexMaterial(column, row).fire : undefined\n if (!response) continue\n const index = row * stride + column\n const before = scorch[index]!\n scorch[index] = Math.max(before, response.maxScorch * BLAST_SOOT * Math.sqrt(1 - distance / radius))\n if (scorch[index] !== before) touchVertex(column, row)\n }\n }\n }\n\n /** True when the flame took ground away, so that what stood there must look again. */\n function burnVertex(column: number, row: number, seconds: number): boolean {\n const index = row * stride + column\n const material = vertexMaterial(column, row)\n const response = material.fire\n if (!response) return false\n const before = scorch[index]!\n scorch[index] = Math.max(before, Math.min(response.maxScorch, before + response.scorchPerSecond * seconds))\n if (response.burnsAway) removeFromVertex(index, response.burnsAway * seconds)\n if (scorch[index] !== before || response.burnsAway) touchVertex(column, row)\n if (response.flammable) ignite(x0 + column * cellSize, z0 + row * cellSize)\n return (response.burnsAway ?? 0) > 0\n }\n\n const fireKey = (x: number, z: number): number => Math.floor((z - z0) / FIRE_CELL) * 65536 + Math.floor((x - x0) / FIRE_CELL)\n function ignite(x: number, z: number): void {\n const key = fireKey(x, z)\n if (burning.has(key) || burning.size >= budget.maxBurningCells) return\n const index = vertexOf(x, z).index\n if (scorch[index]! >= 1) return\n burning.set(key, FIRE_SECONDS)\n }\n\n function updateFire(dt: number): void {\n for (const [key, remaining] of [...burning]) {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n const x = x0 + (cellColumn + 0.5) * FIRE_CELL\n const z = z0 + (cellRow + 0.5) * FIRE_CELL\n burn({ x, z, radius: FIRE_CELL * 0.75, temperature: 600, seconds: dt })\n if (random() < FIRE_SPREAD_PER_SECOND * dt) {\n const angle = Math.floor(random() * 4) * (Math.PI / 2)\n const nextX = x + Math.cos(angle) * FIRE_CELL\n const nextZ = z + Math.sin(angle) * FIRE_CELL\n if (contains(nextX, nextZ)) {\n const { column, row, index } = vertexOf(nextX, nextZ)\n if (vertexMaterial(column, row).fire?.flammable && scorch[index]! < 1) ignite(nextX, nextZ)\n }\n }\n if (remaining - dt <= 0) burning.delete(key)\n else burning.set(key, remaining - dt)\n }\n }\n\n function updateSlides(): void {\n if (sliding.size === 0) return\n let budgetLeft = budget.maxSlideCellsPerFrame\n let minX = Infinity\n let minZ = Infinity\n let maxX = -Infinity\n let maxZ = -Infinity\n for (const index of sliding) {\n if (budgetLeft-- <= 0) break\n sliding.delete(index)\n const column = index % stride\n const row = (index - column) / stride\n if (!isSoftExposed(index)) continue\n const material = vertexMaterial(column, row)\n const slope = Math.tan(((material.reposeDegrees ?? 90) * Math.PI) / 180) * cellSize\n const height = vertexHeight(column, row)\n const neighbours: [number, number][] = [[column - 1, row], [column + 1, row], [column, row - 1], [column, row + 1]]\n for (const [nextColumn, nextRow] of neighbours) {\n if (nextColumn < 0 || nextRow < 0 || nextColumn > columns || nextRow > rows) continue\n const excess = height - vertexHeight(nextColumn, nextRow) - slope\n if (excess <= SLIDE_EPSILON) continue\n const before = dug[index]!\n const moved = removeFromVertex(index, excess * SLIDE_SHARE)\n if (moved <= 0) continue\n tallyLowered(slideTally, index, dug[index]! - before)\n const next = nextRow * stride + nextColumn\n const nextBefore = dug[next]!\n addToVertex(next, moved, isSoftExposed(next))\n tallyLowered(slideTally, next, dug[next]! - nextBefore)\n sliding.add(index)\n sliding.add(next)\n touchVertex(column, row)\n touchVertex(nextColumn, nextRow)\n const px = x0 + column * cellSize\n const pz = z0 + row * cellSize\n minX = Math.min(minX, px)\n maxX = Math.max(maxX, px)\n minZ = Math.min(minZ, pz)\n maxZ = Math.max(maxZ, pz)\n }\n }\n if (minX <= maxX) emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n if (sliding.size === 0 && slideTally.size > 0) {\n emitGroundLoss(slideTally, 'slide', SLIDE_LOSS_MIN_LOWERING)\n slideTally.clear()\n }\n }\n\n /** The box (in x, z) round the vertices that settled rubble raised in this update, told once as one deform. */\n const settledArea = { minX: Infinity, minZ: Infinity, maxX: -Infinity, maxZ: -Infinity }\n function emitSettledArea(): void {\n if (settledArea.minX > settledArea.maxX) return\n const { minX, minZ, maxX, maxZ } = settledArea\n settledArea.minX = settledArea.minZ = Infinity\n settledArea.maxX = settledArea.maxZ = -Infinity\n emitDeform((minX + maxX) / 2, (minZ + maxZ) / 2, Math.hypot(maxX - minX, maxZ - minZ) / 2 + cellSize * 2)\n }\n\n /** A piece of soft ground joins the height where it stops, so that what is thrown out piles up and can be walked on. */\n function settle(piece: TerrainDebris): boolean {\n const material = materials.get(piece.material)\n if (!material || material.reposeDegrees === undefined || material.scatters) return false\n if (material.splats && contains(piece.position[0], piece.position[2]) && !waterAt(piece.position[0], piece.position[2])) addDecal({ kind: 'splat', x: piece.position[0], z: piece.position[2], radius: piece.radius * 2.6, angle: piece.id * 2.399, material: material.id })\n if (!contains(piece.position[0], piece.position[2])) return true\n const { index, column, row } = vertexOf(piece.position[0], piece.position[2])\n addToVertex(index, ((4 / 3) * Math.PI * piece.radius ** 3) / (cellSize * cellSize), false)\n sliding.add(index)\n touchVertex(column, row)\n const px = x0 + column * cellSize, pz = z0 + row * cellSize\n settledArea.minX = Math.min(settledArea.minX, px)\n settledArea.maxX = Math.max(settledArea.maxX, px)\n settledArea.minZ = Math.min(settledArea.minZ, pz)\n settledArea.maxZ = Math.max(settledArea.maxZ, pz)\n return true\n }\n\n function applyHit(hit: Hit): TerrainBlowResult | null {\n const [x, y, z] = hit.point\n switch (hit.type) {\n case 'ballistic':\n case 'blunt':\n case 'slash': {\n if (!hit.energy) return null\n const contactRadius = hit.type === 'blunt' ? hit.radius : undefined\n const caliber = hit.type === 'ballistic' ? hit.caliber : undefined\n return strike(hit.type, { x, z, energy: hit.energy, ...(hit.direction ? { direction: hit.direction } : {}), ...(contactRadius !== undefined ? { contactRadius } : {}), ...(caliber !== undefined ? { caliber } : {}) })\n }\n case 'explosive': {\n if (!hit.energy) return null\n const above = Math.max(0, y - heightAt(x, z))\n const reach = (hit.radius ?? 1) * BLAST_HEIGHT_REACH\n if (above >= reach) return null\n const share = (1 - above / reach) ** 2\n // the ground's specific energies are of real joules (a kilogram of TNT is 4.184 MJ): a charge the blast was told says them; its `energy` is the arsenal's damage scale\n soot(x, z, BLAST_SOOT_REACH * Math.cbrt((hit.energy * share) / 1e6))\n return strike('explosive', { x, z, energy: (hit.hasCharge && hit.tnt !== undefined && hit.tnt > 0 ? hit.tnt * TNT_JOULES : hit.energy) * share })\n }\n case 'fire':\n case 'heat':\n if (y - heightAt(x, z) > (hit.radius ?? 0.2) + FLAME_REACH) return null\n burn({ x, z, radius: hit.radius ?? 0.2, temperature: hit.temperature ?? 0, seconds: hit.duration ?? 0.016 })\n return null\n default:\n return null\n }\n }\n\n function raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null {\n const [ox = 0, oy = 0, oz = 0] = origin\n const [dx = 0, dy = 0, dz = 0] = direction\n const step = cellSize * 0.75\n let previous = 0\n for (let t = 0; t <= maxDistance; t += step) {\n const x = ox + dx * t\n const z = oz + dz * t\n if (contains(x, z) && oy + dy * t <= heightAt(x, z)) {\n let low = previous\n let high = t\n for (let i = 0; i < 6; i++) {\n const middle = (low + high) / 2\n if (oy + dy * middle <= heightAt(ox + dx * middle, oz + dz * middle)) high = middle\n else low = middle\n }\n const px = ox + dx * high\n const pz = oz + dz * high\n const gx = heightAt(px + cellSize, pz) - heightAt(px - cellSize, pz)\n const gz = heightAt(px, pz + cellSize) - heightAt(px, pz - cellSize)\n const length = Math.hypot(gx, 2 * cellSize, gz)\n return { point: [px, oy + dy * high, pz], distance: high, normal: [-gx / length, (2 * cellSize) / length, -gz / length] }\n }\n previous = t\n }\n return null\n }\n\n function chunk(index: number): TerrainChunk {\n const chunkZ = Math.floor(index / chunksX)\n const chunkX = index - chunkZ * chunksX\n return { index, column: chunkX * chunkCells, row: chunkZ * chunkCells, cells: chunkCells, pristine: !touched[index] && !mixed[index] && !options.baseHeight }\n }\n\n function reset(): void {\n dug.fill(0)\n loose.fill(0)\n scorch.fill(0)\n barBend.fill(0)\n touched.fill(0)\n marks.clear()\n cracks.clear()\n decalList.length = 0\n decalsVersion++\n unitDamage.clear()\n debrisStore.clear()\n sliding.clear()\n slideTally.clear()\n burning.clear()\n // the craters and clods draw from here: a reset ground digs the same as a new one\n random = createRandom(seed)\n applyLayout(currentLayout)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n }\n\n applyLayout(currentLayout)\n\n return {\n bounds: options.bounds,\n cellSize,\n columns,\n rows,\n stride,\n chunkCells,\n chunksX,\n chunksZ,\n budget,\n dug,\n loose,\n scorch,\n barBend,\n profileIndex,\n profileList,\n material: (id) => {\n const material = materials.get(id)\n if (!material) throw new Error(`game-terrain: unknown material \"${id}\"`)\n return material\n },\n layout: () => currentLayout,\n setLayout(layout) {\n currentLayout = layout\n reset()\n },\n heightAt,\n heightGrid,\n heightPatch,\n heightRange,\n footAt,\n walkFactorAt,\n waterAt,\n press,\n ripple,\n decals: () => decalList,\n get decalsVersion() {\n return decalsVersion\n },\n vertexHeight,\n vertexMaterial,\n columnAt,\n rollingAt,\n rollingDampingAt,\n contains,\n raycast,\n strike,\n burn,\n open(excavation) {\n excavate(excavation)\n const [ex0, ez0, ex1, ez1] = excavation.rect\n emitDeform((ex0 + ex1) / 2, (ez0 + ez1) / 2, Math.hypot(ex1 - ex0, ez1 - ez0) / 2 + cellSize * 2)\n },\n dig,\n fill,\n applyHit,\n bear: bearAll,\n voidUnder: (x, z, radius) => voidUnder(grid, { x, z, radius }),\n onDeform(listener) {\n deformListeners.add(listener)\n return () => deformListeners.delete(listener)\n },\n update(dt) {\n debrisStore.update(dt, { heightAt, gravity, settle })\n emitSettledArea()\n updateSlides()\n updateFire(dt)\n for (let i = decalList.length - 1; i >= 0; i--) {\n const decal = decalList[i]!\n decal.age += dt\n if (decal.kind === 'ripple' && decal.age > RIPPLE_SECONDS) {\n decalList.splice(i, 1)\n decalsVersion++\n }\n }\n },\n get dirtyChunkCount() {\n return dirty.size\n },\n drainDirtyChunks(max = budget.maxDirtyChunksPerFrame) {\n const taken: TerrainChunk[] = []\n for (const index of dirty) {\n if (taken.length >= max) break\n dirty.delete(index)\n taken.push(chunk(index))\n }\n return taken\n },\n chunk,\n marks: () => marks.list,\n cracks: () => cracks.list,\n get cracksVersion() {\n return cracks.version\n },\n debris: () => debrisStore.list,\n burningPoints: () => [...burning.keys()].map((key) => {\n const cellRow = Math.floor(key / 65536)\n const cellColumn = key - cellRow * 65536\n return [x0 + (cellColumn + 0.5) * FIRE_CELL, z0 + (cellRow + 0.5) * FIRE_CELL] as const\n }),\n get marksVersion() {\n return marks.version\n },\n stats: () => ({ marks: marks.list.length, debris: debrisStore.list.length, debrisMoving: debrisStore.list.filter((piece) => !piece.atRest).length, dirtyChunks: dirty.size, burning: burning.size }),\n reset,\n serialize(): TerrainSnapshot {\n return { layout: currentLayout, dug: sparse(dug), loose: sparse(loose), scorch: sparse(scorch), barBend: sparse(barBend), marks: marks.list.map((mark) => ({ ...mark })), cracks: cracks.list.map((crack) => ({ ...crack })), decals: decalList.filter((decal) => decal.kind !== 'ripple').map((decal) => ({ ...decal })) }\n },\n load(snapshot) {\n currentLayout = snapshot.layout\n reset()\n fillSparse(dug, snapshot.dug)\n fillSparse(loose, snapshot.loose)\n fillSparse(scorch, snapshot.scorch)\n fillSparse(barBend, snapshot.barBend ?? [])\n marks.load(snapshot.marks)\n cracks.load(snapshot.cracks ?? [])\n decalList.push(...(snapshot.decals ?? []).map((decal) => ({ ...decal })))\n decalSerial = decalList.reduce((highest, decal) => Math.max(highest, decal.id), decalSerial)\n for (let chunkIndex = 0; chunkIndex < touched.length; chunkIndex++) markChunk(chunkIndex)\n emitDeform((x0 + x1) / 2, (z0 + z1) / 2, Math.hypot(x1 - x0, z1 - z0) / 2)\n },\n }\n}\n","import type { TerrainBlow, TerrainMaterial, TerrainProfile } from './types'\n\n// Specific energies are what the marks of real blows imply: a 500 J pistol round leaves about 120 cm³ in soil and 3 cm³ in concrete, an 800 kJ grenade a 1.3 m crater in soil and a 25 cm spall on a slab.\n// Cracks run about a metre from a grenade on a slab and half that on asphalt; a contact charge breaks a reinforced slab right through at about 1 kg of TNT (4.2 MJ) for 12 cm,\n// the thickness cubed (the breaching rule of thumb), leaving a hole about one and a half thicknesses wide with the bars across it.\n// Rolling resistance (C_rr) of each ground, for a round thing rolling on it. Tyre tables (Engineering ToolBox \"Rolling Resistance\", after Gillespie, Fundamentals of Vehicle\n// Dynamics, 1992; Wong, Theory of Ground Vehicles): concrete and new asphalt 0.010-0.015, small new cobbles 0.010-0.015, large worn cobbles 0.03, solid sand, loose gravel and\n// medium hard soil 0.04-0.08, loose sand 0.2-0.4. Grass: a mown golf green 0.07-0.13 (Penner, The physics of putting, Can. J. Phys. 80, 2002), a lawn is longer and slower.\n// A tyre spreads its load; a small rigid roller (a rod, a casing) sinks deeper for its size, so on soft ground the high end of each range is taken. Mud is taken as loose sand\n// (the wheel sinks), dry clay and laterite as medium hard soil at its low end, loose snow (0.3 m, a foot sinks 8 cm) an estimate between packed snow (~0.03) and sand.\n// The rough hard floors keep the 0.015 the kit has always used; a smooth one (glazed tile 0.008, a hardwood floor 0.01) holds a small roller back less, so a bottle rolls farther on it.\n// Rolling damping (1/s, `rollingDamping`): the share of its spin a roller loses per second on top of C_rr, from what drags more the faster it rolls (grass blades, ploughed sand\n// and mud, crunched gravel and snow). Rough hard floors lose 0.3 a second (grit, joints, the floor's own give), glazed tile and hardwood about a third of that; grass 1.5, so a can rolling onto a lawn stops within a metre\n// or two, as one does; loose sand and mud the most. Estimates from the stop distances of a ball or a can on each ground, not a table: no standard publishes them.\nexport const TERRAIN_MATERIALS: readonly TerrainMaterial[] = [\n {\n id: 'turf',\n rolling: 0.15,\n rollingDamping: 1.5,\n dig: { effort: 1.3 },\n debris: 'clods',\n rimShare: 0.25,\n reposeDegrees: 55,\n color: [0.09, 0.2, 0.04],\n pattern: 'grass',\n hits: {\n ballistic: { specificEnergy: 3e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.45 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.45, flammable: true },\n },\n {\n id: 'soil',\n rolling: 0.08,\n rollingDamping: 0.6,\n dig: { effort: 1 },\n debris: 'clods',\n rimShare: 0.35,\n reposeDegrees: 40,\n color: [0.2, 0.12, 0.06],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 4e6, aspect: 0.6 },\n blunt: { specificEnergy: 2e6, aspect: 0.2, thresholdJoules: 60 },\n slash: { specificEnergy: 3e5, aspect: 0.5 },\n explosive: { specificEnergy: 4e6, aspect: 0.45 },\n },\n fire: { maxScorch: 0.6, scorchPerSecond: 0.15 },\n },\n {\n id: 'sand',\n rolling: 0.3,\n rollingDamping: 2.0,\n dig: { effort: 0.8 },\n debris: 'dust',\n rimShare: 0.5,\n reposeDegrees: 33,\n color: [0.62, 0.5, 0.3],\n pattern: 'sand',\n hits: {\n ballistic: { specificEnergy: 2.5e6, aspect: 0.5 },\n blunt: { specificEnergy: 1e6, aspect: 0.2, thresholdJoules: 30 },\n slash: { specificEnergy: 1.5e5, aspect: 0.5 },\n explosive: { specificEnergy: 3e6, aspect: 0.35 },\n },\n fire: { maxScorch: 0.2, scorchPerSecond: 0.05 },\n },\n {\n id: 'gravel',\n rolling: 0.08,\n rollingDamping: 1.0,\n dig: { effort: 1.6 },\n debris: 'chips',\n rimShare: 0.15,\n reposeDegrees: 38,\n color: [0.27, 0.25, 0.22],\n pattern: 'gravel',\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.4 },\n blunt: { specificEnergy: 8e6, aspect: 0.2, thresholdJoules: 200 },\n slash: { specificEnergy: 3e7, aspect: 0.3, thresholdJoules: 400 },\n explosive: { specificEnergy: 1e7, aspect: 0.35 },\n },\n fire: { maxScorch: 0.3, scorchPerSecond: 0.06 },\n scatters: true,\n },\n {\n id: 'asphalt',\n rolling: 0.015,\n rollingDamping: 0.35,\n debris: 'chips',\n color: [0.05, 0.05, 0.055],\n pattern: 'asphalt',\n crack: { reach: 0.6, width: 0.008, thresholdJoules: 800 },\n hits: {\n ballistic: { specificEnergy: 3e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1e8, aspect: 0.1, thresholdJoules: 400 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 400 },\n explosive: { specificEnergy: 2e8, aspect: 0.12 },\n },\n fire: { maxScorch: 0.85, scorchPerSecond: 0.1, burnsAway: 0.00005 },\n },\n {\n id: 'concrete',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.33, 0.33, 0.31],\n pattern: 'concrete',\n crack: { reach: 1, width: 0.006, thresholdJoules: 300 },\n breach: { joulesPerCubedThickness: 2.4e9, radiusOverThickness: 1.5 },\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 3e8, aspect: 0.08, thresholdJoules: 800 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 2.7e9, aspect: 0.12 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'mortar',\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.42, 0.4, 0.36],\n pattern: 'plain',\n hits: {\n ballistic: { specificEnergy: 4e7, aspect: 0.2 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 300 },\n slash: { specificEnergy: 3e8, aspect: 0.2, thresholdJoules: 300 },\n explosive: { specificEnergy: 8e8, aspect: 0.14 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n },\n {\n id: 'ceramic',\n rolling: 0.008,\n rollingDamping: 0.1,\n debris: 'shards',\n color: [0.72, 0.7, 0.66],\n pattern: 'tile',\n crack: { reach: 0.5, width: 0.002, thresholdJoules: 40 },\n hits: {\n ballistic: { specificEnergy: 8e6, aspect: 0.1, minRadius: 0.05 },\n blunt: { specificEnergy: 1e7, aspect: 0.08, thresholdJoules: 80, minRadius: 0.06 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 200, minRadius: 0.03 },\n explosive: { specificEnergy: 1e8, aspect: 0.03, minRadius: 0.12 },\n },\n fire: { maxScorch: 0.5, scorchPerSecond: 0.08 },\n },\n {\n id: 'wood_hard',\n rolling: 0.01,\n rollingDamping: 0.12,\n debris: 'splinters',\n color: [0.3, 0.16, 0.07],\n pattern: 'planks',\n hits: {\n ballistic: { specificEnergy: 2.5e7, aspect: 0.35, minRadius: 0.012 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 120 },\n slash: { specificEnergy: 1.5e7, aspect: 0.4, thresholdJoules: 15 },\n explosive: { specificEnergy: 2e8, aspect: 0.1, minRadius: 0.1 },\n },\n fire: { maxScorch: 1, scorchPerSecond: 0.2, burnsAway: 0.0012, flammable: true },\n },\n {\n id: 'stone',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'chips',\n color: [0.23, 0.22, 0.2],\n pattern: 'stone',\n crack: { reach: 0.5, width: 0.004, thresholdJoules: 1000 },\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e8, aspect: 0.08, thresholdJoules: 1500 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 4e9, aspect: 0.14 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n },\n {\n id: 'mud',\n rolling: 0.3,\n rollingDamping: 3.0,\n // the shovel lifts it, and the hole fills in behind the blade\n dig: { effort: 1.4, closes: true },\n debris: 'clods',\n rimShare: 0.15,\n reposeDegrees: 18,\n color: [0.11, 0.075, 0.04],\n pattern: 'mud',\n hits: {\n ballistic: { specificEnergy: 1.2e6, aspect: 0.7 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 15 },\n slash: { specificEnergy: 5e4, aspect: 0.5 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.4 },\n },\n fire: { maxScorch: 0.15, scorchPerSecond: 0.03 },\n footing: { sink: 0.07, drag: 0.6, prints: true },\n splash: 'mud',\n splats: true,\n },\n {\n id: 'clay',\n rolling: 0.05,\n rollingDamping: 0.4,\n dig: { effort: 2.2 },\n debris: 'chips',\n color: [0.47, 0.27, 0.14],\n pattern: 'clay',\n hits: {\n ballistic: { specificEnergy: 1e7, aspect: 0.2, minRadius: 0.03 },\n blunt: { specificEnergy: 1.5e7, aspect: 0.15, thresholdJoules: 100 },\n slash: { specificEnergy: 6e7, aspect: 0.3, thresholdJoules: 30 },\n explosive: { specificEnergy: 8e6, aspect: 0.25 },\n },\n fire: { maxScorch: 0.35, scorchPerSecond: 0.05 },\n cracks: 4,\n },\n {\n // laterite, a soil baked hard (piçarra): no shovel goes in; only a heavy blow or a charge sinks or cracks it\n id: 'laterite',\n rolling: 0.05,\n rollingDamping: 0.4,\n debris: 'chips',\n rimShare: 0.2,\n color: [0.36, 0.17, 0.08],\n pattern: 'soil',\n hits: {\n ballistic: { specificEnergy: 5e7, aspect: 0.2, thresholdJoules: 200 },\n blunt: { specificEnergy: 8e7, aspect: 0.1, thresholdJoules: 600 },\n slash: { specificEnergy: 2e8, aspect: 0.1, thresholdJoules: 400 },\n explosive: { specificEnergy: 3e8, aspect: 0.18 },\n },\n },\n {\n id: 'snow',\n rolling: 0.1,\n rollingDamping: 1.2,\n dig: { effort: 0.6 },\n debris: 'dust',\n rimShare: 0.4,\n reposeDegrees: 38,\n color: [0.82, 0.85, 0.88],\n pattern: 'snow',\n hits: {\n ballistic: { specificEnergy: 1.5e6, aspect: 1 },\n blunt: { specificEnergy: 3e5, aspect: 0.3, thresholdJoules: 10 },\n slash: { specificEnergy: 5e4, aspect: 0.6 },\n explosive: { specificEnergy: 1.5e6, aspect: 0.5 },\n },\n fire: { maxScorch: 0, scorchPerSecond: 0, burnsAway: 0.015 },\n footing: { sink: 0.08, drag: 0.7, prints: true },\n },\n {\n id: 'cobble',\n rolling: 0.03,\n rollingDamping: 0.6,\n debris: 'blocks',\n color: [0.2, 0.19, 0.18],\n pattern: 'cobble',\n hits: {\n ballistic: { specificEnergy: 2.5e8, aspect: 0.12, minRadius: 0.015 },\n blunt: { specificEnergy: 5e7, aspect: 0.12, thresholdJoules: 250 },\n slash: { specificEnergy: 2e9, aspect: 0.2, thresholdJoules: 1500 },\n explosive: { specificEnergy: 1.5e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.4, scorchPerSecond: 0.06 },\n units: { length: 0.3, width: 0.2, looseJoules: 4000 },\n },\n {\n id: 'paver',\n rolling: 0.015,\n rollingDamping: 0.3,\n debris: 'blocks',\n color: [0.36, 0.33, 0.3],\n pattern: 'paver',\n hits: {\n ballistic: { specificEnergy: 1.5e8, aspect: 0.14, minRadius: 0.018 },\n blunt: { specificEnergy: 4e7, aspect: 0.12, thresholdJoules: 150 },\n slash: { specificEnergy: 1e9, aspect: 0.2, thresholdJoules: 800 },\n explosive: { specificEnergy: 1.2e7, aspect: 0.2 },\n },\n fire: { maxScorch: 0.45, scorchPerSecond: 0.08 },\n units: { length: 0.2, width: 0.2, looseJoules: 2500 },\n },\n]\n\n/** How far a blow is held back by the water it crosses before it reaches the bed: a round slows fast in water; a blast is pushed down by it. */\nconst WATER_BLOW_SHARE: Record<TerrainBlow, number> = { ballistic: 0.5, slash: 0.3, blunt: 0.5, explosive: 1 }\n\nexport const TERRAIN_PROFILES: readonly TerrainProfile[] = [\n { id: 'lawn', strata: [{ material: 'turf', thickness: 0.05 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dirt', strata: [{ material: 'soil', thickness: 1.8 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'sand', strata: [{ material: 'sand', thickness: 2.5 }] },\n { id: 'road', strata: [{ material: 'asphalt', thickness: 0.05 }, { material: 'gravel', thickness: 0.25 }, { material: 'soil', thickness: 1.5 }] },\n // a pavement for walking: concrete over its gravel bed over the soil, as the road's layers (a blast digs down to the pipes under it)\n { id: 'sidewalk', strata: [{ material: 'concrete', thickness: 0.08 }, { material: 'gravel', thickness: 0.22 }, { material: 'soil', thickness: 1.5 }] },\n { id: 'concrete_slab', strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'suspended_slab', drop: 3, strata: [{ material: 'concrete', thickness: 0.12, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'tile_floor', strata: [{ material: 'ceramic', thickness: 0.008 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'wood_floor', strata: [{ material: 'wood_hard', thickness: 0.022 }, { material: 'mortar', thickness: 0.03 }, { material: 'concrete', thickness: 0.1, reinforcement: { material: 'steel', cover: 0.03, spacing: 0.15, resistance: 4 } }] },\n { id: 'stone_paving', strata: [{ material: 'stone', thickness: 0.08 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n { id: 'mud', strata: [{ material: 'mud', thickness: 0.5 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'gravel_bed', strata: [{ material: 'gravel', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'dry_clay', strata: [{ material: 'clay', thickness: 0.35 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'snow', strata: [{ material: 'snow', thickness: 0.3 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'cobblestone', strata: [{ material: 'cobble', thickness: 0.12 }, { material: 'sand', thickness: 0.06 }, { material: 'gravel', thickness: 0.2 }, { material: 'soil', thickness: 1.2 }] },\n // rock at the surface (an outcrop, a quarry floor): a blast only spalls it and a shot chips it\n // a yard as it is dug: topsoil, the clay under it, rock deep down\n { id: 'yard', strata: [{ material: 'soil', thickness: 0.35 }, { material: 'clay', thickness: 1.6 }, { material: 'stone', thickness: 1 }] },\n // ground baked hard (laterite over rock): no shovel goes in\n { id: 'hardpan', strata: [{ material: 'laterite', thickness: 0.8 }, { material: 'stone', thickness: 1.5 }] },\n { id: 'bedrock', surfacePattern: 'rock', strata: [{ material: 'stone', thickness: 3 }] },\n { id: 'paver_floor', strata: [{ material: 'paver', thickness: 0.08 }, { material: 'sand', thickness: 0.05 }, { material: 'gravel', thickness: 0.15 }, { material: 'soil', thickness: 1.2 }] },\n // a pond deep enough to stand chest-high in: a charge on its bed goes off under the water\n { id: 'pond', water: { liquid: 'water', depth: 1.4, drag: 0.4, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.2 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n { id: 'shallow_water', water: { liquid: 'water', depth: 0.3, drag: 0.65, blowShare: WATER_BLOW_SHARE }, strata: [{ material: 'mud', thickness: 0.15 }, { material: 'soil', thickness: 1.5 }, { material: 'stone', thickness: 0.5 }] },\n]\n\n/** About twelve grenades (200 kJ) on the same spot of bare bars. */\nexport const DEFAULT_BAR_YIELD_JOULES = 2_400_000\n\n/** A 10 mm bar of CA-50 steel: bare, a mesh of them at 15 cm holds about 450 kg on a spot. */\nexport const DEFAULT_BAR_DIAMETER = 0.01\nexport const DEFAULT_BAR_YIELD_PA = 500e6\n\n/** The profile of a floor with nothing else said: a plain slab. */\nexport const DEFAULT_PROFILE = 'concrete_slab'\n","/** A small seeded stream: the same seed digs the same crater, so a blow of a few bytes draws the same on every client. */\nexport function createRandom(seed: number): () => number {\n let state = seed | 0\n return () => {\n state = (state + 0x6d2b79f5) | 0\n let mixed = Math.imul(state ^ (state >>> 15), 1 | state)\n mixed = (mixed + Math.imul(mixed ^ (mixed >>> 7), 61 | mixed)) ^ mixed\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n","import { createRandom } from './random'\nimport type { TerrainCrack } from './types'\n\n/** Energy the reach and width of a material's cracks are given for (`TerrainCrackResponse`). */\nexport const CRACK_REFERENCE_JOULES = 1e6\n/** A new star this close to an old one, as a share of the old one's reach, lengthens it instead. */\nconst MERGE_SHARE = 0.35\n/** Lines never get thinner than a hairline, nor more than a star holds. */\nconst HAIRLINE = 0.0015\nconst MIN_RAYS = 4\nconst MAX_RAYS = 11\nconst SEGMENTS = 4\nconst BRANCH_CHANCE = 0.45\n\n/** One piece of a crack line on the ground plane, with the width at each end. */\nexport interface CrackSegment {\n readonly x0: number\n readonly z0: number\n readonly x1: number\n readonly z1: number\n readonly w0: number\n readonly w1: number\n}\n\nexport interface CrackStore {\n readonly list: TerrainCrack[]\n readonly version: number\n /** Opens a star at the point, or lengthens and widens the one already there. */\n add(spec: { x: number; z: number; reach: number; width: number; material: string; seed: number }, max: number): TerrainCrack\n clear(): void\n load(cracks: readonly TerrainCrack[]): void\n}\n\nexport function createCrackStore(): CrackStore {\n const list: TerrainCrack[] = []\n let version = 0\n let nextId = 1\n let born = 0\n return {\n list,\n get version() {\n return version\n },\n add(spec, max) {\n version++\n const near = list.find((crack) => Math.hypot(crack.x - spec.x, crack.z - spec.z) < crack.reach * MERGE_SHARE)\n if (near) {\n // a second blow on cracked ground runs the lines further and opens them: concrete fatigues, it does not heal\n near.reach = Math.max(near.reach, spec.reach) + Math.min(near.reach, spec.reach) * 0.25\n near.width = Math.max(near.width, spec.width) * 1.1\n near.rays = Math.min(MAX_RAYS, near.rays + 1)\n return near\n }\n if (list.length >= max) list.shift()\n const rays = MIN_RAYS + Math.floor(createRandom(spec.seed)() * (MAX_RAYS - MIN_RAYS - 2))\n const crack: TerrainCrack = { id: nextId++, x: spec.x, z: spec.z, reach: spec.reach, width: Math.max(HAIRLINE, spec.width), rays, seed: spec.seed, material: spec.material, born: born++ }\n list.push(crack)\n return crack\n },\n clear() {\n list.length = 0\n version++\n },\n load(cracks) {\n list.length = 0\n for (const crack of cracks) {\n list.push({ ...crack })\n nextId = Math.max(nextId, crack.id + 1)\n born = Math.max(born, crack.born + 1)\n }\n version++\n },\n }\n}\n\n/**\n * The lines of a star, from its seed: rays that wander a little as they run out and thin towards their tips, with a branch now and then. The same crack always draws the same\n * lines, so only the crack travels in a snapshot or over the network.\n */\nexport function crackLines(crack: TerrainCrack): CrackSegment[] {\n const random = createRandom(crack.seed)\n const segments: CrackSegment[] = []\n const widthAt = (distance: number): number => Math.max(HAIRLINE, crack.width * (1 - distance / crack.reach))\n for (let ray = 0; ray < crack.rays; ray++) {\n let angle = (ray / crack.rays) * Math.PI * 2 + (random() - 0.5) * 0.6\n const length = crack.reach * (0.45 + 0.55 * random())\n let x = crack.x\n let z = crack.z\n let run = 0\n for (let segment = 0; segment < SEGMENTS; segment++) {\n const step = (length / SEGMENTS) * (0.75 + 0.5 * random())\n angle += (random() - 0.5) * 0.5\n const nx = x + Math.cos(angle) * step\n const nz = z + Math.sin(angle) * step\n segments.push({ x0: x, z0: z, x1: nx, z1: nz, w0: widthAt(run), w1: widthAt(run + step) })\n if (segment > 0 && random() < BRANCH_CHANCE) {\n const side = angle + (random() < 0.5 ? -1 : 1) * (0.45 + random() * 0.5)\n const branch = step * (0.5 + 0.6 * random())\n const w = widthAt(run + step) * 0.6\n segments.push({ x0: nx, z0: nz, x1: nx + Math.cos(side) * branch, z1: nz + Math.sin(side) * branch, w0: Math.max(HAIRLINE, w), w1: HAIRLINE })\n }\n run += step\n x = nx\n z = nz\n }\n }\n return segments\n}\n","import type { TerrainDebris, TerrainDebrisKind } from './types'\n\nconst REST_SPEED = 0.6\nconst RESTITUTION = 0.25\nconst FRICTION = 0.55\nconst MAX_BOUNCES = 2\nconst REST_GAP = 0.01\n\nexport interface DebrisWorld {\n heightAt(x: number, z: number): number\n gravity: number\n /** Soft pieces join the ground where they stop; a false keeps the piece as loose rubble. */\n settle(piece: TerrainDebris): boolean\n}\n\n/** Pieces thrown by blows: they fly, hit the deformed ground, and come to rest. Past `max` the oldest at rest goes first. */\nexport interface DebrisStore {\n readonly list: TerrainDebris[]\n throwPiece(spec: { material: string; kind: TerrainDebrisKind; radius: number; position: [number, number, number]; velocity: [number, number, number]; spin: [number, number, number] }): void\n update(dt: number, world: DebrisWorld): void\n clear(): void\n}\n\nexport function createDebrisStore(max: () => number): DebrisStore {\n const list: TerrainDebris[] = []\n let serial = 0\n\n function makeRoom(): void {\n if (list.length < max()) return\n let at = 0\n let oldest = Infinity\n let oldestResting = -1\n let restingBorn = Infinity\n list.forEach((piece, index) => {\n if (piece.born < oldest) {\n oldest = piece.born\n at = index\n }\n if (piece.atRest && piece.born < restingBorn) {\n restingBorn = piece.born\n oldestResting = index\n }\n })\n list.splice(oldestResting >= 0 ? oldestResting : at, 1)\n }\n\n return {\n list,\n throwPiece(spec) {\n makeRoom()\n list.push({ ...spec, id: ++serial, born: serial, atRest: false, bounces: 0 })\n },\n update(dt, world) {\n for (let i = list.length - 1; i >= 0; i--) {\n const piece = list[i]!\n if (piece.atRest) {\n // what it lay on was dug away or heaped over: it falls again, or rides up\n const under = world.heightAt(piece.position[0], piece.position[2]) + piece.radius * 0.6\n if (piece.position[1] > under + REST_GAP) piece.atRest = false\n else if (piece.position[1] < under - REST_GAP) piece.position[1] = under\n if (piece.atRest) continue\n }\n const { position, velocity } = piece\n velocity[1] -= world.gravity * dt\n position[0] += velocity[0] * dt\n position[1] += velocity[1] * dt\n position[2] += velocity[2] * dt\n const ground = world.heightAt(position[0], position[2]) + piece.radius * 0.6\n if (position[1] > ground) continue\n position[1] = ground\n const speed = Math.hypot(velocity[0], velocity[1], velocity[2])\n if (speed < REST_SPEED || piece.bounces >= MAX_BOUNCES) {\n piece.atRest = true\n if (world.settle(piece)) list.splice(i, 1)\n continue\n }\n piece.bounces++\n velocity[1] = Math.abs(velocity[1]) * RESTITUTION\n velocity[0] *= FRICTION\n velocity[2] *= FRICTION\n }\n },\n clear() {\n list.length = 0\n serial = 0\n },\n }\n}\n","import type { GroundLoss } from '@adatechnology/game-contracts'\nimport type { TerrainVoid } from './types'\n\n/** A loss shallower than this (m below the untouched surface) is a scuff, not a void anything bears over. */\nexport const GROUND_LOSS_MIN_DEPTH = 0.02\n/** Sand that slid tells the host only where it lowered the ground by at least this much (m). */\nexport const SLIDE_LOSS_MIN_LOWERING = 0.05\n/** Under this depth (m) a vertex still counts as ground in `voidUnder`. */\nexport const VOID_MIN_DEPTH = 0.02\n\nexport interface HeightGrid {\n readonly x0: number\n readonly z0: number\n readonly cellSize: number\n readonly stride: number\n readonly columns: number\n readonly rows: number\n readonly dug: Float32Array\n}\n\n/** What one event lowered, by vertex (metres of the column, not of the loose heap on it). Lowerings of the same vertex add up; a fill counts against them. */\nexport type LossTally = Map<number, number>\n\nexport function tallyLowered(tally: LossTally, index: number, amount: number): void {\n if (amount !== 0) tally.set(index, (tally.get(index) ?? 0) + amount)\n}\n\n/**\n * The disc the tally lowered, or null when it is shallower than `GROUND_LOSS_MIN_DEPTH`. Vertices lowered less than `minLowering` are left out. `depth` is\n * the deepest the ground is now under its untouched surface there. A `bowl` (a crater, sand that slid) is told as the paraboloid that is half as deep\n * where the ground is now half as deep, so a wide shallow scrape around a deep hole does not pass for a wide deep one; a `flat` hole (a slab that opened)\n * keeps its edge.\n */\nexport function lossOf(grid: HeightGrid, tally: LossTally, spec: { source: string; minLowering: number; shape: 'bowl' | 'flat' }): GroundLoss | null {\n let weight = 0\n let centerX = 0\n let centerZ = 0\n let depth = 0\n let deepest = 0\n const kept: number[] = []\n for (const [index, amount] of tally) {\n if (amount < spec.minLowering || amount <= 0) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n weight += amount\n centerX += (grid.x0 + column * grid.cellSize) * amount\n centerZ += (grid.z0 + row * grid.cellSize) * amount\n depth = Math.max(depth, grid.dug[index]!)\n deepest = Math.max(deepest, amount)\n kept.push(index)\n }\n if (weight <= 0 || depth < GROUND_LOSS_MIN_DEPTH || deepest < GROUND_LOSS_MIN_DEPTH) return null\n centerX /= weight\n centerZ /= weight\n let radius = 0\n for (const index of kept) {\n if (spec.shape === 'bowl' && grid.dug[index]! < depth / 2) continue\n const column = index % grid.stride\n const row = (index - column) / grid.stride\n radius = Math.max(radius, Math.hypot(grid.x0 + column * grid.cellSize - centerX, grid.z0 + row * grid.cellSize - centerZ))\n }\n const reach = spec.shape === 'bowl' ? Math.SQRT2 * (radius + grid.cellSize / 2) : radius + grid.cellSize / 2\n return { x: centerX, z: centerZ, radius: reach, depth, removed: weight * grid.cellSize * grid.cellSize, source: spec.source }\n}\n\n/** How much of the disc (x, z, radius) has no ground under where it was: the vertices inside it, or the nearest one when the disc is smaller than a cell. */\nexport function voidUnder(grid: HeightGrid, spec: { x: number; z: number; radius: number }): TerrainVoid {\n const { x, z, radius } = spec\n const clamp = (value: number, top: number): number => Math.max(0, Math.min(top, value))\n const column0 = clamp(Math.ceil((x - radius - grid.x0) / grid.cellSize), grid.columns)\n const column1 = clamp(Math.floor((x + radius - grid.x0) / grid.cellSize), grid.columns)\n const row0 = clamp(Math.ceil((z - radius - grid.z0) / grid.cellSize), grid.rows)\n const row1 = clamp(Math.floor((z + radius - grid.z0) / grid.cellSize), grid.rows)\n let count = 0\n let sum = 0\n let depth = 0\n let open = 0\n for (let row = row0; row <= row1; row++) {\n for (let column = column0; column <= column1; column++) {\n if (Math.hypot(grid.x0 + column * grid.cellSize - x, grid.z0 + row * grid.cellSize - z) > radius) continue\n const here = grid.dug[row * grid.stride + column]!\n count++\n sum += here\n depth = Math.max(depth, here)\n if (here >= VOID_MIN_DEPTH) open++\n }\n }\n if (count === 0) {\n const here = grid.dug[clamp(Math.round((z - grid.z0) / grid.cellSize), grid.rows) * grid.stride + clamp(Math.round((x - grid.x0) / grid.cellSize), grid.columns)]!\n return { depth: here, mean: here, fraction: here >= VOID_MIN_DEPTH ? 1 : 0 }\n }\n return { depth, mean: sum / count, fraction: open / count }\n}\n","/**\n * The ground's blend as pure functions of numbers, shared by `Terrain.heightAt`, `Terrain.heightGrid` and `heightPatchGrid`: the same code reads the terrain on the main\n * thread and a copy of its vertices anywhere else (a worker has no terrain), so the heights agree to the bit.\n */\n\n/** Where `v` falls along an axis of `count` cells of `cellSize` from `origin`, in cells, held inside the last cell: its whole part is the cell, the rest the blend across it. */\nexport const cellCoordinate = (v: number, origin: number, count: number, cellSize: number): number => Math.max(0, Math.min(count - 1e-6, (v - origin) / cellSize))\n\n/** The blend of two heights, `t` of the way from `near` to `far` (the one step every blend of the ground is made of). */\nexport const blendHeights = (near: number, far: number, t: number): number => near * (1 - t) + far * t\n\n/**\n * The terrain's vertex heights (`base - dug + loose`, as `heightAt` reads them) over a block of its cells, with what places them in the terrain: plain numbers, so a worker\n * can read the ground from them (`heightPatchGrid`) and answer what `heightGrid` does there, to the bit. Made by `Terrain.heightPatch`.\n */\nexport interface HeightPatch {\n readonly cellSize: number\n /** The terrain's first vertex (its bounds' min x and z) and its cells along x and z: where a point's cell is found, with its clamps. */\n readonly originX: number\n readonly originZ: number\n readonly columns: number\n readonly rows: number\n /** The patch's first vertex (column and row of the terrain) and how many vertices it has along x and along z. */\n readonly column0: number\n readonly row0: number\n readonly width: number\n readonly depth: number\n /** The heights, `width` per row, rows from `row0`: `heights[(row - row0) * width + column - column0]` (the array may be longer). */\n readonly heights: Float64Array\n}\n\n// the cell and the blend of each column and row a patch read finds, kept between reads (one at a time) so a read costs no new arrays\nlet patchColumns = new Int32Array(0)\nlet patchBlendX = new Float64Array(0)\nlet patchNear = new Float64Array(0)\nlet patchFar = new Float64Array(0)\n\n/**\n * The ground over a lattice from a patch: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what the terrain's `heightGrid` answers there (the same\n * cell, clamps and blends, on the same vertex heights). Every point must lie inside the terrain and over the patch's cells (`Terrain.heightPatch` of a rectangle holding\n * them): one that does not throws. Not reentrant (module scratch).\n */\nexport function heightPatchGrid(patch: HeightPatch, xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void {\n const width = xs.length\n const depth = zs.length\n if (out.length < width * depth) throw new RangeError(`heightPatchGrid: out holds ${out.length} heights, the grid has ${width * depth}`)\n const { cellSize, originX, originZ, columns, rows, column0, row0, heights } = patch\n const stride = patch.width\n if (patchColumns.length < width) {\n patchColumns = new Int32Array(width)\n patchBlendX = new Float64Array(width)\n patchNear = new Float64Array(width)\n patchFar = new Float64Array(width)\n }\n for (let i = 0; i < width; i++) {\n const fx = cellCoordinate(xs[i]!, originX, columns, cellSize)\n const column = (fx | 0) - column0\n if (column < 0 || column + 1 >= stride) throw new RangeError(`heightPatchGrid: x ${xs[i]} is past the patch`)\n patchColumns[i] = column\n patchBlendX[i] = fx - (fx | 0)\n }\n let blended = -1\n for (let j = 0; j < depth; j++) {\n const fz = cellCoordinate(zs[j]!, originZ, rows, cellSize)\n const row = (fz | 0) - row0\n if (row < 0 || row + 1 >= patch.depth) throw new RangeError(`heightPatchGrid: z ${zs[j]} is past the patch`)\n const tz = fz - (fz | 0)\n // the two x blends of a column depend on its row of cells only, as in `heightGrid`\n if (row !== blended) {\n blended = row\n for (let i = 0; i < width; i++) {\n const index = row * stride + patchColumns[i]!\n const tx = patchBlendX[i]!\n patchNear[i] = blendHeights(heights[index]!, heights[index + 1]!, tx)\n patchFar[i] = blendHeights(heights[index + stride]!, heights[index + stride + 1]!, tx)\n }\n }\n for (let i = 0; i < width; i++) out[j * width + i] = blendHeights(patchNear[i]!, patchFar[i]!, tz)\n }\n}\n\n/** Whether two patches hold the same vertices at the same heights (the ground they read is the same, to the bit, wherever both reach). */\nexport const samePatch = (a: HeightPatch, b: HeightPatch): boolean => {\n if (a.cellSize !== b.cellSize || a.originX !== b.originX || a.originZ !== b.originZ || a.columns !== b.columns || a.rows !== b.rows) return false\n if (a.column0 !== b.column0 || a.row0 !== b.row0 || a.width !== b.width || a.depth !== b.depth) return false\n const count = a.width * a.depth\n for (let k = 0; k < count; k++) if (a.heights[k] !== b.heights[k]) return false\n return true\n}\n","import type { TerrainBudget, TerrainMark } from './types'\n\n/** Two marks at this fraction of their radii or closer are one hole. */\nconst SAME_HOLE = 0.75\n\n/** Fine marks under a budget per area and a global one: past the budget the closest two of the area become one, and past the global one the oldest goes. */\nexport interface MarkStore {\n readonly list: TerrainMark[]\n add(spec: Omit<TerrainMark, 'id' | 'count' | 'born'>): TerrainMark\n near(x: number, z: number, radius: number): TerrainMark | undefined\n depthAt(x: number, z: number): number\n remove(mark: TerrainMark): void\n removeInside(x: number, z: number, radius: number): void\n clear(): void\n load(marks: readonly TerrainMark[]): void\n readonly version: number\n}\n\nexport function createMarkStore(budget: TerrainBudget): MarkStore {\n const list: TerrainMark[] = []\n const areas = new Map<number, TerrainMark[]>()\n let serial = 0\n let version = 0\n const areaKey = (x: number, z: number): number => Math.floor(x / budget.markAreaSize) * 100003 + Math.floor(z / budget.markAreaSize)\n\n function detach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) {\n const at = area.indexOf(mark)\n if (at >= 0) area.splice(at, 1)\n if (area.length === 0) areas.delete(key)\n }\n const at = list.indexOf(mark)\n if (at >= 0) list.splice(at, 1)\n version++\n }\n\n function attach(mark: TerrainMark): void {\n const key = areaKey(mark.x, mark.z)\n const area = areas.get(key)\n if (area) area.push(mark)\n else areas.set(key, [mark])\n list.push(mark)\n version++\n }\n\n function mergeClosestPair(area: TerrainMark[]): void {\n let bestA = area[0]!\n let bestB = area[1]!\n let best = Infinity\n for (let i = 0; i < area.length; i++) {\n for (let j = i + 1; j < area.length; j++) {\n const distance = Math.hypot(area[i]!.x - area[j]!.x, area[i]!.z - area[j]!.z)\n if (distance < best) {\n best = distance\n bestA = area[i]!\n bestB = area[j]!\n }\n }\n }\n const weight = bestA.radius ** 2 + bestB.radius ** 2\n const shareB = weight > 0 ? bestB.radius ** 2 / weight : 0.5\n detach(bestB)\n bestA.x += (bestB.x - bestA.x) * shareB\n bestA.z += (bestB.z - bestA.z) * shareB\n bestA.radius = Math.sqrt(weight)\n bestA.depth = Math.max(bestA.depth, bestB.depth)\n bestA.count += bestB.count\n version++\n }\n\n return {\n list,\n add(spec) {\n const mark: TerrainMark = { ...spec, id: ++serial, count: 1, born: serial }\n attach(mark)\n const area = areas.get(areaKey(mark.x, mark.z))!\n if (area.length > budget.maxMarksPerArea) mergeClosestPair(area)\n if (list.length > budget.maxMarks) detach(list.reduce((oldest, candidate) => (candidate.born < oldest.born ? candidate : oldest)))\n return mark\n },\n near(x, z, radius) {\n let found: TerrainMark | undefined\n let best = Infinity\n const reach = Math.ceil((radius + 0.5) / budget.markAreaSize)\n const baseX = Math.floor(x / budget.markAreaSize)\n const baseZ = Math.floor(z / budget.markAreaSize)\n for (let dx = -reach; dx <= reach; dx++) {\n for (let dz = -reach; dz <= reach; dz++) {\n for (const mark of areas.get((baseX + dx) * 100003 + baseZ + dz) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < best && distance < Math.max(mark.radius, radius) * SAME_HOLE) {\n best = distance\n found = mark\n }\n }\n }\n }\n return found\n },\n depthAt(x, z) {\n let depth = 0\n for (const mark of areas.get(areaKey(x, z)) ?? []) {\n const distance = Math.hypot(mark.x - x, mark.z - z)\n if (distance < mark.radius) depth = Math.max(depth, mark.depth * (1 - (distance / mark.radius) ** 2))\n }\n return depth\n },\n remove: detach,\n removeInside(x, z, radius) {\n for (const mark of [...list]) if (Math.hypot(mark.x - x, mark.z - z) + mark.radius * 0.5 < radius) detach(mark)\n },\n clear() {\n list.length = 0\n areas.clear()\n // the numbering starts again with the ground (a loaded snapshot takes it on from its own marks); `version` only grows, the renderers follow it\n serial = 0\n version++\n },\n load(marks) {\n this.clear()\n for (const mark of marks) {\n attach({ ...mark })\n serial = Math.max(serial, mark.id)\n }\n },\n get version() {\n return version\n },\n }\n}\n","import type { DestructibleImpl, DestructibleSpec, DestructionEvent, Hit, ObjectState, SurfaceRay, SurfaceRayHit } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainBlowResult } from './types'\n\nconst PART_ID = 'ground'\nconst PART_DEPTH = 3\nconst RAY_BACKOFF = 1\nconst GROUND_HP = 1e12\n/** Most metres the ground rises above its flat level (a heap of what a crater threw out): a ray higher than this cannot meet it. */\nconst HEAP_REACH = 3\n\nexport interface TerrainImplOptions {\n readonly id: string\n readonly name?: string\n /** Every blow that left its mark, with what it did. */\n readonly onBlow?: (result: TerrainBlowResult, hit: Hit) => void\n}\n\n/**\n * The ground as an object of the destruction world (`DestructionWorld.register`): shots, blows, blasts and flames reach it through the world's own raycast and blast like anything else.\n * The collision part is a flat box that only says where to look: the world's raycast asks `surfaceRay`, which follows the ground as it is now (craters, heaps),\n * so a round fired into a crater meets its floor, not the flat top of the box over it.\n */\nexport function createTerrainImpl(terrain: Terrain, options: TerrainImplOptions): DestructibleImpl {\n const { id } = options\n const [x0, z0, x1, z1] = terrain.bounds\n const centerColumn = Math.max(0, Math.min(terrain.columns, Math.round((x1 - x0) / 2 / terrain.cellSize)))\n const centerRow = Math.max(0, Math.min(terrain.rows, Math.round((z1 - z0) / 2 / terrain.cellSize)))\n const centerMaterial = (): string => terrain.vertexMaterial(centerColumn, centerRow).id\n const buildSpec = (material: string): DestructibleSpec => ({\n name: options.name ?? 'Ground',\n parts: [\n {\n id: PART_ID,\n material,\n shape: { kind: 'box', size: [x1 - x0, PART_DEPTH, z1 - z0] },\n position: [(x0 + x1) / 2, -PART_DEPTH / 2, (z0 + z1) / 2],\n hp: GROUND_HP,\n anchored: true,\n tags: ['terrain'],\n },\n ],\n joints: [],\n })\n let cachedSpec: DestructibleSpec | undefined\n const spec = (): DestructibleSpec => {\n const material = centerMaterial()\n if (cachedSpec?.parts[0]?.material !== material) cachedSpec = buildSpec(material)\n return cachedSpec\n }\n const buildState = (material: string): ObjectState => ({\n id,\n position: [0, 0, 0],\n rotation: [0, 0, 0, 1],\n parts: [{ id: PART_ID, material, status: 'intact', hp: GROUND_HP, maxHp: GROUND_HP, mass: 0, temperature: 0, burning: false, fuel: 0, char: 0, melt: 0, dents: [], holes: [], cracks: [], group: 0 }],\n joints: [],\n groups: [[PART_ID]],\n destroyed: false,\n })\n let cachedState: ObjectState | undefined\n const state = (): ObjectState => {\n const material = centerMaterial()\n if (cachedState?.parts[0]?.material !== material) cachedState = buildState(material)\n return cachedState\n }\n const resolve = (hit: Hit): Hit => {\n if (hit.type !== 'ballistic' && hit.type !== 'blunt' && hit.type !== 'slash') return hit\n if (!hit.direction) return { ...hit, point: [hit.point[0], terrain.heightAt(hit.point[0], hit.point[2]), hit.point[2]] }\n const [dx, dy, dz] = hit.direction\n const from = [hit.point[0] - dx * RAY_BACKOFF, hit.point[1] - dy * RAY_BACKOFF, hit.point[2] - dz * RAY_BACKOFF]\n const onGround = terrain.raycast(from, hit.direction, RAY_BACKOFF + PART_DEPTH)\n return onGround ? { ...hit, point: onGround.point } : hit\n }\n /** The ground as it is now along the ray, marched only where the ray is within the depth of the ground and the height of a heap. */\n const surfaceRay = (ray: SurfaceRay): SurfaceRayHit | null => {\n if (ray.ignored?.(PART_ID)) return null\n const [ox, oy, oz] = ray.origin\n const [dx, dy, dz] = ray.direction\n const enter = dy < 0 ? Math.max(0, (oy - HEAP_REACH) / -dy) : oy <= HEAP_REACH ? 0 : Infinity\n const leave = dy < 0 ? (oy + PART_DEPTH) / -dy : Math.hypot(x1 - x0, z1 - z0) + Math.hypot(ox - (x0 + x1) / 2, oz - (z0 + z1) / 2)\n const far = Math.min(ray.maxDistance, leave)\n if (!(enter <= far)) return null\n const hit = terrain.raycast([ox + dx * enter, oy + dy * enter, oz + dz * enter], ray.direction, far - enter)\n if (!hit) return null\n return { part: PART_ID, point: hit.point, normal: hit.normal, distance: enter + hit.distance, pathLen: PART_DEPTH }\n }\n return {\n id,\n ...(options.name ? { name: options.name } : {}),\n describe: spec,\n surfaceRay,\n hit(hit): DestructionEvent[] {\n const landed = resolve(hit)\n const result = terrain.applyHit(landed)\n if (!result || result.radius <= 0) return []\n options.onBlow?.(result, landed)\n return [{ type: 'damage', object: id, time: 0, part: PART_ID, amount: 0, hp: GROUND_HP, damageType: hit.type, ...(hit.source ? { source: hit.source } : {}) }]\n },\n update(dt) {\n terrain.update(dt)\n return []\n },\n state,\n reset() {\n terrain.reset()\n },\n serialize: () => terrain.serialize(),\n load(data) {\n terrain.load(data as ReturnType<Terrain['serialize']>)\n },\n }\n}\n","import type { GroundExcavation, GroundLayout, GroundLoss, Hit } from '@adatechnology/game-contracts'\n\nimport type { HeightPatch } from './height-patch'\n\nexport type { GroundExcavation, GroundLayout, GroundZone } from '@adatechnology/game-contracts'\n\n/** The blows that remove ground. Fire and heat char it instead (`TerrainMaterial.fire`). */\nexport type TerrainBlow = 'ballistic' | 'blunt' | 'slash' | 'explosive'\n\n/** A blow at (x, z): `energy` in joules, `direction` where it travels, `contactRadius` of a blunt tool, `caliber` (mm) of a round, which shapes its crater. */\nexport type TerrainStrike = { x: number; z: number; energy: number; direction?: readonly number[]; contactRadius?: number; caliber?: number }\n\n/** What one kind of blow does to a material. */\nexport interface TerrainBlowResponse {\n /** Joules it takes to remove one cubic metre. */\n readonly specificEnergy: number\n /** Depth over radius of the bowl it leaves: a soft ground craters deep, a hard one spalls wide and shallow. */\n readonly aspect: number\n /** A blow under this many joules leaves nothing (a punch on a slab). */\n readonly thresholdJoules?: number\n /** The bowl is never narrower: a tile comes off as a piece, not as the size of the bullet. */\n readonly minRadius?: number\n}\n\nexport type TerrainDebrisKind = 'clods' | 'chips' | 'shards' | 'splinters' | 'dust' | 'blocks'\n\n/** How a material of the destruction catalogue behaves as ground. `id` is the catalogue's. */\nexport interface TerrainMaterial {\n readonly id: string\n readonly hits: Partial<Record<TerrainBlow, TerrainBlowResponse>>\n readonly debris: TerrainDebrisKind\n /** Share of what a blow removes that piles up on the rim; the rest is thrown. Rigid materials have none. */\n readonly rimShare?: number\n /** Steepest slope in degrees it holds; loose ground slides until it is back to it. */\n readonly reposeDegrees?: number\n /** A shovel digs it: `effort` is how hard a shovelful is against loose soil (1); a material without it (concrete, stone, asphalt) is not dug by hand. */\n readonly dig?: { readonly effort: number; readonly closes?: boolean }\n readonly fire?: TerrainFireResponse\n /** Linear rgb, 0..1, of the material where it is exposed. */\n readonly color: readonly [number, number, number]\n /** Surface pattern a renderer draws while the stratum is intact (`TERRAIN_PATTERNS`). */\n readonly pattern?: TerrainPattern\n /** A rigid surface cracks around a hard blow instead of only losing a bowl: lines that run out from the point (concrete, asphalt, tile, stone). */\n readonly crack?: TerrainCrackResponse\n /** A rigid layer a contact charge breaks right through once it has enough for the whole thickness (the scabbing of a slab): `explosive` only. */\n readonly breach?: TerrainBreachResponse\n /** What a foot does on it. */\n readonly footing?: TerrainFooting\n /**\n * Its rolling resistance (C_rr) to a round thing rolling on it (a can, a rod, a casing): the moment C_rr x weight x radius that slows the roll. Soft ground (sand, mud,\n * grass) gives under the roller and holds it back far more than a hard one (asphalt, concrete). Left out: the host's default (a hard floor).\n */\n readonly rolling?: number\n /**\n * Its rolling damping (1/s): the share of its spin a round thing rolling on it loses per second on top of `rolling`, from what drags more the faster it rolls (grass\n * blades, ploughed sand). Added to the roller's own. Left out: the host's default (a hard floor).\n */\n readonly rollingDamping?: number\n /** Liquid (of the fluids catalogue) a blow on it throws up. */\n readonly splash?: string\n /** Its pieces do not join the ground where they land: they stay as loose stones. */\n readonly scatters?: boolean\n /** Its pieces leave a splat on whatever they land on. */\n readonly splats?: boolean\n /** A brittle crust: each blow runs cracks this many bowl radii around it. */\n readonly cracks?: number\n /** Laid in separate pieces on a bed: a blow loosens whole pieces instead of digging a bowl. */\n readonly units?: TerrainUnits\n}\n\nexport interface TerrainCrackResponse {\n /** Metres the longest line runs for a blow of 1 MJ; it grows with the cube root of the energy. */\n readonly reach: number\n /** Metres wide the lines open at the point for 1 MJ, also by the cube root, never under a hairline. */\n readonly width: number\n /** A blow under this many joules leaves no crack (a punch on a slab). */\n readonly thresholdJoules: number\n}\n\nexport interface TerrainBreachResponse {\n /** Joules over the cube of the layer's thickness (J/m³) that break the whole layer through: for reinforced concrete about 1 kg of TNT for 12 cm. */\n readonly joulesPerCubedThickness: number\n /** Radius of the breach over the thickness at that energy; it grows with the cube root of the excess. */\n readonly radiusOverThickness: number\n}\n\nexport interface TerrainFooting {\n /** Metres the foot goes in. */\n readonly sink: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Keeps the print of what presses it. */\n readonly prints?: boolean\n}\n\nexport interface TerrainUnits {\n /** Metres along x, in rows that shift every other one. Multiples of the cell keep the hole sharp. */\n readonly length: number\n /** Metres along z. */\n readonly width: number\n /** Joules a piece takes, added blow by blow, before it comes off its bed. */\n readonly looseJoules: number\n}\n\nexport interface TerrainFireResponse {\n /** How black it gets, 0..1: concrete only soots, wood and turf char through. */\n readonly maxScorch: number\n /** Scorch gained per second in a flame. */\n readonly scorchPerSecond: number\n /** Metres per second the flame eats away (wood char). */\n readonly burnsAway?: number\n /** Catches and carries the fire to the next cells on its own. */\n readonly flammable?: boolean\n}\n\nexport const TERRAIN_PATTERNS = ['plain', 'grass', 'soil', 'sand', 'asphalt', 'concrete', 'tile', 'planks', 'stone', 'mud', 'gravel', 'clay', 'snow', 'cobble', 'paver', 'rock'] as const\nexport type TerrainPattern = (typeof TERRAIN_PATTERNS)[number]\n\n/** One layer of a column, from the top down. */\nexport interface TerrainStratum {\n /** A `TerrainMaterial.id`. */\n readonly material: string\n /** Metres. */\n readonly thickness: number\n /** Bars inside the layer: exposed at `cover`, they make the digging `resistance` times harder. */\n readonly reinforcement?: {\n readonly material: string\n readonly cover: number\n readonly spacing: number\n readonly resistance: number\n /** Joules on one spot of bare bars before they give way (default `DEFAULT_BAR_YIELD_JOULES`). */\n readonly yieldJoules?: number\n /** Metres across one bar (default `DEFAULT_BAR_DIAMETER`): with `yieldPa` it says what weight bare bars hold. */\n readonly diameter?: number\n /** Pascals at which the steel yields (default `DEFAULT_BAR_YIELD_PA`). */\n readonly yieldPa?: number\n }\n}\n\n/** Weight standing still on the ground: a body, a fridge, a car. */\nexport interface TerrainLoad {\n readonly x: number\n readonly z: number\n /** Metres: half the side of the footprint it stands on. */\n readonly radius: number\n readonly newtons: number\n}\n\n/** What a column of ground is made of. The strata end at the digging limit: under them nothing is removed. */\nexport interface TerrainProfile {\n readonly id: string\n readonly strata: readonly TerrainStratum[]\n /** A slab with nothing under it: where its bars give way the floor opens, and the ground is this many metres further down (the floor below). Without it the ground under the slab holds it up. */\n readonly drop?: number\n /** How the untouched top layer is drawn when it is not its material's way: bare rock is stone, but not laid as paving. Dug, the material's own shows. */\n readonly surfacePattern?: TerrainPattern\n /** Water standing over the column: the strata are its bed. */\n readonly water?: TerrainWater\n}\n\nexport interface TerrainWater {\n /** A liquid of the fluids catalogue. */\n readonly liquid: string\n /** Metres from the surface to the bed. */\n readonly depth: number\n /** What is left of the walking speed, 0..1. */\n readonly drag: number\n /** Share of a blow that reaches the bed. */\n readonly blowShare: Partial<Record<TerrainBlow, number>>\n}\n\nexport interface TerrainBudget {\n /** Side in metres of the squares that hold a limited number of marks. */\n readonly markAreaSize: number\n readonly maxMarksPerArea: number\n readonly maxMarks: number\n /** Chunks a renderer redraws per frame; the rest wait. */\n readonly maxDirtyChunksPerFrame: number\n readonly maxDebris: number\n /** Thrown pieces of one blow. */\n readonly maxDebrisPerBlow: number\n /** Cells checked for sliding per frame. */\n readonly maxSlideCellsPerFrame: number\n /** Cells on fire at once. */\n readonly maxBurningCells: number\n /** Stars of cracks kept; past it the oldest goes. */\n readonly maxCracks: number\n /** Cracks, prints, ruts, splats and ripples at once; past it the oldest goes. */\n readonly maxDecals: number\n}\n\nexport interface TerrainOptions {\n /** World rectangle `[x0, z0, x1, z1]` in metres. */\n readonly bounds: readonly [number, number, number, number]\n /** Metres per cell (default 0.1). */\n readonly cellSize?: number\n /** Cells per side of a chunk (default 32). */\n readonly chunkCells?: number\n /** Which profile is where. */\n readonly layout?: GroundLayout\n /** Extra or overriding profiles, by id. */\n readonly profiles?: readonly TerrainProfile[]\n /** Extra or overriding materials, by id. */\n readonly materials?: readonly TerrainMaterial[]\n readonly budget?: Partial<TerrainBudget>\n /** Height of the untouched ground (default flat at 0). */\n readonly baseHeight?: (x: number, z: number) => number\n /** Metres per second squared. */\n readonly gravity?: number\n readonly seed?: number\n /**\n * Ground taken away from under the surface: a crater (`crater`), a slab that gave way into the void under it (`slab`), sand that slid off a slope\n * (`slide`). The host hands it to what stands there (`DestructionWorld.groundLoss`), so foundations over it settle or lose their support.\n */\n readonly onGroundLoss?: (loss: GroundLoss) => void\n}\n\n/** A shovelful (`Terrain.dig`): the blade's footprint at (x, z), how deep it goes in, where the earth is thrown (a heap on the ground there). */\nexport interface TerrainDig {\n readonly x: number\n readonly z: number\n /** Width and length of the blade's bite, metres (default 0.3 x 0.3). */\n readonly size?: readonly [number, number]\n /** How deep one shovelful goes, metres (default 0.2). */\n readonly depth?: number\n /** Where the earth lands: heaped round this point. Without it, it is lost (carried away). */\n readonly dump?: { readonly x: number; readonly z: number }\n}\n\n/** What a shovelful took. */\nexport interface TerrainDigResult {\n /** Cubic metres taken out (and heaped at `dump`). */\n readonly volume: number\n /** The material dug (the one at the bite's centre). */\n readonly material: string\n /** How hard it was against loose soil (1): a shovelful of it takes that much longer. 0 when nothing was dug. */\n readonly effort: number\n /** The material that stopped the blade (concrete, stone...), when it could not dig; `water` where the ground is under water. */\n readonly refused?: string\n /** The blade lifted it but the hole closed behind it (mud): nothing changed. */\n readonly closes?: true\n}\n\n/** Earth thrown back into a hole (`Terrain.fill`): taken from the heap round `from`, laid into the hole at (x, z), at most `volume`. */\nexport interface TerrainFill {\n readonly x: number\n readonly z: number\n readonly size?: readonly [number, number]\n readonly from: { readonly x: number; readonly z: number; readonly radius: number }\n readonly volume: number\n}\n\n/** What is missing under a disc of the ground (`Terrain.voidUnder`). */\nexport interface TerrainVoid {\n /** Metres under the untouched surface at the deepest vertex. */\n readonly depth: number\n /** Metres under the untouched surface, averaged over the disc. */\n readonly mean: number\n /** 0..1, the share of the disc's vertices that are void (dug at least `VOID_MIN_DEPTH`). */\n readonly fraction: number\n}\n\n/** A fine mark: a bullet pock or a chip, smaller than a cell. It grows with the blows on it until it is dug into the height field. */\nexport interface TerrainMark {\n readonly id: number\n x: number\n z: number\n radius: number\n depth: number\n /** The material the mark shows at the bottom. */\n material: string\n blow: TerrainBlow\n /** Blows and marks merged into this one. */\n count: number\n /** Order of creation: the oldest is the one recycled. */\n born: number\n}\n\nexport type TerrainDecalKind = 'crack' | 'print' | 'rut' | 'splat' | 'ripple'\n\n/** A mark with no depth of its own: drawn over the surface, it changes nothing that stands there. */\nexport interface TerrainDecal {\n readonly id: number\n readonly kind: TerrainDecalKind\n readonly x: number\n readonly z: number\n readonly radius: number\n /** Radians around y. */\n readonly angle: number\n /** The material whose colour it takes. */\n readonly material: string\n /** Seconds it has been there; a ripple fades with it. */\n age: number\n}\n\nexport interface TerrainDebris {\n readonly id: number\n readonly material: string\n readonly kind: TerrainDebrisKind\n readonly radius: number\n readonly position: [number, number, number]\n readonly velocity: [number, number, number]\n readonly spin: [number, number, number]\n atRest: boolean\n bounces: number\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** A star of cracks on a rigid surface. The lines themselves come from `crackLines`, drawn from the seed, so a snapshot keeps only this. */\nexport interface TerrainCrack {\n readonly id: number\n readonly x: number\n readonly z: number\n /** Metres the longest line runs. */\n reach: number\n /** Metres wide the lines are at the point. */\n width: number\n rays: number\n readonly seed: number\n readonly material: string\n /** Order of creation: the oldest is the one recycled. */\n readonly born: number\n}\n\n/** What a blow did. */\nexport interface TerrainBlowResult {\n readonly point: readonly [number, number, number]\n /** Bowl radius in metres; 0 when the blow left nothing. */\n readonly radius: number\n /** Metres removed at the point. */\n readonly depth: number\n /** Metres under the untouched surface the point is now. */\n readonly totalDepth: number\n /** Materials removed, top first, with the cubic metres of each. */\n readonly removed: readonly { readonly material: string; readonly volume: number }[]\n /** Material now exposed at the point. */\n readonly exposed: string\n /** The column has no more to give here: the slab's bottom, the end of the rock. */\n readonly atLimit: boolean\n /** Reinforcement is showing at the point. */\n readonly rebarExposed: boolean\n /** The bars gave way here and the slab opened (`TerrainProfile.drop`). */\n readonly collapsed: boolean\n /** Left a fine mark (`true`) or dug the height field (`false`). */\n readonly fine: boolean\n /** The cracks it opened or lengthened around the point, if the surface is rigid. */\n readonly crack?: TerrainCrack\n /** A contact charge broke the rigid layer right through (`TerrainMaterial.breach`). */\n readonly breached?: boolean\n /** The water the blow crossed: `level` is where the splash goes up. */\n readonly water?: { readonly liquid: string; readonly level: number }\n}\n\n/** The water standing at a point. */\nexport interface TerrainWaterHere {\n readonly liquid: string\n readonly level: number\n readonly depth: number\n}\n\nexport interface TerrainRegion {\n readonly x: number\n readonly z: number\n readonly radius: number\n}\n\nexport interface TerrainColumn {\n readonly profile: string\n readonly material: string\n readonly stratum: number\n /** Metres under the untouched surface. */\n readonly depth: number\n /** Metres that can still be dug here. */\n readonly remaining: number\n readonly scorch: number\n readonly loose: number\n}\n\nexport interface TerrainStats {\n readonly marks: number\n readonly debris: number\n readonly debrisMoving: number\n readonly dirtyChunks: number\n readonly burning: number\n}\n\nexport interface TerrainChunk {\n readonly index: number\n /** First column and row of the chunk's vertices. */\n readonly column: number\n readonly row: number\n readonly cells: number\n /** True while nothing touched it and it has one profile: one flat quad draws it. */\n readonly pristine: boolean\n}\n\nexport interface Terrain {\n readonly bounds: readonly [number, number, number, number]\n readonly cellSize: number\n readonly columns: number\n readonly rows: number\n /** Vertices per row. */\n readonly stride: number\n readonly chunkCells: number\n readonly chunksX: number\n readonly chunksZ: number\n readonly budget: TerrainBudget\n /** Per vertex: metres removed under the untouched surface. */\n readonly dug: Float32Array\n /** Per vertex: metres of loose ground heaped on top. */\n readonly loose: Float32Array\n /** Per vertex: 0..1, how burnt. */\n readonly scorch: Float32Array\n /** Per vertex: how far the bare bars have given, 0 straight, 1 or more gone. */\n readonly barBend: Float32Array\n /** Per vertex: index in `profileList`. */\n readonly profileIndex: Uint8Array\n readonly profileList: readonly TerrainProfile[]\n material(id: string): TerrainMaterial\n layout(): GroundLayout\n setLayout(layout: GroundLayout): void\n /** Height at (x, z) as things stand on it. */\n heightAt(x: number, z: number): number\n /**\n * `heightAt` over a grid, in one pass: the height at (`xs[i]`, `zs[j]`) into `out[j * xs.length + i]`, to the bit what `heightAt` answers there (the same cell, blend and\n * vertices; past the terrain, the host's `baseHeight`). For a reader of many points on a lattice (a physics engine's ground tile), which saves a call per point.\n * Not reentrant: it keeps its scratch between calls, so a `baseHeight` must not call it back.\n */\n heightGrid(xs: ArrayLike<number>, zs: ArrayLike<number>, out: Float64Array): void\n /**\n * The vertex heights under a rectangle (the cells `heightGrid` reads for any point in it), as plain numbers a worker can read the ground from (`heightPatchGrid`, to the\n * bit what `heightGrid` answers there); null when the rectangle is not wholly inside the terrain (past it the host's `baseHeight` answers). Writes into `into` when it is\n * long enough, else a new array. A 2.4 m square at 10 cm cells is 26 x 26 numbers.\n */\n heightPatch(minX: number, maxX: number, minZ: number, maxZ: number, into?: Float64Array): HeightPatch | null\n /**\n * The lowest and the highest `heightAt` can answer over the rectangle, exact bounds (the height between vertices is a blend of the four around it, so no\n * point is under the lowest or over the highest vertex of the cells the rectangle covers); null when the rectangle is not wholly inside the terrain, where the ground is the\n * host's `baseHeight` and no bound is known. Costs the vertices the rectangle covers, not a read per sample.\n */\n heightRange(minX: number, maxX: number, minZ: number, maxZ: number): { readonly low: number; readonly high: number } | null\n /** Height of vertex (column, row). */\n vertexHeight(column: number, row: number): number\n /** Material exposed at a vertex. */\n vertexMaterial(column: number, row: number): TerrainMaterial\n columnAt(x: number, z: number): TerrainColumn\n /** The rolling resistance (`TerrainMaterial.rolling`) of the material exposed at (x, z), as `columnAt` reads it, without building the column; undefined: the host's default. */\n rollingAt(x: number, z: number): number | undefined\n /** The rolling damping (`TerrainMaterial.rollingDamping`) of the material exposed at (x, z), read as `rollingAt`; undefined: the host's default. */\n rollingDampingAt(x: number, z: number): number | undefined\n contains(x: number, z: number): boolean\n /** First point of the ground along a ray, or null. */\n raycast(origin: readonly number[], direction: readonly number[], maxDistance: number): { point: [number, number, number]; distance: number; normal: [number, number, number] } | null\n /** A blow at (x, z). `energy` in joules, `direction` where it travels (it throws the pieces back along it). */\n strike(blow: TerrainBlow, spec: TerrainStrike): TerrainBlowResult\n /**\n * Opens a pit in the ground as it stands now (a shaft a blast threw its cover off): the same dig as an excavation of the layout, never less deep than the ground already is there, and\n * no ground loss. The layout is left alone, so the next `reset` closes it with the craters.\n */\n open(excavation: GroundExcavation): void\n /** A shovelful at (x, z): takes the earth down through what a shovel digs, stops at what it does not (concrete, rock), heaps it at `dump`. */\n dig(spec: TerrainDig): TerrainDigResult\n /** Earth thrown back from a heap into a hole: fills what was dug first, then heaps. Returns the cubic metres moved. */\n fill(spec: TerrainFill): number\n /** A flame over a disc for `seconds`. */\n burn(spec: { x: number; z: number; radius: number; temperature: number; seconds: number }): void\n /** Applies a world hit (`Hit` of the destruction contract); null when it does nothing to the ground. */\n applyHit(hit: Hit): TerrainBlowResult | null\n /** What stands still on the ground now. Where it stands over bare bars they sag under it, and past what they hold they give way; a slab over a void then opens. True when it opened. */\n bear(loads: readonly TerrainLoad[]): boolean\n /** How much ground is missing under the disc (x, z, radius), measured from the untouched surface. */\n voidUnder(x: number, z: number, radius: number): TerrainVoid\n /** Height a foot stands at: the ground less what it sinks in. */\n footAt(x: number, z: number): number\n /** What is left of the walking speed here, 0..1. */\n walkFactorAt(x: number, z: number): number\n /** The water standing here, or null. */\n waterAt(x: number, z: number): TerrainWaterHere | null\n /** A foot or a wheel on the ground: it leaves its print where the ground keeps one, a ripple in water. False where it leaves nothing. */\n press(spec: { x: number; z: number; radius: number; angle?: number; kind?: 'print' | 'rut' }): boolean\n /** Rings on the water at (x, z). */\n ripple(x: number, z: number, radius: number): void\n decals(): readonly TerrainDecal[]\n /** Goes up when the decals change. */\n readonly decalsVersion: number\n /** Follow the ground changing: `region` is the disc it changed in. What rests there has lost its support and must look again. Returns the unsubscribe function. */\n onDeform(listener: (region: TerrainRegion) => void): () => void\n /** Moves the pieces, the sliding ground and the fire. */\n update(dt: number): void\n /** Chunks waiting to be redrawn; every chunk at once means the floor was just laid anew (a layout, a reset). */\n readonly dirtyChunkCount: number\n /** Takes up to the budget's chunks that changed since the last call. */\n drainDirtyChunks(max?: number): TerrainChunk[]\n chunk(index: number): TerrainChunk\n marks(): readonly TerrainMark[]\n cracks(): readonly TerrainCrack[]\n /** Changes whenever a crack is added or grows, so a renderer redraws only then. */\n readonly cracksVersion: number\n debris(): readonly TerrainDebris[]\n /** Cells on fire now, as world points. */\n burningPoints(): readonly (readonly [number, number])[]\n /** Goes up when the marks change. */\n readonly marksVersion: number\n stats(): TerrainStats\n /** Back to the untouched ground. */\n reset(): void\n serialize(): TerrainSnapshot\n load(snapshot: TerrainSnapshot): void\n}\n\nexport interface TerrainSnapshot {\n readonly layout: GroundLayout\n readonly dug: readonly (readonly [number, number])[]\n readonly loose: readonly (readonly [number, number])[]\n readonly scorch: readonly (readonly [number, number])[]\n readonly barBend?: readonly (readonly [number, number])[]\n readonly marks: readonly TerrainMark[]\n readonly cracks?: readonly TerrainCrack[]\n readonly decals?: readonly TerrainDecal[]\n}\n","import type { Terrain } from './types'\n\nconst STRIDE = 0.72\nconst FOOT_LENGTH = 0.15\nconst FOOT_APART = 0.11\n\nexport interface Footprints {\n /** Call as the walker moves; it leaves a print each stride, left and right in turn. */\n update(x: number, z: number): void\n reset(): void\n}\n\n/** The trail of something walking: whoever moves on the ground reports where it is, and the ground keeps the prints it can keep. */\nexport function createFootprints(terrain: Terrain, options: { readonly stride?: number; readonly footLength?: number } = {}): Footprints {\n const stride = options.stride ?? STRIDE\n const footLength = options.footLength ?? FOOT_LENGTH\n let lastX: number | null = null\n let lastZ = 0\n let side = 1\n return {\n update(x, z) {\n if (lastX === null) {\n lastX = x\n lastZ = z\n return\n }\n const dx = x - lastX\n const dz = z - lastZ\n const walked = Math.hypot(dx, dz)\n if (walked < stride) return\n lastX = x\n lastZ = z\n // a jump of many strides is a teleport, not a walk\n if (walked > stride * 3) return\n const angle = Math.atan2(dx, dz)\n side = -side\n terrain.press({ x: x + (Math.cos(angle) * FOOT_APART * side), z: z - (Math.sin(angle) * FOOT_APART * side), radius: footLength, angle })\n },\n reset() {\n lastX = null\n },\n }\n}\n","const GRAVITY = 9.81\n/** Per second, the share of a body's speed water takes when it is all under: a body in water bobs once and stops, it does not bounce. */\nconst WATER_DRAG = 9\n/** The liquid does not throw a very light body out: past this many times its weight the push has nothing more to give. */\nconst MAX_LIFT_WEIGHTS = 1.6\n\nexport interface WaterLiftParams {\n /** Kilograms. */\n readonly mass: number\n /** Cubic metres of the whole body. */\n readonly volume: number\n /** Share of the body under the surface, 0..1. */\n readonly submerged: number\n /** Kilograms per cubic metre of the liquid. */\n readonly liquidDensity?: number\n readonly gravity?: number\n}\n\nexport interface WaterLift {\n /** Upward metres per second squared the liquid gives the body. */\n readonly acceleration: number\n /** Per second, the part of the speed the liquid takes. */\n readonly drag: number\n /** Lighter than the liquid it displaces. */\n readonly floats: boolean\n}\n\n/** Archimedes on a body in a liquid: what it displaces lifts it, so a light log floats and a concrete block goes to the bed. */\nexport function waterLift(params: WaterLiftParams): WaterLift {\n const density = params.liquidDensity ?? 1000\n const submerged = Math.max(0, Math.min(1, params.submerged))\n const mass = Math.max(1e-6, params.mass)\n const gravity = params.gravity ?? GRAVITY\n return {\n acceleration: Math.min(MAX_LIFT_WEIGHTS * gravity, (density * params.volume * submerged * gravity) / mass),\n drag: WATER_DRAG * submerged,\n floats: mass / Math.max(1e-9, params.volume) < density,\n }\n}\n","import type * as THREE_NS from 'three'\nimport { TERRAIN_PATTERNS } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\n/** Index of a pattern in the shader's branches. */\nexport const patternIndex = (pattern: string | undefined): number => Math.max(0, TERRAIN_PATTERNS.indexOf((pattern ?? 'plain') as (typeof TERRAIN_PATTERNS)[number]))\n\nconst SURFACE_GLSL = /* glsl */ `\nfloat tsHash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }\nfloat tsNoise(vec2 p) {\n vec2 i = floor(p); vec2 f = fract(p); f = f * f * (3.0 - 2.0 * f);\n return mix(mix(tsHash(i), tsHash(i + vec2(1.0, 0.0)), f.x), mix(tsHash(i + vec2(0.0, 1.0)), tsHash(i + vec2(1.0, 1.0)), f.x), f.y);\n}\nfloat tsFbm(vec2 p) { return tsNoise(p) * 0.55 + tsNoise(p * 2.3 + 7.1) * 0.3 + tsNoise(p * 5.1 + 3.3) * 0.15; }\n// a pixel wider than FAR_PIXEL_TO metres shows only the average of the pattern, PATTERN_MEAN of the base colour\nconst float FAR_PIXEL_FROM = 0.03;\nconst float FAR_PIXEL_TO = 0.12;\nconst float PATTERN_MEAN = 0.92;\n// metres one pixel covers on the ground here: a line or a grain finer than that cannot be drawn, only its average can\nfloat tsPixel = 0.0;\nfloat tsLine(float value, float period, float width) {\n float drawn = max(width, tsPixel);\n float d = abs(fract(value / period + 0.5) - 0.5) * period;\n return (1.0 - smoothstep(drawn * 0.6, drawn, d)) * (width / drawn);\n}\nvec3 terrainPattern(vec3 base, vec2 xz, float kind) {\n float k = floor(kind + 0.5);\n if (k < 0.5) return base * (0.86 + 0.28 * tsFbm(xz * 9.0));\n if (k < 1.5) {\n float blades = tsNoise(xz * vec2(70.0, 55.0)) * 0.6 + tsNoise(xz * 22.0) * 0.4;\n float patches = tsFbm(xz * 1.3);\n return base * (0.55 + 0.8 * blades) * mix(vec3(1.25, 1.05, 0.7), vec3(0.8, 1.1, 0.85), patches);\n }\n if (k < 2.5) return base * (0.6 + 0.75 * tsFbm(xz * 6.0)) * (0.82 + 0.36 * tsNoise(xz * 48.0));\n if (k < 3.5) return base * (0.88 + 0.12 * sin(xz.x * 22.0 + tsFbm(xz * 2.0) * 9.0)) * (0.92 + 0.16 * tsNoise(xz * 90.0));\n if (k < 4.5) { float grain = tsNoise(xz * 120.0); return base * (0.55 + 1.1 * grain * grain) * (0.85 + 0.3 * tsFbm(xz * 0.8)); }\n if (k < 5.5) {\n float joint = max(tsLine(xz.x, 3.0, 0.012), tsLine(xz.y, 3.0, 0.012));\n return base * (0.82 + 0.3 * tsFbm(xz * 3.5)) * (0.94 + 0.12 * tsNoise(xz * 130.0)) * (1.0 - 0.6 * joint);\n }\n if (k < 6.5) {\n vec2 cell = floor(xz / 0.6);\n float grout = max(tsLine(xz.x, 0.6, 0.006), tsLine(xz.y, 0.6, 0.006));\n return mix(base * (0.93 + 0.14 * tsHash(cell)) * (0.97 + 0.06 * tsFbm(xz * 7.0)), vec3(0.14, 0.13, 0.12), grout);\n }\n if (k < 7.5) {\n float row = floor(xz.y / 0.14);\n float along = xz.x + tsHash(vec2(row, 3.0)) * 2.4;\n float seam = max(tsLine(xz.y, 0.14, 0.004), tsLine(along, 2.4, 0.004));\n float grain = tsNoise(vec2(along * 3.0, xz.y * 70.0)) * 0.6 + tsNoise(vec2(along * 11.0, xz.y * 180.0)) * 0.4;\n return base * (0.72 + 0.56 * tsHash(vec2(row, floor(along / 2.4)))) * (0.75 + 0.5 * grain) * (1.0 - 0.75 * seam);\n }\n if (k < 8.5) {\n vec2 cell = floor(xz / 0.22);\n float seams = max(tsLine(xz.x, 0.22, 0.012), tsLine(xz.y, 0.22, 0.012));\n return base * (0.7 + 0.6 * tsHash(cell)) * (0.85 + 0.3 * tsFbm(xz * 16.0)) * (1.0 - 0.55 * seams);\n }\n if (k < 9.5) {\n float wet = smoothstep(0.42, 0.62, tsFbm(xz * 2.6));\n return base * (0.65 + 0.7 * tsFbm(xz * 11.0)) * mix(1.25, 0.55, wet);\n }\n if (k < 10.5) {\n vec2 grid = xz / 0.045;\n vec2 cell = floor(grid);\n vec2 inside = fract(grid) - 0.5 + (vec2(tsHash(cell), tsHash(cell + 9.0)) - 0.5) * 0.5;\n float stone = 1.0 - smoothstep(0.22, 0.5, length(inside));\n return base * (0.45 + 1.15 * tsHash(cell + 4.0)) * (0.35 + 0.85 * stone);\n }\n if (k < 11.5) {\n vec2 p = xz / 0.45 + (vec2(tsNoise(xz * 3.0), tsNoise(xz * 3.0 + 5.0)) - 0.5) * 0.7;\n vec2 cell = floor(p);\n float nearest = 8.0;\n float second = 8.0;\n for (int j = -1; j <= 1; j++) {\n for (int i = -1; i <= 1; i++) {\n vec2 other = cell + vec2(float(i), float(j));\n vec2 at = other + vec2(tsHash(other), tsHash(other + 3.0));\n float d = length(at - p);\n if (d < nearest) { second = nearest; nearest = d; } else if (d < second) second = d;\n }\n }\n float crack = 1.0 - smoothstep(0.0, 0.06, second - nearest);\n return base * (0.82 + 0.3 * tsFbm(xz * 9.0)) * (1.0 - 0.78 * crack);\n }\n if (k < 12.5) return min(base * (0.97 + 0.08 * tsFbm(xz * 1.8)) + 0.05 * tsNoise(xz * 140.0), vec3(1.0));\n if (k < 13.5) {\n float row = floor(xz.y / 0.2);\n float along = xz.x - mod(abs(row), 2.0) * 0.1;\n vec2 cell = vec2(floor(along / 0.3), row);\n float seam = max(tsLine(xz.y, 0.2, 0.014), tsLine(along, 0.3, 0.014));\n return base * (0.72 + 0.6 * tsHash(cell)) * (0.82 + 0.36 * tsFbm(xz * 22.0)) * (1.0 - 0.8 * seam);\n }\n if (k < 14.5) {\n float row = floor(xz.y / 0.2);\n float along = xz.x - mod(abs(row), 2.0) * 0.1;\n vec2 cell = vec2(floor(along / 0.2), row);\n float seam = max(tsLine(xz.y, 0.2, 0.008), tsLine(along, 0.2, 0.008));\n return base * (0.86 + 0.26 * tsHash(cell)) * (0.92 + 0.16 * tsNoise(xz * 70.0)) * (1.0 - 0.7 * seam);\n }\n // bare rock: weathered blotches, lichen-dark patches and a few long joints, no grid\n float blotch = tsFbm(xz * 0.9) * 0.6 + tsFbm(xz * 4.0 + 2.0) * 0.4;\n float joint = 1.0 - smoothstep(0.0, 0.035, abs(tsNoise(xz * vec2(0.7, 1.9)) - 0.5));\n float grain = tsNoise(xz * 95.0);\n return base * (0.62 + 0.75 * blotch) * (0.88 + 0.24 * grain) * (1.0 - 0.6 * joint);\n}\n/** The pattern where a pixel can hold it; far off, where a pixel covers more ground than the finest grain, its average, so that the grain does not sparkle as dots. */\nvec3 terrainSurface(vec3 base, vec2 xz, float kind) {\n tsPixel = max(length(dFdx(xz)), length(dFdy(xz)));\n vec3 near = terrainPattern(base, xz, kind);\n return mix(near, base * PATTERN_MEAN, smoothstep(FAR_PIXEL_FROM, FAR_PIXEL_TO, tsPixel));\n}\n`\n\n/** The ground's material: the colour of what is exposed comes per vertex, flat so that the edge between two materials stays sharp, its pattern (blades of grass, grout, planks) is drawn per pixel from the world position so that it never tiles or stretches. */\nexport function createSurfaceMaterial(THREE: ThreeLib): THREE_NS.MeshStandardMaterial {\n const material = new THREE.MeshStandardMaterial({ roughness: 0.95, metalness: 0 })\n material.onBeforeCompile = (shader) => {\n shader.vertexShader = shader.vertexShader\n .replace('#include <common>', '#include <common>\\nattribute float aPattern;\\nattribute vec3 aBase;\\nattribute vec2 aShade;\\nflat varying float vPattern;\\nflat varying vec3 vBase;\\nvarying vec2 vShade;\\nvarying vec2 vGroundXZ;')\n .replace('#include <begin_vertex>', '#include <begin_vertex>\\nvPattern = aPattern;\\nvBase = aBase;\\nvShade = aShade;\\nvGroundXZ = position.xz;')\n shader.fragmentShader = shader.fragmentShader\n .replace('#include <common>', `#include <common>\\nflat varying float vPattern;\\nflat varying vec3 vBase;\\nvarying vec2 vShade;\\nvarying vec2 vGroundXZ;\\n${SURFACE_GLSL}`)\n .replace('#include <color_fragment>', '#include <color_fragment>\\ndiffuseColor.rgb = mix(terrainSurface(vBase, vGroundXZ, vPattern), vec3(0.012, 0.011, 0.01), vShade.y) * vShade.x;')\n }\n material.customProgramCacheKey = () => 'game-terrain-surface'\n return material\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\nimport { patternIndex } from './surface-material'\n\ntype ThreeLib = typeof THREE_NS\n\n/** Metres over which the raw colour of a dug layer darkens: the bottom of a hole gets little light. */\nconst DEPTH_SHADE = 1.6\nconst MIN_DEPTH_LIGHT = 0.55\nconst LOOSE_VISIBLE = 0.004\n/** A skin thinner than this (turf, asphalt) is not what comes out of a hole: what is under it is. */\nconst THIN_SKIN = 0.1\nconst SKIRT_QUADS = 4\nconst BROKEN_DEPTH = 0.004\nconst BROKEN_TONE = 0.62\n\n/** What a vertex shows: the colour and pattern of what is exposed or heaped on it, sharp at the edge between materials, and its light and burn, which blend. */\nfunction vertexLook(terrain: Terrain, column: number, row: number, base: [number, number, number], shade: [number, number]): number {\n const index = row * terrain.stride + column\n let material = terrain.vertexMaterial(column, row)\n if (terrain.loose[index]! > LOOSE_VISIBLE) {\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const first = profile.strata[0]!\n material = terrain.material(first.thickness < THIN_SKIN && profile.strata[1] ? profile.strata[1].material : first.material)\n }\n // dug concrete shows its broken aggregate, not the troweled surface with its joints\n const broken = material.pattern === 'concrete' && terrain.dug[index]! > BROKEN_DEPTH\n const tone = broken ? BROKEN_TONE : 1\n base[0] = material.color[0] * tone\n base[1] = material.color[1] * tone\n base[2] = material.color[2] * tone\n shade[0] = Math.max(MIN_DEPTH_LIGHT, 1 - terrain.dug[index]! / DEPTH_SHADE)\n shade[1] = terrain.scorch[index]!\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const untouched = profile.surfacePattern !== undefined && terrain.dug[index]! <= BROKEN_DEPTH && terrain.loose[index]! <= LOOSE_VISIBLE\n return patternIndex(broken ? 'soil' : untouched ? profile.surfacePattern : material.pattern)\n}\n\n/** How many vertices `buildChunkGeometry` gives the chunk at this step: a geometry of that many can be refilled for it. */\nexport function chunkVertexCount(terrain: Terrain, chunk: TerrainChunk, step: number): number {\n const lastColumn = Math.min(terrain.columns, chunk.column + chunk.cells)\n const lastRow = Math.min(terrain.rows, chunk.row + chunk.cells)\n return (Math.ceil((lastColumn - chunk.column) / step) + 1) * (Math.ceil((lastRow - chunk.row) / step) + 1)\n}\n\nfunction attributeArray(geometry: THREE_NS.BufferGeometry, name: string): Float32Array {\n return geometry.getAttribute(name).array as Float32Array\n}\n\nfunction refreshAttributes(geometry: THREE_NS.BufferGeometry, names: readonly string[]): void {\n for (const name of names) geometry.getAttribute(name).needsUpdate = true\n geometry.boundingSphere = null\n geometry.boundingBox = null\n}\n\nconst LOOK_ATTRIBUTES = ['position', 'normal', 'aBase', 'aShade', 'aPattern'] as const\n\n/**\n * The chunk as a grid with one vertex every `step` cells; the normals come from the height field, so that neighbouring chunks meet without a seam. Given a `reuse` geometry\n * with the right vertex count (`chunkVertexCount`) it writes into that one's buffers instead of making new ones, so a crater costs no GPU allocation.\n */\nexport function buildChunkGeometry(THREE: ThreeLib, terrain: Terrain, chunk: TerrainChunk, step: number, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows } = terrain\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const across = Math.ceil((lastColumn - chunk.column) / step) + 1\n const down = Math.ceil((lastRow - chunk.row) / step) + 1\n const target = reuse && reuse.getAttribute('position').count === across * down ? reuse : undefined\n const positions = target ? attributeArray(target, 'position') : new Float32Array(across * down * 3)\n const normals = target ? attributeArray(target, 'normal') : new Float32Array(across * down * 3)\n const bases = target ? attributeArray(target, 'aBase') : new Float32Array(across * down * 3)\n const shades = target ? attributeArray(target, 'aShade') : new Float32Array(across * down * 2)\n const patterns = target ? attributeArray(target, 'aPattern') : new Float32Array(across * down)\n const base: [number, number, number] = [0, 0, 0]\n const shade: [number, number] = [1, 0]\n let at = 0\n for (let j = 0; j < down; j++) {\n const row = Math.min(lastRow, chunk.row + j * step)\n for (let i = 0; i < across; i++) {\n const column = Math.min(lastColumn, chunk.column + i * step)\n const height = terrain.vertexHeight(column, row)\n positions[at * 3] = x0 + column * cellSize\n positions[at * 3 + 1] = height\n positions[at * 3 + 2] = z0 + row * cellSize\n const left = terrain.vertexHeight(Math.max(0, column - 1), row)\n const right = terrain.vertexHeight(Math.min(columns, column + 1), row)\n const back = terrain.vertexHeight(column, Math.max(0, row - 1))\n const front = terrain.vertexHeight(column, Math.min(rows, row + 1))\n const nx = left - right\n const ny = 2 * cellSize\n const nz = back - front\n const length = Math.hypot(nx, ny, nz)\n normals[at * 3] = nx / length\n normals[at * 3 + 1] = ny / length\n normals[at * 3 + 2] = nz / length\n patterns[at] = vertexLook(terrain, column, row, base, shade)\n bases.set(base, at * 3)\n shades.set(shade, at * 2)\n at++\n }\n }\n if (target) {\n refreshAttributes(target, LOOK_ATTRIBUTES)\n return target\n }\n const indices = new Uint32Array((across - 1) * (down - 1) * 6)\n let cursor = 0\n for (let j = 0; j < down - 1; j++) {\n for (let i = 0; i < across - 1; i++) {\n const a = j * across + i\n const b = a + 1\n const c = a + across\n const d = c + 1\n indices[cursor++] = a\n indices[cursor++] = c\n indices[cursor++] = b\n // both triangles end on `b`: a flat attribute takes the last vertex, so the whole quad has one material and the edge between two is a straight line\n indices[cursor++] = c\n indices[cursor++] = d\n indices[cursor++] = b\n }\n }\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setAttribute('aBase', new THREE.BufferAttribute(bases, 3))\n geometry.setAttribute('aShade', new THREE.BufferAttribute(shades, 2))\n geometry.setAttribute('aPattern', new THREE.BufferAttribute(patterns, 1))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n return geometry\n}\n\n/**\n * Every chunk nothing touched, as one flat quad each in one geometry: the whole floor of an arena is a single draw call until someone digs it. Around them, out to `skirt` metres, the\n * ground goes on as the same surface: what is thrown past the edge lands on something, not on the sky.\n */\nexport function buildPristineGeometry(THREE: ThreeLib, terrain: Terrain, chunks: readonly TerrainChunk[], skirt: number, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows } = terrain\n const [, , x1, z1] = terrain.bounds\n const quads = chunks.length + SKIRT_QUADS\n // room for every chunk, so the same buffers serve however many are still untouched\n const capacity = terrain.chunksX * terrain.chunksZ + SKIRT_QUADS\n const target = reuse && reuse.getAttribute('position').count === capacity * 4 ? reuse : undefined\n const positions = target ? attributeArray(target, 'position') : new Float32Array(capacity * 12)\n const normals = target ? attributeArray(target, 'normal') : new Float32Array(capacity * 12)\n const bases = target ? attributeArray(target, 'aBase') : new Float32Array(capacity * 12)\n const shades = target ? attributeArray(target, 'aShade') : new Float32Array(capacity * 8)\n const patterns = target ? attributeArray(target, 'aPattern') : new Float32Array(capacity * 4)\n const indices = target ? (target.getIndex()!.array as Uint32Array) : new Uint32Array(capacity * 6)\n const base: [number, number, number] = [0, 0, 0]\n const shade: [number, number] = [1, 0]\n chunks.forEach((chunk, n) => {\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const corners = [[chunk.column, chunk.row], [lastColumn, chunk.row], [chunk.column, lastRow], [lastColumn, lastRow]] as const\n const pattern = vertexLook(terrain, chunk.column, chunk.row, base, shade)\n corners.forEach(([column, row], corner) => {\n const at = n * 4 + corner\n positions[at * 3] = x0 + column * cellSize\n positions[at * 3 + 1] = terrain.vertexHeight(column, row)\n positions[at * 3 + 2] = z0 + row * cellSize\n normals[at * 3 + 1] = 1\n bases.set(base, at * 3)\n shades.set(shade, at * 2)\n patterns[at] = pattern\n })\n const first = n * 4\n indices.set([first, first + 2, first + 1, first + 2, first + 3, first + 1], n * 6)\n })\n const surface = terrain.material(terrain.profileList.find((profile) => profile.id === terrain.layout().surface)?.strata[0]?.material ?? terrain.profileList[terrain.profileIndex[0]!]!.strata[0]!.material)\n const rects = [\n [x0 - skirt, z0 - skirt, x1 + skirt, z0],\n [x0 - skirt, z1, x1 + skirt, z1 + skirt],\n [x0 - skirt, z0, x0, z1],\n [x1, z0, x1 + skirt, z1],\n ] as const\n rects.forEach(([ax, az, bx, bz], r) => {\n const n = chunks.length + r\n const corners = [[ax, az], [bx, az], [ax, bz], [bx, bz]] as const\n corners.forEach(([x, z], corner) => {\n const at = n * 4 + corner\n positions[at * 3] = x\n positions[at * 3 + 1] = 0\n positions[at * 3 + 2] = z\n normals[at * 3 + 1] = 1\n bases.set(surface.color, at * 3)\n shades[at * 2] = 1\n patterns[at] = patternIndex(surface.pattern)\n })\n const first = n * 4\n indices.set([first, first + 2, first + 1, first + 2, first + 3, first + 1], n * 6)\n })\n const geometry = target ?? new THREE.BufferGeometry()\n if (target) {\n refreshAttributes(target, LOOK_ATTRIBUTES)\n target.getIndex()!.needsUpdate = true\n } else {\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setAttribute('aBase', new THREE.BufferAttribute(bases, 3))\n geometry.setAttribute('aShade', new THREE.BufferAttribute(shades, 2))\n geometry.setAttribute('aPattern', new THREE.BufferAttribute(patterns, 1))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n }\n geometry.setDrawRange(0, quads * 6)\n return geometry\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainDecal, TerrainDecalKind } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst TEXTURE_SIZE = 128\nconst DECAL_LIFT = 0.008\nconst RIPPLE_SECONDS = 1.6\nconst CRACK_ARMS = 7\nconst DARK_GROUND_PRINT_TONE = 0.1\n/** How dark each kind is against the colour of its material: a crack is a shadow, a splat is the material itself. */\nconst KIND_TONE: Record<TerrainDecalKind, number> = { crack: 0.16, print: 0.55, rut: 0.5, splat: 1, ripple: 3 }\n/** Width over length of what it covers: a print is a sole, a rut a band. */\nconst KIND_ASPECT: Record<TerrainDecalKind, number> = { crack: 1, print: 0.55, rut: 0.5, splat: 1, ripple: 1 }\n\ntype AlphaAt = (u: number, v: number) => number\n\nconst hash = (value: number): number => {\n const raw = Math.sin(value * 91.17) * 43758.5453\n return raw - Math.floor(raw)\n}\nconst ellipse = (u: number, v: number, cu: number, cv: number, ru: number, rv: number): number => Math.hypot((u - cu) / ru, (v - cv) / rv)\n\nfunction segmentDistance(px: number, py: number, ax: number, ay: number, bx: number, by: number): number {\n const dx = bx - ax\n const dy = by - ay\n const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))\n return Math.hypot(px - ax - dx * t, py - ay - dy * t)\n}\n\n/** Arms that leave the blow and fork on the way out. */\nfunction crackSegments(): number[][] {\n const segments: number[][] = []\n for (let arm = 0; arm < CRACK_ARMS; arm++) {\n let angle = (arm / CRACK_ARMS) * 6.283 + hash(arm) * 0.5\n let [x, y] = [0, 0]\n for (let step = 0; step < 5; step++) {\n const length = 0.075 + hash(arm * 7 + step) * 0.05\n const nextX = x + Math.cos(angle) * length\n const nextY = y + Math.sin(angle) * length\n segments.push([x, y, nextX, nextY])\n if (step > 0 && hash(arm * 13 + step) > 0.55) {\n const branch = angle + (hash(arm + step * 3) > 0.5 ? 0.7 : -0.7)\n segments.push([nextX, nextY, nextX + Math.cos(branch) * length * 0.8, nextY + Math.sin(branch) * length * 0.8])\n }\n x = nextX\n y = nextY\n angle += (hash(arm * 3 + step * 11) - 0.5) * 0.9\n }\n }\n return segments\n}\n\nconst SHAPES: Record<TerrainDecalKind, () => AlphaAt> = {\n crack() {\n const segments = crackSegments()\n return (u, v) => {\n let nearest = Infinity\n for (const [ax, ay, bx, by] of segments) nearest = Math.min(nearest, segmentDistance(u, v, ax!, ay!, bx!, by!))\n return 1 - Math.min(1, Math.max(0, (nearest - 0.004) / 0.008))\n }\n },\n print: () => (u, v) => {\n // v runs heel to toe\n const sole = ellipse(u, v, 0, 0.17, 0.42, 0.28)\n const heel = ellipse(u, v, 0, -0.27, 0.32, 0.18)\n const inside = Math.min(sole, heel)\n return inside > 1 ? 0 : 0.85 * (Math.sin(v * 70) > -0.3 ? 1 : 0.55)\n },\n rut: () => (u, v) => (Math.abs(u) > 0.46 || Math.abs(v) > 0.5 ? 0 : Math.sin(v * 44 + Math.abs(u) * 18) > -0.2 ? 0.8 : 0.45),\n splat() {\n return (u, v) => {\n const angle = Math.atan2(v, u)\n const edge = 0.3 + 0.08 * Math.sin(angle * 5) + 0.05 * Math.sin(angle * 13 + 1) + 0.04 * Math.sin(angle * 23 + 2)\n const body = 1 - Math.max(0, Math.min(1, (Math.hypot(u, v) - edge) / 0.03))\n return Math.max(body, ellipse(u, v, 0.38, 0.12, 0.05, 0.04) < 1 || ellipse(u, v, -0.22, -0.36, 0.06, 0.05) < 1 ? 1 : 0)\n }\n },\n ripple: () => (u, v) => {\n const r = Math.hypot(u, v)\n return r > 0.5 ? 0 : Math.max(0, Math.sin(r * 42)) * (1 - r * 2) ** 0.5\n },\n}\n\nfunction createAlphaTexture(THREE: ThreeLib, alphaAt: AlphaAt): THREE_NS.DataTexture {\n const size = TEXTURE_SIZE\n const data = new Uint8Array(size * size * 4)\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n const at = (y * size + x) * 4\n data[at] = data[at + 1] = data[at + 2] = 255\n data[at + 3] = Math.round(Math.max(0, Math.min(1, alphaAt((x + 0.5) / size - 0.5, (y + 0.5) / size - 0.5))) * 255)\n }\n }\n const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat)\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\nconst KINDS = Object.keys(SHAPES) as TerrainDecalKind[]\n\n/** The marks of no depth, one instanced mesh per kind so that each has its shape. */\nexport function createDecalLayers(THREE: ThreeLib, terrain: Terrain): { group: THREE_NS.Group; sync(): void; dispose(): void } {\n const group = new THREE.Group()\n group.name = 'terrain-decals'\n const geometry = new THREE.PlaneGeometry(1, 1)\n geometry.rotateX(-Math.PI / 2)\n const layers = KINDS.map((kind) => {\n const texture = createAlphaTexture(THREE, SHAPES[kind]())\n const material = new THREE.MeshStandardMaterial({ map: texture, transparent: true, depthWrite: false, roughness: kind === 'ripple' ? 0.2 : 1, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxDecals)\n mesh.name = `terrain-decal-${kind}`\n mesh.count = 0\n mesh.frustumCulled = false\n mesh.receiveShadow = true\n mesh.renderOrder = 2\n group.add(mesh)\n return { kind, mesh, material, texture }\n })\n const matrix = new THREE.Matrix4()\n const rotation = new THREE.Matrix4()\n const scale = new THREE.Matrix4()\n const colour = new THREE.Color()\n let seen = -1\n\n const place = (decal: TerrainDecal): boolean => {\n const water = terrain.waterAt(decal.x, decal.z)\n const grow = decal.kind === 'ripple' ? 0.5 + (decal.age / RIPPLE_SECONDS) * 1.5 : 1\n const size = decal.radius * 2 * grow\n rotation.makeRotationY(decal.angle)\n scale.makeScale(size * KIND_ASPECT[decal.kind], 1, size)\n matrix.multiplyMatrices(rotation, scale)\n matrix.setPosition(decal.x, (decal.kind === 'ripple' ? (water?.level ?? terrain.heightAt(decal.x, decal.z)) : terrain.heightAt(decal.x, decal.z)) + DECAL_LIFT, decal.z)\n return true\n }\n\n return {\n group,\n sync() {\n const decals = terrain.decals()\n const rippling = decals.some((decal) => decal.kind === 'ripple')\n if (seen === terrain.decalsVersion && !rippling) return\n seen = terrain.decalsVersion\n for (const layer of layers) {\n let count = 0\n for (const decal of decals) {\n if (decal.kind !== layer.kind || !place(decal)) continue\n layer.mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(decal.material).color\n const fade = decal.kind === 'ripple' ? Math.max(0, 1 - decal.age / RIPPLE_SECONDS) : 1\n // a print is a shadow: on a pale ground it greys, on a dark one it has to go nearly black to show\n const tone = (decal.kind === 'print' || decal.kind === 'rut') && r < 0.5 ? DARK_GROUND_PRINT_TONE : KIND_TONE[decal.kind]\n layer.mesh.setColorAt(count, colour.setRGB(Math.min(1, r * tone + (decal.kind === 'ripple' ? 0.5 : 0)) * fade, Math.min(1, g * tone + (decal.kind === 'ripple' ? 0.55 : 0)) * fade, Math.min(1, b * tone + (decal.kind === 'ripple' ? 0.6 : 0)) * fade))\n count++\n }\n layer.mesh.count = count\n layer.mesh.instanceMatrix.needsUpdate = true\n if (layer.mesh.instanceColor) layer.mesh.instanceColor.needsUpdate = true\n }\n },\n dispose() {\n geometry.dispose()\n for (const layer of layers) {\n layer.material.dispose()\n layer.texture.dispose()\n }\n group.removeFromParent()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport { crackLines } from '@adatechnology/game-terrain'\nimport type { Terrain, TerrainDebrisKind } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst MARK_LIFT = 0.006\nconst MARK_REACH = 1.5\nconst MARK_TEXTURE_SIZE = 64\nconst MARK_DARKEN = 0.85\n/** How a piece of each kind is stretched: a shard is a flake, a splinter a long sliver. */\nconst PIECE_SHAPE: Record<TerrainDebrisKind, readonly [number, number, number]> = { clods: [1, 0.85, 1], chips: [1, 0.6, 0.8], shards: [1.3, 0.2, 1], splinters: [0.3, 0.25, 2.4], dust: [1, 0.8, 1], blocks: [1, 0.42, 0.65] }\n\n/** A pock as an alpha disc: dark in the middle, a broken lighter ring where the surface chipped. */\nfunction createMarkTexture(THREE: ThreeLib): THREE_NS.DataTexture {\n const size = MARK_TEXTURE_SIZE\n const data = new Uint8Array(size * size * 4)\n for (let y = 0; y < size; y++) {\n for (let x = 0; x < size; x++) {\n const u = (x + 0.5) / size - 0.5\n const v = (y + 0.5) / size - 0.5\n const angle = Math.atan2(v, u)\n const lobes = 0.86 + 0.09 * Math.sin(angle * 5) + 0.05 * Math.sin(angle * 13 + 1)\n const q = Math.hypot(u, v) / (0.5 * lobes)\n const shade = q < 0.55 ? 0.42 + q * 0.5 : 0.7 + (q - 0.55) * 0.8\n const at = (y * size + x) * 4\n data[at] = data[at + 1] = data[at + 2] = Math.round(Math.min(1, shade) * 255)\n data[at + 3] = q < 0.8 ? 255 : q < 1 ? Math.round((1 - (q - 0.8) / 0.2) * 255) : 0\n }\n }\n const texture = new THREE.DataTexture(data, size, size, THREE.RGBAFormat)\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\nexport function createMarkLayer(THREE: ThreeLib, terrain: Terrain, drawDistance: number): { mesh: THREE_NS.InstancedMesh; sync(camera: { x: number; z: number }): void; dispose(): void } {\n const geometry = new THREE.PlaneGeometry(1, 1)\n geometry.rotateX(-Math.PI / 2)\n const texture = createMarkTexture(THREE)\n const material = new THREE.MeshStandardMaterial({ map: texture, transparent: true, depthWrite: false, roughness: 1, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxMarks)\n mesh.name = 'terrain-marks'\n mesh.count = 0\n mesh.frustumCulled = false\n mesh.receiveShadow = true\n mesh.renderOrder = 1\n // the colour attribute is part of the program key: made on the first mark it would link the program in the middle of the game\n mesh.setColorAt(0, new THREE.Color(1, 1, 1))\n const matrix = new THREE.Matrix4()\n const rotation = new THREE.Matrix4()\n const scale = new THREE.Matrix4()\n const colour = new THREE.Color()\n let seen = ''\n let cameraX = Infinity\n let cameraZ = Infinity\n return {\n mesh,\n sync(camera) {\n const marks = terrain.marks()\n let blows = 0\n for (const mark of marks) blows += mark.count\n const stamp = `${terrain.marksVersion}:${blows}`\n if (stamp === seen && Math.hypot(camera.x - cameraX, camera.z - cameraZ) < 5) return\n seen = stamp\n cameraX = camera.x\n cameraZ = camera.z\n let count = 0\n for (const mark of marks) {\n if (Math.hypot(mark.x - camera.x, mark.z - camera.z) > drawDistance) continue\n const size = mark.radius * 2 * MARK_REACH\n rotation.makeRotationY(mark.id * 2.399)\n scale.makeScale(size, 1, size)\n matrix.multiplyMatrices(rotation, scale)\n matrix.setPosition(mark.x, terrain.heightAt(mark.x, mark.z) + MARK_LIFT, mark.z)\n mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(mark.material).color\n colour.setRGB(r * MARK_DARKEN + 0.04, g * MARK_DARKEN + 0.04, b * MARK_DARKEN + 0.04)\n mesh.setColorAt(count, colour)\n count++\n }\n mesh.count = count\n mesh.instanceMatrix.needsUpdate = true\n if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n },\n dispose() {\n geometry.dispose()\n material.dispose()\n texture.dispose()\n mesh.removeFromParent()\n },\n }\n}\n\nexport function createDebrisLayer(THREE: ThreeLib, terrain: Terrain): { mesh: THREE_NS.InstancedMesh; sync(): void; dispose(): void } {\n const geometry = new THREE.IcosahedronGeometry(1, 0)\n const material = new THREE.MeshStandardMaterial({ roughness: 0.95, flatShading: true })\n const mesh = new THREE.InstancedMesh(geometry, material, terrain.budget.maxDebris)\n mesh.name = 'terrain-debris'\n mesh.count = 0\n mesh.castShadow = true\n mesh.frustumCulled = false\n mesh.setColorAt(0, new THREE.Color(1, 1, 1))\n const matrix = new THREE.Matrix4()\n const position = new THREE.Vector3()\n const scale = new THREE.Vector3()\n const quaternion = new THREE.Quaternion()\n const euler = new THREE.Euler()\n const colour = new THREE.Color()\n return {\n mesh,\n sync() {\n const pieces = terrain.debris()\n let count = 0\n for (const piece of pieces) {\n const [x, y, z] = piece.position\n // the turn follows the distance travelled, so that a piece at rest stays as it landed\n const travelled = x * 1.7 + z * 1.3 + y\n euler.set(piece.spin[0] * travelled * 0.2 + piece.id, piece.spin[1] * travelled * 0.2, piece.spin[2] * travelled * 0.2)\n const shape = PIECE_SHAPE[piece.kind]\n scale.set(shape[0] * piece.radius, shape[1] * piece.radius, shape[2] * piece.radius)\n matrix.compose(position.set(x, y, z), quaternion.setFromEuler(euler), scale)\n mesh.setMatrixAt(count, matrix)\n const [r, g, b] = terrain.material(piece.material).color\n const tone = 0.85 + ((piece.id * 37) % 30) / 100\n mesh.setColorAt(count, colour.setRGB(r * tone, g * tone, b * tone))\n count++\n }\n mesh.count = count\n mesh.instanceMatrix.needsUpdate = true\n if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true\n },\n dispose() {\n geometry.dispose()\n material.dispose()\n mesh.removeFromParent()\n },\n }\n}\n\nconst CRACK_LIFT = 0.004\n/** Quads all the cracks of the terrain can take at once; past it the farthest stars are left out. */\nconst MAX_CRACK_QUADS = 8192\n/** A crack shows the material's own colour, much darker: the shadow inside the line. */\nconst CRACK_SHADE = 0.22\n/** Under this luminance a surface is dark (asphalt) and its cracks are drawn lighter than it. */\nconst DARK_SURFACE = 0.1\nconst DUST_LIFT = 2\nconst DUST_GREY = 0.12\n\n/**\n * The cracks of rigid ground (`Terrain.cracks`) as thin ribbons on the surface, wide at the point and thin at the tips, in one draw call. The geometry is rebuilt only when a crack\n * is added or grows, or the ground under them moves, never per frame.\n */\nexport function createCrackLayer(THREE: ThreeLib, terrain: Terrain): { mesh: THREE_NS.Mesh; sync(): void; dispose(): void } {\n const positions = new Float32Array(MAX_CRACK_QUADS * 4 * 3)\n const colours = new Float32Array(MAX_CRACK_QUADS * 4 * 3)\n const indices = new Uint32Array(MAX_CRACK_QUADS * 6)\n for (let quad = 0; quad < MAX_CRACK_QUADS; quad++) {\n const first = quad * 4\n indices.set([first, first + 2, first + 1, first + 1, first + 2, first + 3], quad * 6)\n }\n const geometry = new THREE.BufferGeometry()\n const position = new THREE.BufferAttribute(positions, 3)\n const colour = new THREE.BufferAttribute(colours, 3)\n position.setUsage(THREE.DynamicDrawUsage)\n colour.setUsage(THREE.DynamicDrawUsage)\n geometry.setAttribute('position', position)\n geometry.setAttribute('color', colour)\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n geometry.setDrawRange(0, 0)\n const material = new THREE.MeshBasicMaterial({ vertexColors: true, transparent: true, opacity: 0.9, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 })\n const mesh = new THREE.Mesh(geometry, material)\n mesh.name = 'terrain-cracks'\n mesh.frustumCulled = false\n mesh.renderOrder = 2\n let seen = -1\n let groundMoved = false\n const stopListening = terrain.onDeform(() => {\n groundMoved = true\n })\n const lift = (x: number, z: number): number => terrain.heightAt(x, z) + CRACK_LIFT\n return {\n mesh,\n sync() {\n const cracks = terrain.cracks()\n if (seen === terrain.cracksVersion && !(groundMoved && cracks.length > 0)) return\n seen = terrain.cracksVersion\n groundMoved = false\n let quad = 0\n // the newest first: when the buffer is full, it is the old hairlines that go unseen\n for (let n = cracks.length - 1; n >= 0 && quad < MAX_CRACK_QUADS; n--) {\n const crack = cracks[n]!\n const tone = terrain.material(crack.material).color\n // on a dark surface (asphalt) a crack reads by the grey dust of the broken binder at its lips, not by a shadow darker than black\n const dark = tone[0] * 0.3 + tone[1] * 0.59 + tone[2] * 0.11 < DARK_SURFACE\n const k = dark ? DUST_LIFT : CRACK_SHADE\n const r = dark ? Math.min(1, tone[0] * k + DUST_GREY) : tone[0] * k\n const g = dark ? Math.min(1, tone[1] * k + DUST_GREY) : tone[1] * k\n const b = dark ? Math.min(1, tone[2] * k + DUST_GREY) : tone[2] * k\n for (const s of crackLines(crack)) {\n if (quad >= MAX_CRACK_QUADS) break\n if (!terrain.contains(s.x0, s.z0) || !terrain.contains(s.x1, s.z1)) continue\n const length = Math.hypot(s.x1 - s.x0, s.z1 - s.z0)\n if (length < 1e-5) continue\n // across the line, half the width each side\n const ax = -(s.z1 - s.z0) / length\n const az = (s.x1 - s.x0) / length\n const corners = [\n [s.x0 + ax * s.w0 * 0.5, s.z0 + az * s.w0 * 0.5],\n [s.x0 - ax * s.w0 * 0.5, s.z0 - az * s.w0 * 0.5],\n [s.x1 + ax * s.w1 * 0.5, s.z1 + az * s.w1 * 0.5],\n [s.x1 - ax * s.w1 * 0.5, s.z1 - az * s.w1 * 0.5],\n ] as const\n corners.forEach(([x, z], corner) => {\n const at = (quad * 4 + corner) * 3\n positions[at] = x\n positions[at + 1] = lift(x, z)\n positions[at + 2] = z\n colours[at] = r\n colours[at + 1] = g\n colours[at + 2] = b\n })\n quad++\n }\n }\n position.needsUpdate = true\n colour.needsUpdate = true\n geometry.setDrawRange(0, quad * 6)\n },\n dispose() {\n stopListening()\n geometry.dispose()\n material.dispose()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport type { GroundLayout } from '@adatechnology/game-contracts'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { Terrain } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst LABEL_LIFT = 0.025\nconst LABEL_HEIGHT = 0.42\nconst LABEL_MAX_WIDTH = 3\nconst WATER_COLOUR = 0x2c5a68\nconst WATER_OPACITY = 0.62\nconst WATER_ROUGHNESS = 0.08\nconst WAVE_SIZE = 64\nconst WAVE_TILES_PER_METRE = 0.6\nconst WAVE_SPEED = 0.012\n\nfunction buildSign(THREE: ThreeLib, text: string): THREE_NS.Mesh | null {\n if (typeof document === 'undefined') return null\n const canvas = document.createElement('canvas')\n canvas.width = 512\n canvas.height = 72\n const context = canvas.getContext('2d')\n if (!context) return null\n context.fillStyle = 'rgba(0,0,0,0.65)'\n context.fillRect(0, 0, 512, 72)\n context.fillStyle = '#fff'\n context.font = 'bold 46px sans-serif'\n context.textAlign = 'center'\n context.textBaseline = 'middle'\n context.fillText(text, 256, 38)\n const mesh = new THREE.Mesh(new THREE.PlaneGeometry(LABEL_MAX_WIDTH, LABEL_HEIGHT), new THREE.MeshBasicMaterial({ map: new THREE.CanvasTexture(canvas), transparent: true, depthWrite: false }))\n mesh.rotation.x = -Math.PI / 2\n return mesh\n}\n\n/** A gentle bump map as normals, tiled over the water: it moves in `sync`. */\nfunction createWaveTexture(THREE: ThreeLib): THREE_NS.DataTexture {\n const data = new Uint8Array(WAVE_SIZE * WAVE_SIZE * 4)\n const tau = Math.PI * 2 / WAVE_SIZE\n for (let y = 0; y < WAVE_SIZE; y++) {\n for (let x = 0; x < WAVE_SIZE; x++) {\n const dx = Math.cos(x * tau * 2 + y * tau) * 0.5 + Math.cos(x * tau * 5 - y * tau * 2) * 0.3\n const dy = Math.cos(y * tau * 3 + x * tau) * 0.5 + Math.cos(y * tau * 4 - x * tau * 3) * 0.3\n const at = (y * WAVE_SIZE + x) * 4\n data[at] = Math.round((dx * 0.25 + 0.5) * 255)\n data[at + 1] = Math.round((dy * 0.25 + 0.5) * 255)\n data[at + 2] = 255\n data[at + 3] = 255\n }\n }\n const texture = new THREE.DataTexture(data, WAVE_SIZE, WAVE_SIZE, THREE.RGBAFormat)\n texture.wrapS = texture.wrapT = THREE.RepeatWrapping\n texture.magFilter = THREE.LinearFilter\n texture.minFilter = THREE.LinearFilter\n texture.needsUpdate = true\n return texture\n}\n\n/** What a layout lays over the ground: the water of the zones that have it and the sign of the zones that say what they are. Follows the layout as it changes. */\nexport function createZoneLayer(THREE: ThreeLib, terrain: Terrain): { group: THREE_NS.Group; sync(): void; dispose(): void } {\n const group = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'ground' })\n group.name = 'terrain-zones'\n const waves = createWaveTexture(THREE)\n // where the water meets the bed at its edge the two lie on one plane: the offset draws the water in front instead of flickering\n const water = new THREE.MeshStandardMaterial({ color: WATER_COLOUR, transparent: true, opacity: WATER_OPACITY, roughness: WATER_ROUGHNESS, metalness: 0.1, normalMap: waves, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 })\n let drawnFor: GroundLayout | null = null\n const throwAway = (): void => {\n for (const child of [...group.children]) {\n group.remove(child)\n const mesh = child as THREE_NS.Mesh\n mesh.geometry.dispose()\n if (mesh.material !== water) {\n const material = mesh.material as THREE_NS.MeshBasicMaterial\n material.map?.dispose()\n material.dispose()\n }\n }\n }\n const isWater = (surface: string): boolean => terrain.profileList.some((profile) => profile.id === surface && profile.water)\n const draw = (layout: GroundLayout): void => {\n throwAway()\n const [x0, z0, x1, z1] = terrain.bounds\n const rects: (readonly [number, number, number, number])[] = isWater(layout.surface) ? [[x0, z0, x1, z1]] : []\n for (const zone of layout.zones ?? []) {\n if (isWater(zone.surface)) rects.push(zone.rect)\n if (!zone.label) continue\n const sign = buildSign(THREE, zone.label)\n if (!sign) continue\n const [ax, , bx, bz] = zone.rect\n sign.scale.x = Math.min(1, (bx - ax - 0.1) / LABEL_MAX_WIDTH)\n sign.position.set((ax + bx) / 2, LABEL_LIFT, bz - LABEL_HEIGHT / 2 - 0.03)\n sign.renderOrder = 3\n group.add(sign)\n }\n for (const [ax, az, bx, bz] of rects) {\n const plane = new THREE.PlaneGeometry(bx - ax, bz - az)\n plane.rotateX(-Math.PI / 2)\n const uv = plane.getAttribute('uv') as THREE_NS.BufferAttribute\n for (let i = 0; i < uv.count; i++) uv.setXY(i, uv.getX(i) * (bx - ax) * WAVE_TILES_PER_METRE, uv.getY(i) * (bz - az) * WAVE_TILES_PER_METRE)\n const mesh = new THREE.Mesh(plane, water)\n mesh.name = 'terrain-water'\n mesh.position.set((ax + bx) / 2, terrain.waterAt((ax + bx) / 2, (az + bz) / 2)?.level ?? 0, (az + bz) / 2)\n mesh.renderOrder = 1\n group.add(mesh)\n }\n }\n return {\n group,\n sync() {\n const layout = terrain.layout()\n if (layout !== drawnFor) {\n drawnFor = layout\n draw(layout)\n }\n const shift = (Date.now() % 1_000_000) * 0.001 * WAVE_SPEED\n waves.offset.set(shift, shift * 0.7)\n },\n dispose() {\n throwAway()\n water.dispose()\n waves.dispose()\n group.removeFromParent()\n },\n }\n}\n","import type * as THREE_NS from 'three'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\n\ntype ThreeLib = typeof THREE_NS\n\nconst BAR_RADIUS = 0.006\nconst EXPOSED_MARGIN = 0.002\n/** Metres a bar hangs just before it gives way. */\nconst MAX_SAG = 0.07\n\n/** Bars a fresh geometry has room for at least, so that a chunk whose bars grow a little keeps its buffers. */\nconst MIN_BAR_CAPACITY = 32\n\nfunction barCapacity(count: number): number {\n let capacity = MIN_BAR_CAPACITY\n while (capacity < count) capacity *= 2\n return capacity\n}\n\n/**\n * The bars of a reinforced layer where the digging passed their cover: a mesh of the chunk, or null when none is showing. A `reuse` geometry with room for them is written into\n * (and only its draw range changes) instead of making new buffers.\n */\nexport function buildRebarGeometry(THREE: ThreeLib, terrain: Terrain, chunk: TerrainChunk, reuse?: THREE_NS.BufferGeometry): THREE_NS.BufferGeometry | null {\n const [x0, z0] = terrain.bounds\n const { cellSize, columns, rows, stride } = terrain\n const lastColumn = Math.min(columns, chunk.column + chunk.cells)\n const lastRow = Math.min(rows, chunk.row + chunk.cells)\n const boxes: number[] = []\n const coverOf = (index: number): { depth: number; spacing: number } | null => {\n let top = 0\n for (const stratum of terrain.profileList[terrain.profileIndex[index]!]!.strata) {\n if (stratum.reinforcement) return { depth: top + stratum.reinforcement.cover, spacing: stratum.reinforcement.spacing }\n top += stratum.thickness\n }\n return null\n }\n // past the bottom of its strata the slab has opened: the bars are gone there and stay bent around the hole\n const showing = (index: number, depth: number): boolean => {\n const profile = terrain.profileList[terrain.profileIndex[index]!]!\n const limit = profile.strata.reduce((sum, stratum) => sum + stratum.thickness, 0)\n return terrain.dug[index]! > depth + EXPOSED_MARGIN && terrain.dug[index]! <= limit + EXPOSED_MARGIN\n }\n const onBar = (coordinate: number, spacing: number): boolean => Math.floor(coordinate / spacing) !== Math.floor((coordinate + cellSize) / spacing)\n const addBox = (ax: number, az: number, bx: number, bz: number, y: number): void => {\n boxes.push(Math.min(ax, bx) - BAR_RADIUS, y - BAR_RADIUS, Math.min(az, bz) - BAR_RADIUS, Math.max(ax, bx) + BAR_RADIUS, y + BAR_RADIUS, Math.max(az, bz) + BAR_RADIUS)\n }\n for (let row = chunk.row; row <= lastRow; row++) {\n for (let column = chunk.column; column <= lastColumn; column++) {\n const index = row * stride + column\n const cover = coverOf(index)\n if (!cover || !showing(index, cover.depth)) continue\n const x = x0 + column * cellSize\n const z = z0 + row * cellSize\n const y = -cover.depth - BAR_RADIUS - Math.min(1, terrain.barBend[index]!) * MAX_SAG\n if (onBar(z, cover.spacing) && column < lastColumn && showing(index + 1, cover.depth)) addBox(x, z, x + cellSize, z, y)\n if (onBar(x, cover.spacing) && row < lastRow && showing(index + stride, cover.depth)) addBox(x, z, x, z + cellSize, y)\n }\n }\n if (boxes.length === 0) return null\n const count = boxes.length / 6\n const target = reuse && reuse.getAttribute('position').count >= count * 24 ? reuse : undefined\n const capacity = target ? target.getAttribute('position').count / 24 : barCapacity(count)\n const positions = target ? (target.getAttribute('position').array as Float32Array) : new Float32Array(capacity * 24 * 3)\n const normals = target ? (target.getAttribute('normal').array as Float32Array) : new Float32Array(capacity * 24 * 3)\n const indices = target ? (target.getIndex()!.array as Uint32Array) : new Uint32Array(capacity * 36)\n const FACES: readonly (readonly [readonly number[], readonly [number, number, number]])[] = [\n [[0, 4, 2, 0, 4, 5, 3, 4, 5, 3, 4, 2], [0, 1, 0]],\n [[0, 1, 5, 0, 1, 2, 3, 1, 2, 3, 1, 5], [0, -1, 0]],\n [[0, 1, 5, 3, 1, 5, 3, 4, 5, 0, 4, 5], [0, 0, 1]],\n [[3, 1, 2, 0, 1, 2, 0, 4, 2, 3, 4, 2], [0, 0, -1]],\n [[3, 1, 5, 3, 1, 2, 3, 4, 2, 3, 4, 5], [1, 0, 0]],\n [[0, 1, 2, 0, 1, 5, 0, 4, 5, 0, 4, 2], [-1, 0, 0]],\n ]\n let vertex = 0\n let cursor = 0\n for (let n = 0; n < count; n++) {\n const box = boxes.slice(n * 6, n * 6 + 6)\n for (const [corners, normal] of FACES) {\n const first = vertex\n for (let c = 0; c < 4; c++) {\n positions[vertex * 3] = box[corners[c * 3]!]!\n positions[vertex * 3 + 1] = box[corners[c * 3 + 1]!]!\n positions[vertex * 3 + 2] = box[corners[c * 3 + 2]!]!\n normals.set(normal, vertex * 3)\n vertex++\n }\n indices.set([first, first + 1, first + 2, first, first + 2, first + 3], cursor)\n cursor += 6\n }\n }\n if (target) {\n target.getAttribute('position').needsUpdate = true\n target.getAttribute('normal').needsUpdate = true\n target.getIndex()!.needsUpdate = true\n target.boundingSphere = null\n target.boundingBox = null\n target.setDrawRange(0, count * 36)\n return target\n }\n const geometry = new THREE.BufferGeometry()\n geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3))\n geometry.setAttribute('normal', new THREE.BufferAttribute(normals, 3))\n geometry.setIndex(new THREE.BufferAttribute(indices, 1))\n geometry.setDrawRange(0, count * 36)\n return geometry\n}\n","import type * as THREE_NS from 'three'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { Terrain, TerrainChunk } from '@adatechnology/game-terrain'\nimport { buildChunkGeometry, buildPristineGeometry, chunkVertexCount } from './chunk-geometry'\nimport { createDecalLayers } from './decal-layers'\nimport { createCrackLayer, createDebrisLayer, createMarkLayer } from './layers'\nimport { createZoneLayer } from './zone-layer'\nimport { buildRebarGeometry } from './rebar'\nimport { createSurfaceMaterial } from './surface-material'\n\ntype ThreeLib = typeof THREE_NS\n\nexport interface TerrainRendererOptions {\n readonly terrain: Terrain\n /** Beyond this distance in metres a dug chunk draws half its vertices (default 30), twice this a quarter. */\n readonly lodDistance?: number\n /** Marks farther than this in metres are not drawn (default 45). */\n readonly markDistance?: number\n /** Metres the untouched ground goes on beyond the terrain, so that it has no edge in sight (default 300). */\n readonly skirt?: number\n}\n\nexport interface TerrainRenderer {\n readonly group: THREE_NS.Group\n /** Call every frame with the camera's position. Redraws at most the terrain's budget of chunks. */\n sync(camera: { readonly x: number; readonly y: number; readonly z: number }): void\n /** What is on the screen, for a bench. */\n stats(): { readonly chunkMeshes: number; readonly pristineChunks: number; readonly marksDrawn: number; readonly debrisDrawn: number; readonly crackQuads: number }\n dispose(): void\n}\n\nconst DEFAULT_LOD_DISTANCE = 30\nconst DEFAULT_MARK_DISTANCE = 45\nconst DEFAULT_SKIRT = 300\nconst LOD_CHECK_METRES = 4\nconst REBAR_COLOUR = 0x4a3528\n/** Geometries of chunks that went back to pristine or changed detail, kept to be refilled for the next dug chunk. */\nconst MAX_SPARE_GEOMETRIES = 24\n\ninterface DrawnChunk {\n mesh: THREE_NS.Mesh\n rebar: THREE_NS.Mesh | null\n step: number\n}\n\n/** The ground of a `Terrain`: chunks nobody touched share one flat geometry, a dug one gets a mesh of its own that gets simpler far away. */\nexport function createTerrainRenderer(THREE: ThreeLib, options: TerrainRendererOptions): TerrainRenderer {\n const { terrain } = options\n const lodDistance = options.lodDistance ?? DEFAULT_LOD_DISTANCE\n const skirt = options.skirt ?? DEFAULT_SKIRT\n const group = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'ground' })\n group.name = 'floor'\n const surface = createSurfaceMaterial(THREE)\n const rebarMaterial = new THREE.MeshStandardMaterial({ color: REBAR_COLOUR, roughness: 0.75, metalness: 0.35 })\n const pristineMesh = new THREE.Mesh(new THREE.BufferGeometry(), surface)\n pristineMesh.receiveShadow = true\n pristineMesh.name = 'terrain-pristine'\n pristineMesh.frustumCulled = false\n group.add(pristineMesh)\n const drawn = new Map<number, DrawnChunk>()\n const marks = createMarkLayer(THREE, terrain, options.markDistance ?? DEFAULT_MARK_DISTANCE)\n const debris = createDebrisLayer(THREE, terrain)\n const cracks = createCrackLayer(THREE, terrain)\n const decals = createDecalLayers(THREE, terrain)\n const zones = createZoneLayer(THREE, terrain)\n group.add(marks.mesh, cracks.mesh, debris.mesh, decals.group, zones.group)\n let pristineStale = true\n let pristineBuilt = false\n let pristineCount = 0\n let lodX = Infinity\n let lodZ = Infinity\n let firstSync = true\n\n const distanceTo = (chunk: TerrainChunk, camera: { x: number; z: number }): number => {\n const half = (chunk.cells * terrain.cellSize) / 2\n const centreX = terrain.bounds[0] + chunk.column * terrain.cellSize + half\n const centreZ = terrain.bounds[1] + chunk.row * terrain.cellSize + half\n return Math.hypot(centreX - camera.x, centreZ - camera.z)\n }\n const stepFor = (distance: number): number => (distance > lodDistance * 2 ? 4 : distance > lodDistance ? 2 : 1)\n\n const spareGeometries: THREE_NS.BufferGeometry[] = []\n\n function keepSpare(geometry: THREE_NS.BufferGeometry): void {\n if (spareGeometries.length < MAX_SPARE_GEOMETRIES) spareGeometries.push(geometry)\n else geometry.dispose()\n }\n\n function takeSpare(chunk: TerrainChunk, step: number): THREE_NS.BufferGeometry | undefined {\n const count = chunkVertexCount(terrain, chunk, step)\n const found = spareGeometries.findIndex((geometry) => geometry.getAttribute('position').count === count)\n return found < 0 ? undefined : spareGeometries.splice(found, 1)[0]\n }\n\n function drop(index: number): void {\n const entry = drawn.get(index)\n if (!entry) return\n group.remove(entry.mesh)\n keepSpare(entry.mesh.geometry)\n if (entry.rebar) {\n group.remove(entry.rebar)\n entry.rebar.geometry.dispose()\n }\n drawn.delete(index)\n }\n\n function drawRebar(chunk: TerrainChunk, entry: DrawnChunk): void {\n const bars = buildRebarGeometry(THREE, terrain, chunk, entry.rebar?.geometry)\n if (!bars) {\n if (entry.rebar) entry.rebar.visible = false\n return\n }\n if (entry.rebar && entry.rebar.geometry === bars) {\n entry.rebar.visible = true\n return\n }\n if (entry.rebar) {\n group.remove(entry.rebar)\n entry.rebar.geometry.dispose()\n }\n entry.rebar = new THREE.Mesh(bars, rebarMaterial)\n entry.rebar.castShadow = true\n group.add(entry.rebar)\n }\n\n function draw(chunk: TerrainChunk, camera: { x: number; z: number }): void {\n const step = stepFor(distanceTo(chunk, camera))\n let entry = drawn.get(chunk.index)\n if (!entry) {\n const mesh = new THREE.Mesh(buildChunkGeometry(THREE, terrain, chunk, step, takeSpare(chunk, step)), surface)\n mesh.receiveShadow = true\n group.add(mesh)\n entry = { mesh, rebar: null, step }\n drawn.set(chunk.index, entry)\n } else {\n const previous = entry.mesh.geometry\n const sameDetail = previous.getAttribute('position').count === chunkVertexCount(terrain, chunk, step)\n entry.mesh.geometry = buildChunkGeometry(THREE, terrain, chunk, step, sameDetail ? previous : takeSpare(chunk, step))\n if (entry.mesh.geometry !== previous) keepSpare(previous)\n entry.step = step\n }\n drawRebar(chunk, entry)\n }\n\n function rebuildPristine(): void {\n const chunks: TerrainChunk[] = []\n for (let index = 0; index < terrain.chunksX * terrain.chunksZ; index++) {\n const chunk = terrain.chunk(index)\n if (chunk.pristine) chunks.push(chunk)\n }\n if (!pristineBuilt) pristineMesh.geometry.dispose()\n pristineMesh.geometry = buildPristineGeometry(THREE, terrain, chunks, skirt, pristineBuilt ? pristineMesh.geometry : undefined)\n pristineBuilt = true\n pristineCount = chunks.length\n pristineStale = false\n }\n\n return {\n group,\n sync(camera) {\n // the first picture and a floor just laid (a new layout, a reset) have every chunk dirty: pristine ones need no work of their own, the rest are drawn at once, since the\n // pristine floor is rebuilt without them in the same frame and a chunk left for later would be a hole to the sky until its turn came\n const laidAnew = terrain.dirtyChunkCount >= terrain.chunksX * terrain.chunksZ\n const limit = firstSync || laidAnew ? Infinity : undefined\n firstSync = false\n for (const chunk of terrain.drainDirtyChunks(limit)) {\n if (chunk.pristine) {\n if (drawn.has(chunk.index)) drop(chunk.index)\n pristineStale = true\n } else {\n if (!drawn.has(chunk.index)) pristineStale = true\n draw(chunk, camera)\n }\n }\n if (pristineStale) rebuildPristine()\n if (Math.hypot(camera.x - lodX, camera.z - lodZ) > LOD_CHECK_METRES) {\n lodX = camera.x\n lodZ = camera.z\n for (const [index, entry] of drawn) {\n const chunk = terrain.chunk(index)\n if (stepFor(distanceTo(chunk, camera)) !== entry.step) draw(chunk, camera)\n }\n }\n marks.sync(camera)\n cracks.sync()\n debris.sync()\n decals.sync()\n zones.sync()\n },\n stats: () => ({ chunkMeshes: drawn.size, pristineChunks: pristineCount, marksDrawn: marks.mesh.count, debrisDrawn: debris.mesh.count, crackQuads: cracks.mesh.geometry.drawRange.count / 6 }),\n dispose() {\n for (const index of [...drawn.keys()]) drop(index)\n for (const geometry of spareGeometries) geometry.dispose()\n pristineMesh.geometry.dispose()\n surface.dispose()\n rebarMaterial.dispose()\n marks.dispose()\n cracks.dispose()\n debris.dispose()\n decals.dispose()\n zones.dispose()\n group.removeFromParent()\n },\n }\n}\n","import type { TERRAIN_STRIPS } from './test-module'\n\n/** The ground profiles of the catalogue (`TERRAIN_PROFILES` of game-terrain) by name, for a HUD that says what the floor under the aim is. */\nconst PROFILE_NAMES: Record<string, Record<string, string>> = {\n en: { lawn: 'Lawn', dirt: 'Dirt', sand: 'Sand', road: 'Asphalt road', concrete_slab: 'Concrete slab', sidewalk: 'Sidewalk', suspended_slab: 'Slab over a void', tile_floor: 'Tile floor', wood_floor: 'Wood floor', stone_paving: 'Stone paving', mud: 'Mud', gravel_bed: 'Gravel', dry_clay: 'Dry clay', snow: 'Snow', cobblestone: 'Cobblestones', paver_floor: 'Concrete pavers', shallow_water: 'Shallow water', bedrock: 'Bare rock', pond: 'Pond' },\n 'pt-BR': { lawn: 'Grama', dirt: 'Terra', sand: 'Areia', road: 'Asfalto', concrete_slab: 'Laje de concreto', sidewalk: 'Calçada', suspended_slab: 'Laje sobre vão', tile_floor: 'Piso cerâmico', wood_floor: 'Assoalho', stone_paving: 'Calçamento de pedra', mud: 'Lama', gravel_bed: 'Cascalho', dry_clay: 'Barro seco', snow: 'Neve', cobblestone: 'Paralelepípedo', paver_floor: 'Bloquete', shallow_water: 'Água rasa', bedrock: 'Rocha', pond: 'Lago' },\n}\n\n/** The name of a ground profile in the locale (`en` when the locale is unknown); a profile a game added without a name answers its id. */\nexport function terrainProfileName(profileId: string, localeId: string): string {\n return (PROFILE_NAMES[localeId] ?? PROFILE_NAMES.en!)[profileId] ?? profileId\n}\n\ninterface TerrainText {\n readonly name: string\n readonly group: string\n readonly weight: string\n readonly surfaces: Record<(typeof TERRAIN_STRIPS)[number], string>\n}\n\nconst LOCALES: Record<string, TerrainText> = {\n en: {\n name: 'Terrain',\n group: 'Terrain',\n weight: 'Concrete block (60 kg)',\n surfaces: { dirt: 'Dirt', lawn: 'Lawn', sand: 'Sand', road: 'Asphalt', concrete_slab: 'Concrete slab', suspended_slab: 'Slab over a void', wood_floor: 'Wood floor', tile_floor: 'Tile', stone_paving: 'Stone paving', mud: 'Mud', gravel_bed: 'Gravel', dry_clay: 'Dry clay', snow: 'Snow', cobblestone: 'Cobblestones', paver_floor: 'Concrete pavers', shallow_water: 'Shallow water', bedrock: 'Bare rock', pond: 'Pond' },\n },\n 'pt-BR': {\n name: 'Terreno',\n group: 'Terreno',\n weight: 'Bloco de concreto (60 kg)',\n surfaces: { dirt: 'Terra', lawn: 'Grama', sand: 'Areia', road: 'Asfalto', concrete_slab: 'Laje de concreto', suspended_slab: 'Laje sobre vão', wood_floor: 'Assoalho', tile_floor: 'Cerâmica', stone_paving: 'Pedra', mud: 'Lama', gravel_bed: 'Cascalho', dry_clay: 'Barro seco', snow: 'Neve', cobblestone: 'Paralelepípedo', paver_floor: 'Bloquete', shallow_water: 'Água rasa', bedrock: 'Rocha', pond: 'Lago' },\n },\n}\n\nexport const locale = (id: string): TerrainText => LOCALES[id] ?? LOCALES.en!\n","import type * as THREE_NS from 'three'\nimport { markKitOrigin } from '@adatechnology/game-contracts'\nimport type { DestructibleSpec, GroundLayout, ModuleArea, TestableItem, TestableModule } from '@adatechnology/game-contracts'\nimport { locale as localeTable } from './locale'\n\ntype ThreeLib = typeof THREE_NS\n\n/** The lots of the area, side by side in two rows, one of each ground: the soft and wet ones in the back row, rock and the built ones in front. */\nexport const TERRAIN_STRIPS = ['lawn', 'dirt', 'sand', 'mud', 'dry_clay', 'gravel_bed', 'snow', 'shallow_water', 'pond', 'bedrock', 'road', 'cobblestone', 'paver_floor', 'stone_paving', 'concrete_slab', 'suspended_slab', 'tile_floor', 'wood_floor'] as const\nconst LOT_WIDTH = 3\nconst LOT_DEPTH = 3.8\nconst LOTS_PER_ROW = 9\n/** Between the target wall and the table of the room: what the player sees on arriving, and clear of the furniture. */\nconst LOTS_Z1 = -1.4\nconst lotRect = (index: number): readonly [number, number, number, number] => {\n const row = Math.floor(index / LOTS_PER_ROW)\n const x0 = ((index % LOTS_PER_ROW) - LOTS_PER_ROW / 2) * LOT_WIDTH\n // the first row is the far one\n const z1 = LOTS_Z1 - (1 - row) * LOT_DEPTH\n return [x0, z1 - LOT_DEPTH, x0 + LOT_WIDTH, z1]\n}\n\n/** A lot of each ground, with its sign. A host lays it to give a room every ground to try (`createTestRoom`'s `ground`). */\nexport function terrainLotsGround(locale = 'en'): GroundLayout {\n const text = localeTable(locale)\n return { surface: 'concrete_slab', zones: TERRAIN_STRIPS.map((surface, index) => ({ rect: lotRect(index), surface, label: text.surfaces[surface] })) }\n}\nexport const TERRAIN_AREA_GROUND: GroundLayout = terrainLotsGround()\n\nconst WEIGHT_SIDE = 0.32\nconst WEIGHT_HEIGHT = 4\n\nfunction weightSpec(): DestructibleSpec {\n return { name: 'Weight', parts: [{ id: 'block', material: 'concrete', shape: { kind: 'box', size: [WEIGHT_SIDE, WEIGHT_SIDE, WEIGHT_SIDE] }, position: [0, WEIGHT_SIDE / 2, 0] }], joints: [] }\n}\n\nfunction buildWeight(THREE: ThreeLib): THREE_NS.Object3D {\n const mesh = new THREE.Mesh(new THREE.BoxGeometry(WEIGHT_SIDE, WEIGHT_SIDE, WEIGHT_SIDE), new THREE.MeshStandardMaterial({ color: 0xb4b4ae, roughness: 0.9 }))\n mesh.name = 'block'\n mesh.position.y = WEIGHT_SIDE / 2\n mesh.castShadow = true\n const root = markKitOrigin(new THREE.Group(), { owner: 'game-terrain-three', kind: 'item' })\n root.add(mesh)\n return root\n}\n\n/**\n * The ground bench: a lot of each surface side by side to shoot, blow up, burn and drop weights on. Opening the area lays the lots with their signs (`ground`) and drops a concrete block\n * on each from four metres.\n */\nexport function createTerrainTestModule(options: { readonly locale?: string } = {}): TestableModule {\n const text = localeTable(options.locale ?? 'en')\n return {\n id: 'terrain',\n name: text.name,\n group: text.group,\n ground: terrainLotsGround(options.locale ?? 'en'),\n items(): TestableItem[] {\n return [{ id: 'terrain_weight', name: text.weight, build: (THREE) => buildWeight(THREE as ThreeLib), spec: weightSpec, movable: true }]\n },\n area(): ModuleArea {\n return {\n placements: TERRAIN_STRIPS.map((_, index) => {\n const [x0, z0] = lotRect(index)\n return { item: 'terrain_weight', position: [x0 + LOT_WIDTH / 2, WEIGHT_HEIGHT, z0 + 1.2] }\n }),\n view: { eye: [0, 1.7, 1.5], target: [0, 0, -6] },\n }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqBO,MAAM,wBAAiE,EAAE,UAAU,KAAK,MAAM,MAAM,UAAU,KAAK,aAAa,OAAO,IAAO;AKVrJ,MAAM,gCAAgC,OAAO;AYmCtC,MAAM,oBAAoB;IAC/B,oBAAoB;IACpB,cAAc;IACd,YAAY;IACZ,cAAc;IACd,gBAAgB;IAChB,iBAAiB;IACjB,YAAY;IACZ,mBAAmB;IACnB,eAAe;IACf,cAAc;IACd,sBAAsB;IACtB,yBAAyB;IACzB,oBAAoB;IACpB,oBAAoB;EACtB;AAGO,MAAM,oBAAoB;IAC/B,CAAC,kBAAkB,kBAAkB,GAAG,EAAE,UAAU,KAAK,OAAO,UAAU;;IAE1E,CAAC,kBAAkB,UAAU,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACrF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,WAAW,gBAAgB,EAAE;IACvF,CAAC,kBAAkB,YAAY,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,WAAW,EAAE;IAC/E,CAAC,kBAAkB,eAAe,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,gBAAgB,EAAE;IACvF,CAAC,kBAAkB,UAAU,GAAG,EAAE,UAAU,KAAK,OAAO,QAAQ,gBAAgB,EAAE;IAClF,CAAC,kBAAkB,cAAc,GAAG,EAAE,UAAU,KAAK,OAAO,OAAO;IACnE,CAAC,kBAAkB,iBAA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