@adatechnology/game-audio 0.6.0 → 0.6.1

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","../src/rng.ts","../src/recipe.ts","../src/falloff.ts","../src/listener.ts","../src/data/voice-groups.json","../src/voices.ts","../src/plan.ts","../src/sample.ts","../src/measure/calibration.ts","../src/bank.ts","../src/data/mix-profiles.json","../src/mix.ts","../src/webaudio/noise.ts","../src/webaudio/chain.ts","../src/webaudio/context.ts","../src/loops.ts","../src/webaudio/nodes.ts","../src/webaudio/realize-loop.ts","../src/webaudio/engine-loop.ts","../src/webaudio/sample-loop.ts","../src/webaudio/engine-noise.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/index.ts","../src/webaudio/engine-queue.ts","../src/webaudio/realize-game.ts","../src/webaudio/realize-layered.ts","../src/webaudio/realize-weapon.ts","../src/webaudio/realize.ts","../src/variation.ts","../src/webaudio/sample-store.ts","../src/webaudio/realize-sample.ts","../src/webaudio/engine.ts","../src/measure/analyze.ts","../src/measure/criteria.ts","../src/catalog.ts","../src/manifest.ts","../src/kit-samples.ts","../src/user-samples.ts","../src/data/game-sfx.json","../src/recipes/noise-class.ts","../src/recipes/scene.ts","../src/library/crowd_rumble.json","../src/library/engine_saw.json","../src/library/horn.json","../src/library/radio_static.json","../src/library/rotor_blades.json","../src/library/siren.json","../src/library/index.ts","../src/library/cabin.ts","../src/recipes/foley.ts","../src/recipes/body-foley.ts","../src/webaudio/sink.ts","../src/bench/locale.ts","../src/bench/module.ts"],"sourcesContent":["/**\n * @adatechnology/game-audio: sound as data. A recipe (layers of noise, oscillators, filters, LFOs and an envelope) is planned into a `SoundPlan`\n * with every number decided by a seeded stream, and the plan is what the WebAudio layer builds. Distance curves, pan, a voice limiter, loops and\n * the two team mixing chains (the game and the art scene) are here; the sounds themselves live in each subject's bank.\n */\nexport { createRng, drawBetween, streamFor, streamSeed } from './rng'\nexport { BUILD_ORDERS, BUS_IDS } from './recipe'\nexport type {\n Automation,\n BuildOrder,\n BusId,\n Curve,\n Envelope,\n EnvelopePoint,\n Falloff,\n FilterBank,\n FilterSpec,\n FormantVoiceSource,\n Layer,\n LayerSource,\n LoopOrder,\n LoopRecipe,\n Modulator,\n NoiseSource,\n OscSource,\n ParamRef,\n Range,\n SoundBank,\n SoundRecipe,\n SoundSet,\n Time,\n} from './recipe'\nexport { planSound } from './plan'\nexport {\n DEFAULT_CROSSOVER,\n DEFAULT_SAMPLE_CUTOFF_K,\n DEFAULT_SAMPLE_FALLOFF,\n DEFAULT_SAMPLE_PITCH,\n DEFAULT_TAIL_GAIN,\n LAYER_FLOOR,\n OPEN_CUTOFF,\n SAMPLE_ENVIRONMENTS,\n crossGains,\n farMixAt,\n pickTake,\n planSample,\n sampleCutoff,\n sampleUrls,\n tierFor,\n} from './sample'\nexport type { PlannedSampleLayer, SampleCrossover, SampleEnvironment, SampleLayerRole, SampleMemory, SamplePlan, SamplePlanInput, SampleRef, SampleSound, SampleTail, SampleTier } from './sample'\nexport { CALIBRATION_ID, CALIBRATION_LOOP_ID, CALIBRATION_LOOP_SOUND, CALIBRATION_SOUND, calibrationLoader, encodeWav, isCalibrationUrl } from './measure/calibration'\nexport { CRITERIA, CRITERIA_TARGETS, measureCriteria, recordOutput } from './measure/criteria'\nexport type { ActionCheck, CriterionId, CriterionResult, MeasureOptions } from './measure/criteria'\nexport { balanceOf, centroidHz, countHits, dbOf, endDropDb, onsetIndex, peakIndex, peakOf, ringSeconds, rmsDb } from './measure/analyze'\nexport { SFX_BLOWS, SFX_CATALOG, SFX_CATEGORIES, SFX_IMPACTS, SFX_MATERIALS, impactSoundId, sfxState } from './catalog'\nexport type { SfxBlow, SfxCategory, SfxEntry, SfxMaterial, SfxPriority, SfxState } from './catalog'\nexport { SDK_LICENSES, SFX_LAYERS, SFX_TIERS, parseSfxName, sampleBankFromManifest, splitTier } from './manifest'\nexport type { SampleBankOptions, SampleDefaults, SdkLicense, SfxFileEntry, SfxLayer, SfxManifest, SfxManifestLike, SfxManifestSound } from './manifest'\nexport { KIT_SAMPLES_BANK, USER_SAMPLES_BANK, USER_SOUND_PREFIX, loadUserSamples, soundSourceOf, userSampleBank } from './user-samples'\nexport type {\n LoadUserSamplesOptions,\n SoundSource,\n UserSampleBankOptions,\n UserSampleBankResult,\n UserSfxFile,\n UserSfxManifest,\n UserSfxSound,\n UserSoundPick,\n UserSoundPicks,\n UserSoundRole,\n} from './user-samples'\nexport { KIT_CATEGORY_BUS, KIT_SAMPLE_ALIASES, kitSampleBank, kitSampleDefaults, loadKitSamples, withAliases } from './kit-samples'\nexport type { KitSampleBankOptions, LoadKitSamplesOptions } from './kit-samples'\nexport type { PlanInput, PlannedAutomation, PlannedEnvelopePoint, PlannedFilter, PlannedLayer, PlannedModulator, PlannedSource, SoundPlan } from './plan'\nexport { DISTANCE_CURVES, cutoffDivisor, falloffGain, isSilent } from './falloff'\nexport type { DistanceCurveName } from './falloff'\nexport { DEFAULT_LISTENER, PAN_LIMIT, PAN_MIN_DISTANCE, listenerDistance, panFor } from './listener'\nexport type { DistanceMode, Listener } from './listener'\nexport { BUS_PRIORITY, DEFAULT_MAX_VOICES, VOICE_GROUPS, busPriority, createVoiceManager } from './voices'\nexport type { VoiceDecision, VoiceGroup, VoiceManager, VoiceManagerOptions, VoiceRefusal, VoiceRequest, VoiceStats } from './voices'\nexport { LOOP_SMOOTHING, LOOP_START_ABOVE, createLoopState } from './loops'\nexport type { LoopAction, LoopState } from './loops'\nexport { DEFAULT_MIX, MIX_PROFILES, busGain, resolveMix } from './mix'\nexport type { BusSetting, MixProfile } from './mix'\nexport { createSoundRegistry } from './bank'\nexport type { DeepPartial, SoundRegistry } from './bank'\nexport { GAME_SFX_BANK, GAME_SFX_CLASSES, GAME_SFX_FALLBACK, noiseClassRecipe } from './recipes/noise-class'\nexport type { NoiseClass } from './recipes/noise-class'\nexport { sceneMany, sceneNoise, sceneRecipe, sceneTone, sceneVoice } from './recipes/scene'\nexport type { SceneLength, SceneNoise, SceneRecipeOptions, SceneTone, SceneVoice } from './recipes/scene'\nexport { LIBRARY_BANK, LIBRARY_LOOPS, LIBRARY_SOUNDS } from './library'\nexport { CABIN_BANK, CABIN_SOUNDS } from './library/cabin'\nexport { FOLEY_BANK, FOLEY_FALLOFF, ITEM_FOLEY, LEAF_FOLEY, LEAF_FOLEY_SETS, PICKUP_CLASSES } from './recipes/foley'\nexport type { LeafFoley, PickupClass } from './recipes/foley'\nexport { BODY_FALLOFF, BODY_FOLEY_BANK, BODY_FOLEY_SET_IDS, BODY_FOLEY_TAKES, FOOTSTEP_FALLOFF } from './recipes/body-foley'\nexport { createSetPicker, retunePlan } from './variation'\nexport type { SetPicker } from './variation'\nexport { createAudioEngine, limiterCurve } from './webaudio/engine'\nexport type { AudioChannel, AudioEngine, AudioEngineOptions, AudioStats, PlayOptions, SampleOptions, VoiceHandle, VoiceStartEvent } from './webaudio/engine'\nexport { createSampleStore, fetchLoader, inlineLoader } from './webaudio/sample-store'\nexport type { SampleLoadReport, SampleLoader, SampleStatus, SampleStore } from './webaudio/sample-store'\nexport { realizeSample, sampleLength } from './webaudio/realize-sample'\nexport type { RealizedSampleVoice, SampleTarget } from './webaudio/realize-sample'\nexport type { AudioLoopHandle, LoopSet } from './webaudio/engine-loop'\nexport { CROSSFADE_STEPS, DEFAULT_LOOP_CROSSFADE, equalPowerIn, loopCrossfade } from './webaudio/sample-loop'\nexport type { SampleLoopHost } from './webaudio/sample-loop'\nexport type { StartQueueOptions } from './webaudio/engine-queue'\nexport { realize } from './webaudio/realize'\nexport type { RealizedVoice, RealizeTarget } from './webaudio/nodes'\nexport { buildChain } from './webaudio/chain'\nexport type { MixChain } from './webaudio/chain'\nexport { bufferOf, fillImpulse, fillNoise } from './webaudio/noise'\nexport { globalContext, unlockContext } from './webaudio/context'\nexport { createAudioSink } from './webaudio/sink'\nexport type { EngineSink } from './webaudio/sink'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport { BENCH_BANK, createAudioTestModule } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport type { AudioScenarioLike, AudioTestModule, AudioTestModuleOptions } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport { audioBenchTextOf } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport type { AudioBenchText } from './testing'\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; floats in [0, 1). The same generator the golden tool seeds `Math.random` with, so a team routine and its recipe draw the same numbers. */\nexport function createRng(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let mixed = Math.imul(state ^ (state >>> 15), state | 1)\n mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61)\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** The seed of the stream called `name` (or numbered `name`): one seed gives each channel its own sequence, so one subject's sounds never shift another's. */\nexport function streamSeed(seed: number, name: string | number): number {\n const label = String(name)\n let hash = FNV_OFFSET\n for (let index = 0; index < label.length; index++) hash = Math.imul(hash ^ label.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function streamFor(seed: number, name: string | number): () => number {\n return createRng(streamSeed(seed, name))\n}\n\n/** `min + random × (max − min)`: the form every team routine uses (`95 + Math.random() * 40`). */\nexport function drawBetween(random: () => number, min: number, max: number): number {\n return min + random() * (max - min)\n}\n","/**\n * Sound recipes are data. A recipe says which nodes a sound has and which numbers drive them; ranges are drawn when the sound is planned, in\n * the order the fields are written (see `planSound`), so a recipe ported from a team routine draws its random numbers in the routine's order.\n */\n\nexport const BUS_IDS = ['weapons', 'voices', 'world', 'ambience', 'weather', 'ui'] as const\nexport type BusId = (typeof BUS_IDS)[number]\n\n/** A named number: from `PlayOptions.params` or the recipe's `vars`, times `scale`, plus `add`. */\nexport type ParamRef = { readonly param: string; readonly scale?: number; readonly add?: number }\n\n/** A number, a `[min, max]` drawn uniformly (`min + random × (max − min)`), or a named number. */\nexport type Range = number | readonly [min: number, max: number] | ParamRef\n\n/** Seconds from the layer start: a range, the layer `'duration'`, or `'0.6d'` (0.6 × the layer duration). */\nexport type Time = Range | 'duration' | `${number}d`\n\nexport type Curve = 'linear' | 'exp'\n\n/**\n * How an AudioParam moves:\n * - `{ set }` assigns `.value`;\n * - `{ set, to, curve, over }` assigns `.value`, then ramps to `to` at `over`;\n * - `{ from }` calls `setValueAtTime(from)` at the start; with `to`, `curve` and `over` it then ramps to `to` (`'from'` is the value drawn for `from`: the art scene ramps a tone back to its own start when it gives no end).\n */\nexport type Automation =\n | { readonly set: Range; readonly to?: Range | 'from'; readonly curve?: Curve; readonly over?: Time }\n | { readonly from: Range; readonly to?: Range | 'from'; readonly curve?: Curve; readonly over?: Time }\n\n/**\n * One gain point: time (seconds, or `'0.6d'`), value and how it is reached (`set` = `setValueAtTime`, or a ramp). The value is multiplied by the\n * layer level (volume, distance and layer gain) except when the fourth item is `'fixed'` (the floor a ramp falls to, such as 0.001).\n */\nexport type EnvelopePoint =\n | readonly [time: number | `${number}d`, value: number, curve: 'set' | Curve]\n | readonly [time: number | `${number}d`, value: number, curve: 'set' | Curve, fixed: 'fixed']\nexport type Envelope = readonly EnvelopePoint[]\n\nexport type FilterSpec = {\n readonly type: BiquadFilterType\n readonly frequency: Automation\n readonly q?: Range\n /** The BiquadFilter gain (shelf and peaking types). */\n readonly gain?: Range\n /** A gain node after the filter, for a parallel bank where each band has its own level (the game's scream formants). */\n readonly level?: Range\n}\n\nexport type FilterBank = { readonly mode: 'serial' | 'parallel'; readonly bank: readonly FilterSpec[] }\n\n/** An LFO. `depth` is absolute, or a factor of the source start frequency. With `base`, gain modulation goes through its own gain stage (the game rotor). */\nexport type Modulator = {\n readonly target: 'gain' | 'frequency'\n /** Left out, the oscillator keeps its default (sine) and no type is set. */\n readonly wave?: OscillatorType\n readonly rate: Range\n readonly depth: Range | { readonly scaleOf: 'frequency'; readonly factor: number }\n readonly base?: number\n}\n\n/**\n * Noise from the engine's seeded buffer. `offset` is where playback starts in it: `'random'` (random × `offsetScale`, default 1), `'fit'`\n * (random × (buffer length − duration)) or seconds. `loop` sets the source to loop (the art scene sets it on every noise source).\n */\nexport type NoiseSource = {\n readonly kind: 'noise'\n readonly offset?: 'random' | 'fit' | number\n readonly offsetScale?: number\n readonly loop?: boolean\n}\n\nexport type OscSource = { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency: Automation }\n\n/** The art scene's `voice`: an oscillator with vibrato through formant bands, plus a band of breath noise, summed and boosted. */\nexport type FormantVoiceSource = {\n readonly kind: 'formant_voice'\n readonly wave: OscillatorType\n readonly frequency: Automation\n /** Vibrato rate, and depth as a factor of the start frequency. */\n readonly vibrato: { readonly rate: Range; readonly depth: number }\n readonly formants: readonly { readonly frequency: Range; readonly q: number }[]\n readonly breath: { readonly frequency: Range; readonly q: number; readonly gain: Range }\n readonly mix: number\n}\n\nexport type LayerSource = NoiseSource | OscSource | FormantVoiceSource\n\nexport type Layer = {\n /** Start, seconds after the sound starts. */\n readonly at?: Range\n /** Overrides the recipe duration for this layer. */\n readonly duration?: Range\n /** Seconds the source keeps running after the duration (the `+ 0.05` of the team routines). Default: the recipe's, else 0.05. */\n readonly tail?: number\n /** The layer played `count` times, `spacing` seconds apart (the game's animal calls). */\n readonly repeat?: { readonly count: number; readonly spacing: number }\n /** Layer level before distance. Default 1. */\n readonly gain?: Range\n /** Send to the reverb, 0..1 or more (the art scene uses up to 1.2). */\n readonly wet?: number\n readonly source: LayerSource\n readonly filters?: FilterBank\n readonly modulators?: readonly Modulator[]\n readonly envelope: Envelope\n}\n\n/**\n * Distance falloff of a sound's level:\n * - `inverse_square`: `volume / (1 + d² × k)`; `cutoffK` also divides every lowpass cutoff by `1 + d × cutoffK` (the game's muffling);\n * - `linear`: `max(0, 1 − d / range)`, silent at or below `minGain`;\n * - `none`: no distance.\n * `scale` multiplies the level (the game's boom is 1.4 at the source), and below `minGain` the sound is not played.\n */\nexport type Falloff =\n | { readonly model: 'inverse_square'; readonly k: number; readonly minGain?: number; readonly cutoffK?: number; readonly scale?: number }\n | { readonly model: 'linear'; readonly range: number; readonly minGain?: number; readonly scale?: number }\n | { readonly model: 'none' }\n\n/**\n * The order the realizer creates and wires the nodes in. Each one is the order of the team routine it reproduces, so the trace of the SDK\n * matches the trace of the team code node for node:\n * - `layered` (default): the art scene's `sNoise`, `sTone` and `voice`; every layer has its own output stage (distance gain, pan, reverb send);\n * - `burst`: the game's `sfx` (jogo L62089);\n * - `scream`: the game's `grito` (L62128);\n * - `groan`: the game's `voz` (L62143);\n * - `boom`: the game's `boom` (L68278);\n * - `static`: the game's `chiado` (L69998);\n * - `chord`: the game's `buzina` (L70272);\n * - `calls`: the game's `bichoSom` (L66625);\n * - `siren`: the art scene's `siren` (L1369);\n * - `weapon`: the weapon audio of the kit (`weapons-three`): per layer a filtered noise burst or an oscillator, then its own gain, chained to the bus.\n * Every order but `layered` puts the level into the envelope and connects straight to the bus.\n */\nexport const BUILD_ORDERS = ['layered', 'burst', 'scream', 'groan', 'boom', 'static', 'chord', 'calls', 'siren', 'weapon'] as const\nexport type BuildOrder = (typeof BUILD_ORDERS)[number]\n\nexport type SoundRecipe = {\n readonly id: string\n readonly bus: BusId\n readonly order?: BuildOrder\n /** Named numbers drawn first, in the order written; layers read them with `{ param }`. */\n readonly vars?: Readonly<Record<string, Range>>\n readonly duration?: Range\n readonly tail?: number\n readonly layers: readonly Layer[]\n readonly falloff?: Falloff\n /** Stereo pan from the listener (the art scene's `panFor`). Only the `layered` order has an output stage to pan. */\n readonly pan?: boolean\n /** Voice group for the limiter (`undead_voice`...). */\n readonly group?: string\n /** Limiter priority; default from the bus (weapons > voices > world > ambience). */\n readonly priority?: number\n /**\n * The team routine creates nodes before it checks the level (the game's `bichoSom` creates its gain and filter first): a silent sound is kept as\n * a plan with `silent: true` so the realizer repeats those nodes. Off by default.\n */\n readonly keepSilent?: boolean\n /** Where the numbers come from: `\"jogo:L62128\"`, `\"cena:L1342\"`, or `\"sdk\"` for values the kit chose. */\n readonly sources: readonly string[]\n}\n\n/**\n * The order the loop realizer creates the nodes in:\n * - `game_loop`: the game's `loopSet` (L62109): gain and filter first, nodes created the first time the volume passes `startAbove`, gain from 0;\n * - `chain_loop`: the art scene's loops in `initAudio` (L1314–1316): source, filters, gain at its starting volume, created when the loop opens.\n */\nexport type LoopOrder = 'game_loop' | 'chain_loop'\n\nexport type LoopRecipe = {\n readonly id: string\n readonly bus: BusId\n readonly order?: LoopOrder\n /** An oscillator loop may leave the frequency out: it starts at the default and `set({ frequency })` glides it (the game's motor). */\n readonly source: (NoiseSource & { readonly loop: true }) | { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency?: Automation; readonly loop: true }\n readonly filters?: FilterBank\n readonly modulators?: readonly Modulator[]\n /** `setTargetAtTime` time constants (jogo L62125–62126: 0.15 for the volume, 0.08 for the frequency). */\n readonly smoothing?: { readonly volume: number; readonly frequency: number }\n /** Nodes are created the first time the volume reaches this (jogo L62112: 0.002). */\n readonly startAbove?: number\n /** Volume the gain starts at when the loop opens (`chain_loop`). */\n readonly volume?: number\n /**\n * Distance falloff of the loop, applied each time `set` gives a `position` (an engine, a fire, a skid heard from where it is). Left out, the loop is\n * heard at the listener, as the team loops are. `cutoffK` also lowers the first filter's cutoff with the distance, as it does for one-shots.\n */\n readonly falloff?: Falloff\n /** Stereo pan from the listener, from the `position` of each `set` (a panner after the gain). Off by default. */\n readonly pan?: boolean\n readonly sources: readonly string[]\n}\n\n/**\n * One id that plays one of several recipes (the takes of a footstep, of a punch): `play(id)` draws a variant, never the one it played last time (unless\n * `repeat`), and plays it at a rate drawn from `rate` (1.04 is 4% higher and 4% shorter; see `retunePlan`), so ten footsteps never sound like one.\n */\nexport type SoundSet = {\n readonly id: string\n /** Recipe ids, at least one. */\n readonly variants: readonly string[]\n /** `[min, max]` of the playback rate (pitch and speed together). Default `[1, 1]`. */\n readonly rate?: readonly [min: number, max: number]\n /** Allow the same variant twice in a row (default false). */\n readonly repeat?: boolean\n}\n\nexport type SoundBank = {\n readonly id: string\n readonly sounds?: readonly SoundRecipe[]\n readonly loops?: readonly LoopRecipe[]\n readonly sets?: readonly SoundSet[]\n /** Sounds played from recorded files (see `sample.ts`). A sample and a recipe may share an id: the sample plays once its files are loaded. */\n readonly samples?: readonly SampleSound[]\n}\n\n// ----- sounds from recorded files (planned by `planSample` in sample.ts; the types live here so the bank has them without an import cycle)\n\n/** One take: a file and its own trim (linear gain, default 1). */\nexport type SampleRef = { readonly url: string; readonly gain?: number }\n\n/** Where a sound happens: a closed room rings short and dense, the open field long and thin. */\nexport type SampleEnvironment = 'indoor' | 'outdoor'\n\n/** Where the near take hands over to the far one: all near up to `from` metres, all far from `to`, an equal-power crossfade between. */\nexport type SampleCrossover = { readonly from: number; readonly to: number }\n\nexport type SampleTail = {\n readonly indoor?: readonly SampleRef[]\n readonly outdoor?: readonly SampleRef[]\n /** Level of the tail against the dry take (default 0.6). */\n readonly gain?: number\n /** Seconds after the start (default 0: the tail file carries its own pre-delay). */\n readonly at?: number\n}\n\n/**\n * A set of takes for a strength of the action (criterion C7: a light blow, a heavy one, a car at 10 or 60 km/h): from `from` (0..1) up, these takes\n * replace `close` and `far`. The tier played is the last one whose `from` is at or below `PlayOptions.intensity`.\n */\nexport type SampleTier = {\n readonly name: string\n readonly from: number\n readonly close: readonly SampleRef[]\n readonly far?: readonly SampleRef[]\n}\n\nexport type SampleSound = {\n readonly id: string\n readonly bus: BusId\n /** The takes heard near; at least one (the criteria ask four for a sound heard all the time). */\n readonly close: readonly SampleRef[]\n /** The takes heard far; without them the near take plays at every distance (muffled by the lowpass). */\n readonly far?: readonly SampleRef[]\n /** Takes by strength (light, medium, heavy), in rising `from`; without `intensity` the near takes above play. */\n readonly tiers?: readonly SampleTier[]\n /** Default `{ from: 30, to: 80 }`. */\n readonly crossover?: SampleCrossover\n readonly tail?: SampleTail\n /** ± fraction of the playback rate drawn per play (default 0.04: ±4 %, inside the 3–5 % of the criteria). 0 plays every take at its pitch. */\n readonly pitch?: number\n /** Level of the sound (default 1). */\n readonly gain?: number\n /** Default `{ model: 'inverse_square', k: 0.002, minGain: 0.002 }`: a recorded take already sounds near or far, so the curve is gentler than a recipe's. */\n readonly falloff?: Falloff\n /** The lowpass cutoff is `20000 / (1 + d × cutoffK)` Hz (default 0.01: 10 kHz at 100 m). 0 turns the distance lowpass off. */\n readonly cutoffK?: number\n /** Stereo pan from the listener (default true). */\n readonly pan?: boolean\n readonly group?: string\n readonly priority?: number\n /**\n * At most `voices` plays of this sound ring at once: a new one fades the oldest out in `fade` seconds (default 0.03) at its own start. Rapid fire\n * then stays shot by shot instead of a wall of overlapping takes (criterion C9). Without it every play rings to its end.\n */\n readonly choke?: { readonly voices: number; readonly fade?: number }\n /**\n * A continuous sound (fire, rain, an engine idling) that `engine.loop(id)` plays: the near takes chained without a seam, each crossed into the next\n * in `crossfade` seconds (default 0.25, equal power), never the same take twice in a row. While the files load, the recipe loop of `fallback`\n * (or of the same id) plays. `play(id)` still plays one take as a one-shot.\n */\n readonly loop?: boolean | { readonly crossfade?: number }\n /** A recipe id the engine plays while the files are not loaded yet (or failed): the synthesized sound stays as the fallback. */\n readonly fallback?: string\n /** Where each file came from: `\"freesound:123456 autor CC0\"`, or `\"sdk\"` for files the kit made. */\n readonly sources: readonly string[]\n}\n","import type { Falloff } from './recipe'\n\n/** The distance curves of the team routines, by name. Each recipe carries its own; these are the values to copy. */\nexport const DISTANCE_CURVES = {\n /** The game's `sfx`: `vol / (1 + d² × 0.004)`, cutoff `/ (1 + d × 0.01)`, silent below 0.01 (jogo L62091–62092, L62101). */\n game_sfx: { model: 'inverse_square', k: 0.004, cutoffK: 0.01, minGain: 0.01 },\n /** The game's `grito`: `1 / (1 + d² × 0.006)`, silent below 0.02 (jogo L62129–62130). */\n game_scream: { model: 'inverse_square', k: 0.006, minGain: 0.02 },\n /** The game's `voz`: `1 / (1 + d² × 0.01)`, silent below 0.02 (jogo L62146–62147). */\n game_voice: { model: 'inverse_square', k: 0.01, minGain: 0.02 },\n /** The game's `boom`: `1.4 / (1 + d² × 0.002)`, never silent (jogo L68280). */\n game_boom: { model: 'inverse_square', k: 0.002, scale: 1.4 },\n /** The art scene's `outAt`: `vol / (1 + d² × 0.008)` (cena L1320). */\n art_scene: { model: 'inverse_square', k: 0.008 },\n /** The game's animal calls: `max(0, 1 − d / 70) × 0.25`, silent at or below 0.005 (jogo L66627–66628). */\n animals: { model: 'linear', range: 70, scale: 0.25, minGain: 0.005 },\n} as const satisfies Readonly<Record<string, Falloff>>\n\nexport type DistanceCurveName = keyof typeof DISTANCE_CURVES\n\n/** The level at `distance` for a sound at `volume`, before the recipe's envelope. */\nexport function falloffGain(falloff: Falloff | undefined, volume: number, distance: number): number {\n if (!falloff || falloff.model === 'none') return volume\n if (falloff.model === 'linear') {\n const level = Math.max(0, 1 - distance / falloff.range) * volume\n return falloff.scale === undefined ? level : level * falloff.scale\n }\n const level = volume / (1 + distance * distance * falloff.k)\n return falloff.scale === undefined ? level : falloff.scale * level\n}\n\n/** Whether a level is too quiet to play: below `minGain` (the game's `att < 0.01`), or at or below it for `linear` (the animal calls' `v <= 0.005`). */\nexport function isSilent(falloff: Falloff | undefined, gain: number): boolean {\n if (!falloff || falloff.model === 'none' || falloff.minGain === undefined) return false\n return falloff.model === 'linear' ? gain <= falloff.minGain : gain < falloff.minGain\n}\n\n/** What every lowpass cutoff is divided by at `distance` (1 when the curve has no muffling). */\nexport function cutoffDivisor(falloff: Falloff | undefined, distance: number): number {\n if (!falloff || falloff.model !== 'inverse_square' || falloff.cutoffK === undefined) return 1\n return 1 + distance * falloff.cutoffK\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\n/** Where the ears are. `yaw` turns around y like a three.js camera: the right ear points at `(cos yaw, 0, −sin yaw)`. */\nexport type Listener = { readonly position: Vec3; readonly yaw: number }\n\nexport type DistanceMode = 'xz' | '3d'\n\nexport const DEFAULT_LISTENER: Listener = { position: [0, 0, 0], yaw: 0 }\n\n/** The art scene clamps the pan to ±0.85 and never divides by less than 2 m (cena L1319). */\nexport const PAN_LIMIT = 0.85\nexport const PAN_MIN_DISTANCE = 2\n\n/** Distance from the listener: on the ground (`xz`, the teams' choice) or in 3D. */\nexport function listenerDistance(listener: Listener, position: Vec3, mode: DistanceMode = 'xz'): number {\n const dx = position[0] - listener.position[0]\n const dz = position[2] - listener.position[2]\n if (mode === 'xz') return Math.hypot(dx, dz)\n return Math.hypot(dx, position[1] - listener.position[1], dz)\n}\n\n/** The art scene's `panFor`: the side the sound is on, −0.85 (left) to 0.85 (right). No HRTF, for cost. */\nexport function panFor(listener: Listener, position: Vec3): number {\n const rightX = Math.cos(listener.yaw)\n const rightZ = -Math.sin(listener.yaw)\n const dx = position[0] - listener.position[0]\n const dz = position[2] - listener.position[2]\n const distance = Math.hypot(dx, dz) || 1\n const pan = (dx * rightX + dz * rightZ) / Math.max(distance, PAN_MIN_DISTANCE)\n return pan < -PAN_LIMIT ? -PAN_LIMIT : pan > PAN_LIMIT ? PAN_LIMIT : pan\n}\n","{\n \"undead_voice\": {\n \"maxConcurrent\": 5,\n \"cooldown\": 0.25,\n \"maxDistance\": 40,\n \"sources\": [\n \"cena:L1342 `AU.groans > 4` refuses, so five play at once\",\n \"jogo:L66986 one groan every 0.25 s (`groanBudget`), only nearer than 40 m\",\n \"jogo:L70472 the budget counts down by the frame time\"\n ]\n },\n \"fire_ignite\": {\n \"maxConcurrent\": 2,\n \"cooldown\": 0.15,\n \"sources\": [\n \"sdk: many parts catching at once (a blast sets a shelf alight) are one or two ignitions, not forty\"\n ]\n },\n \"fire_crackle\": {\n \"maxConcurrent\": 4,\n \"sources\": [\n \"sdk: the crackles of every fire share four voices\"\n ]\n }\n}\n","import voiceGroupsJson from './data/voice-groups.json'\nimport type { BusId } from './recipe'\n\n/**\n * Rules for a group of voices (`undead_voice`...). A request passes when every rule passes:\n * - `maxConcurrent`: at most this many of the group play at once (`steal` replaces the group's oldest instead of refusing);\n * - `cooldown`: seconds after an accepted voice before the next one (the game's `groanBudget`, jogo L66986 and L70472);\n * - `maxDistance`: only voices nearer than this (the game's `d < 40`).\n */\nexport type VoiceGroup = {\n readonly maxConcurrent?: number\n readonly cooldown?: number\n readonly maxDistance?: number\n readonly steal?: boolean\n readonly sources?: readonly string[]\n}\n\n/** `undead_voice`: the art scene's five at once with the game's 0.25 s cooldown and 40 m. */\nexport const VOICE_GROUPS: Readonly<Record<string, VoiceGroup>> = voiceGroupsJson\n\n/** Q7: weapons > voices > world > ambience; the interface above all, weather with the ambience. */\nexport const BUS_PRIORITY: Readonly<Record<BusId, number>> = { ui: 5, weapons: 4, voices: 3, world: 2, weather: 1, ambience: 1 }\nexport const DEFAULT_MAX_VOICES = 32\n\nexport function busPriority(bus: BusId): number {\n return BUS_PRIORITY[bus]\n}\n\nexport type VoiceRequest = {\n readonly group?: string\n readonly priority: number\n /** Planned level; the global cap drops the lowest `priority × gain`. */\n readonly gain: number\n readonly distance?: number\n /** Seconds the voice lasts. */\n readonly length: number\n}\n\nexport type VoiceRefusal = 'cooldown' | 'distance' | 'group_full' | 'global_full'\n\nexport type VoiceDecision =\n | { readonly accepted: true; readonly id: number; readonly evicted: readonly number[] }\n | { readonly accepted: false; readonly reason: VoiceRefusal }\n\nexport type VoiceStats = { readonly active: number; readonly peak: number; readonly dropped: number; readonly maxVoices: number }\n\nexport type VoiceManager = {\n request(request: VoiceRequest): VoiceDecision\n /** Ends a voice early (stopped by the host). */\n release(id: number): void\n /** Sets how long an accepted voice lasts (the engine admits a voice before its random length is drawn). */\n setLength(id: number, seconds: number): void\n /** Moves time on: cooldowns count down and finished voices leave. Returns the ids that ended. */\n advance(dt: number): number[]\n setGroup(id: string, group: VoiceGroup | undefined): void\n stats(): VoiceStats\n}\n\nexport type VoiceManagerOptions = {\n /** Default `VOICE_GROUPS`. */\n readonly groups?: Readonly<Record<string, VoiceGroup>>\n readonly maxVoices?: number\n}\n\ntype ActiveVoice = { readonly id: number; readonly group?: string; readonly score: number; remaining: number }\n\n/** The voice limiter: per-group rules, a global cap and priority dropping. Pure and time-driven (`advance`), so goldens script it frame by frame. */\nexport function createVoiceManager(options: VoiceManagerOptions = {}): VoiceManager {\n const groups = new Map(Object.entries(options.groups ?? VOICE_GROUPS))\n const maxVoices = options.maxVoices ?? DEFAULT_MAX_VOICES\n const budgets = new Map<string, number>()\n let voices: ActiveVoice[] = []\n let nextId = 1\n let peak = 0\n let dropped = 0\n\n const refuse = (reason: VoiceRefusal): VoiceDecision => {\n dropped += 1\n return { accepted: false, reason }\n }\n\n const groupCheck = (request: VoiceRequest, evicted: number[]): VoiceRefusal | undefined => {\n const group = request.group === undefined ? undefined : groups.get(request.group)\n if (!group) return undefined\n if (group.maxDistance !== undefined && !((request.distance ?? 0) < group.maxDistance)) return 'distance'\n if (group.cooldown !== undefined && (budgets.get(request.group as string) ?? 0) > 0) return 'cooldown'\n const members = voices.filter((voice) => voice.group === request.group)\n if (group.maxConcurrent === undefined || members.length < group.maxConcurrent) return undefined\n if (!group.steal) return 'group_full'\n evicted.push((members[0] as ActiveVoice).id)\n return undefined\n }\n\n return {\n request(request) {\n const evicted: number[] = []\n const refusal = groupCheck(request, evicted)\n if (refusal) return refuse(refusal)\n const score = request.priority * request.gain\n const remaining = voices.filter((voice) => !evicted.includes(voice.id))\n if (remaining.length >= maxVoices) {\n const lowest = remaining.reduce((low, voice) => (voice.score < low.score ? voice : low))\n if (score <= lowest.score) return refuse('global_full')\n evicted.push(lowest.id)\n dropped += 1\n }\n const group = request.group === undefined ? undefined : groups.get(request.group)\n if (group?.cooldown !== undefined) budgets.set(request.group as string, group.cooldown)\n const id = nextId++\n voices = [...voices.filter((voice) => !evicted.includes(voice.id)), { id, ...(request.group === undefined ? {} : { group: request.group }), score, remaining: request.length }]\n peak = Math.max(peak, voices.length)\n return { accepted: true, id, evicted }\n },\n release(id) {\n voices = voices.filter((voice) => voice.id !== id)\n },\n setLength(id, seconds) {\n const voice = voices.find((entry) => entry.id === id)\n if (voice) voice.remaining = seconds\n },\n advance(dt) {\n for (const [group, budget] of budgets) budgets.set(group, budget - dt)\n const ended: number[] = []\n for (const voice of voices) {\n voice.remaining -= dt\n if (voice.remaining <= 0) ended.push(voice.id)\n }\n if (ended.length > 0) voices = voices.filter((voice) => voice.remaining > 0)\n return ended\n },\n setGroup(id, group) {\n if (group) groups.set(id, group)\n else groups.delete(id)\n },\n stats: () => ({ active: voices.length, peak, dropped, maxVoices }),\n }\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { cutoffDivisor, falloffGain, isSilent } from './falloff'\nimport { DEFAULT_LISTENER, listenerDistance, panFor } from './listener'\nimport type { DistanceMode, Listener } from './listener'\nimport type { Automation, BuildOrder, BusId, Curve, Envelope, FilterSpec, Layer, LayerSource, Modulator, Range, SoundRecipe, Time } from './recipe'\nimport { createRng } from './rng'\nimport { busPriority } from './voices'\n\n/** How an AudioParam moves, with every number resolved and every time in seconds from the layer start. */\nexport type PlannedAutomation = {\n /** Assigned to `.value`. */\n readonly value?: number\n /** `setValueAtTime(from)` at the layer start. */\n readonly from?: number\n /** Ramp target, reached `at` seconds after the layer start. */\n readonly to?: number\n readonly curve?: Curve\n readonly at?: number\n}\n\nexport type PlannedFilter = {\n readonly type: BiquadFilterType\n readonly frequency: PlannedAutomation\n readonly q?: number\n readonly gain?: number\n readonly level?: number\n}\n\nexport type PlannedModulator = {\n readonly target: 'gain' | 'frequency'\n readonly wave?: OscillatorType\n readonly rate: number\n readonly depth: number\n readonly base?: number\n}\n\nexport type PlannedSource =\n | { readonly kind: 'noise'; readonly offset: number; readonly loop: boolean }\n | { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency: PlannedAutomation }\n | {\n readonly kind: 'formant_voice'\n readonly wave: OscillatorType\n readonly frequency: PlannedAutomation\n readonly vibrato: { readonly rate: number; readonly depth: number }\n readonly formants: readonly { readonly frequency: number; readonly q: number }[]\n readonly breath: { readonly frequency: number; readonly q: number; readonly gain: number; readonly offset: number }\n readonly mix: number\n }\n\nexport type PlannedEnvelopePoint = { readonly time: number; readonly value: number; readonly curve: 'set' | Curve }\n\nexport type PlannedLayer = {\n readonly at: number\n readonly duration: number\n readonly tail: number\n /** Layer gain × the sound's level: in the envelope for every order but `layered`, in the output stage for `layered`. */\n readonly level: number\n readonly wet?: number\n readonly source: PlannedSource\n readonly filters?: { readonly mode: 'serial' | 'parallel'; readonly bank: readonly PlannedFilter[] }\n readonly modulators: readonly PlannedModulator[]\n readonly envelope: readonly PlannedEnvelopePoint[]\n}\n\n/** A sound with every number decided: what the realizer builds, what goldens compare and what the bench sheet prints. */\nexport type SoundPlan = {\n readonly id: string\n readonly bus: BusId\n readonly order: BuildOrder\n readonly group?: string\n readonly priority: number\n /** The level from volume and distance, before layer gains. */\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** Too quiet to hear, kept only for a recipe with `keepSilent`. */\n readonly silent: boolean\n /** Seconds until the last source stops. */\n readonly length: number\n readonly layers: readonly PlannedLayer[]\n}\n\nexport type PlanInput = {\n /** Where the numbers are drawn from. Default: a fresh stream with seed 1. */\n readonly random?: () => number\n readonly volume?: number\n /** Distance in meters; overrides `position`. */\n readonly distance?: number\n readonly position?: Vec3\n readonly listener?: Listener\n readonly distanceMode?: DistanceMode\n readonly params?: Readonly<Record<string, number>>\n /** 0..1 from the host's occlusion callback: gain × (1 − 0.5 × o), lowpass cutoffs × (1 − 0.6 × o). */\n readonly occlusion?: number\n /** Length of the noise buffer, for `offset: 'fit'`. Default 1.5. */\n readonly noiseSeconds?: number\n}\n\nconst DEFAULT_TAIL = 0.05\nconst DEFAULT_NOISE_SECONDS = 1.5\nconst OCCLUSION_GAIN = 0.5\nconst OCCLUSION_CUTOFF = 0.6\n\ntype Scope = { readonly random: () => number; readonly params: Record<string, number> }\n\nfunction isParamRef(range: Range): range is Extract<Range, { readonly param: string }> {\n return typeof range === 'object' && !Array.isArray(range)\n}\n\nfunction draw(range: Range, scope: Scope): number {\n if (typeof range === 'number') return range\n if (isParamRef(range)) {\n const value = scope.params[range.param]\n if (value === undefined) throw new Error(`game-audio: the recipe reads the param \"${range.param}\", which was not given`)\n return value * (range.scale ?? 1) + (range.add ?? 0)\n }\n const [min, max] = range as readonly [number, number]\n return min + scope.random() * (max - min)\n}\n\n// a time is drawn now when it is a range; 'duration' and '0.6d' wait for the layer duration\ntype PendingTime = number | 'duration' | `${number}d`\n\nfunction drawTime(time: Time, scope: Scope): PendingTime {\n if (time === 'duration' || (typeof time === 'string' && time.endsWith('d'))) return time as PendingTime\n return draw(time as Range, scope)\n}\n\nfunction timeOf(time: PendingTime, duration: number): number {\n if (typeof time === 'number') return time\n if (time === 'duration') return duration\n return Number(time.slice(0, -1)) * duration\n}\n\ntype PendingAutomation = { value?: number; from?: number; to?: number; curve?: Curve; over?: PendingTime }\n\nfunction drawAutomation(automation: Automation, scope: Scope): PendingAutomation {\n const pending: PendingAutomation = {}\n for (const key of Object.keys(automation)) {\n if (key === 'set' && 'set' in automation) pending.value = draw(automation.set, scope)\n else if (key === 'from' && 'from' in automation) pending.from = draw(automation.from, scope)\n else if (key === 'to' && automation.to !== undefined) pending.to = automation.to === 'from' ? (pending.from ?? pending.value ?? 0) : draw(automation.to, scope)\n else if (key === 'curve') pending.curve = automation.curve\n else if (key === 'over' && automation.over !== undefined) pending.over = drawTime(automation.over, scope)\n }\n return pending\n}\n\nfunction finishAutomation(pending: PendingAutomation, duration: number): PlannedAutomation {\n if (pending.from !== undefined && pending.to === undefined) return { from: pending.from }\n if (pending.from !== undefined) return { from: pending.from, to: pending.to, curve: pending.curve ?? 'linear', at: timeOf(pending.over ?? 'duration', duration) }\n if (pending.to === undefined || pending.over === undefined) return { value: pending.value }\n return { value: pending.value, to: pending.to, curve: pending.curve ?? 'linear', at: timeOf(pending.over, duration) }\n}\n\nconst startFrequency = (automation: PendingAutomation): number => automation.from ?? automation.value ?? 0\n\ntype PendingFilter = { spec: FilterSpec; frequency: PendingAutomation; q?: number; gain?: number; level?: number }\n\nfunction drawFilter(spec: FilterSpec, scope: Scope): PendingFilter {\n const pending: PendingFilter = { spec, frequency: {} }\n for (const key of Object.keys(spec)) {\n if (key === 'frequency') pending.frequency = drawAutomation(spec.frequency, scope)\n else if (key === 'q' && spec.q !== undefined) pending.q = draw(spec.q, scope)\n else if (key === 'gain' && spec.gain !== undefined) pending.gain = draw(spec.gain, scope)\n else if (key === 'level' && spec.level !== undefined) pending.level = draw(spec.level, scope)\n }\n return pending\n}\n\ntype PendingModulator = { modulator: Modulator; rate: number; depth?: number }\n\nfunction drawModulator(modulator: Modulator, scope: Scope): PendingModulator {\n const pending: PendingModulator = { modulator, rate: 0 }\n for (const key of Object.keys(modulator)) {\n if (key === 'rate') pending.rate = draw(modulator.rate, scope)\n else if (key === 'depth' && !(typeof modulator.depth === 'object' && 'scaleOf' in modulator.depth)) pending.depth = draw(modulator.depth as Range, scope)\n }\n return pending\n}\n\ntype PendingVoice = { frequency: PendingAutomation; vibratoRate: number; formants: { frequency: number; q: number }[]; breath: { frequency: number; q: number; gain: number } }\n\nfunction drawVoice(source: Extract<LayerSource, { kind: 'formant_voice' }>, scope: Scope): PendingVoice {\n const pending: PendingVoice = { frequency: {}, vibratoRate: 0, formants: [], breath: { frequency: 0, q: source.breath.q, gain: 0 } }\n for (const key of Object.keys(source)) {\n if (key === 'frequency') pending.frequency = drawAutomation(source.frequency, scope)\n else if (key === 'vibrato') pending.vibratoRate = draw(source.vibrato.rate, scope)\n else if (key === 'formants') pending.formants = source.formants.map((formant) => ({ frequency: draw(formant.frequency, scope), q: formant.q }))\n else if (key === 'breath') pending.breath = { frequency: draw(source.breath.frequency, scope), q: source.breath.q, gain: draw(source.breath.gain, scope) }\n }\n return pending\n}\n\ntype LayerDefaults = { readonly duration?: number; readonly tail?: number; readonly noiseSeconds: number }\n\ntype PendingLayer = {\n at: number\n duration?: number\n gain: number\n automation?: PendingAutomation\n voice?: PendingVoice\n filters: PendingFilter[]\n modulators: PendingModulator[]\n}\n\nfunction drawLayer(layer: Layer, scope: Scope): PendingLayer {\n const pending: PendingLayer = { at: 0, gain: 1, filters: [], modulators: [] }\n for (const key of Object.keys(layer)) {\n if (key === 'at' && layer.at !== undefined) pending.at = draw(layer.at, scope)\n else if (key === 'duration' && layer.duration !== undefined) pending.duration = draw(layer.duration, scope)\n else if (key === 'gain' && layer.gain !== undefined) pending.gain = draw(layer.gain, scope)\n else if (key === 'source' && layer.source.kind === 'osc') pending.automation = drawAutomation(layer.source.frequency, scope)\n else if (key === 'source' && layer.source.kind === 'formant_voice') pending.voice = drawVoice(layer.source, scope)\n else if (key === 'filters' && layer.filters) pending.filters = layer.filters.bank.map((spec) => drawFilter(spec, scope))\n else if (key === 'modulators' && layer.modulators) pending.modulators = layer.modulators.map((modulator) => drawModulator(modulator, scope))\n }\n return pending\n}\n\n// the team code draws the noise start point when the source starts, after every other number of the layer\nfunction drawOffset(source: LayerSource, duration: number, scope: Scope, noiseSeconds: number): number {\n if (source.kind === 'formant_voice') return scope.random()\n if (source.kind !== 'noise' || source.offset === undefined) return 0\n if (typeof source.offset === 'number') return source.offset\n if (source.offset === 'fit') return scope.random() * Math.max(0, noiseSeconds - duration)\n return scope.random() * (source.offsetScale ?? 1)\n}\n\nfunction finishSource(layer: Layer, pending: PendingLayer, duration: number, offset: number): PlannedSource {\n const source = layer.source\n if (source.kind === 'noise') return { kind: 'noise', offset, loop: source.loop === true }\n if (source.kind === 'osc') return { kind: 'osc', wave: source.wave, frequency: finishAutomation(pending.automation ?? {}, duration) }\n const voice = pending.voice as PendingVoice\n return {\n kind: 'formant_voice',\n wave: source.wave,\n frequency: finishAutomation(voice.frequency, duration),\n vibrato: { rate: voice.vibratoRate, depth: startFrequency(voice.frequency) * source.vibrato.depth },\n formants: voice.formants,\n breath: { ...voice.breath, offset },\n mix: source.mix,\n }\n}\n\nfunction finishModulator(pending: PendingModulator, sourceFrequency: number): PlannedModulator {\n const { modulator } = pending\n const depth = typeof modulator.depth === 'object' && 'scaleOf' in modulator.depth ? sourceFrequency * modulator.depth.factor : (pending.depth ?? 0)\n return { target: modulator.target, ...(modulator.wave ? { wave: modulator.wave } : {}), rate: pending.rate, depth, ...(modulator.base === undefined ? {} : { base: modulator.base }) }\n}\n\nfunction finishEnvelope(envelope: Envelope, duration: number, level: number): PlannedEnvelopePoint[] {\n return envelope.map(([time, value, curve, fixed]) => ({ time: timeOf(time, duration), value: fixed === 'fixed' ? value : value * level, curve }))\n}\n\nfunction planLayer(layer: Layer, scope: Scope, defaults: LayerDefaults, levelInEnvelope: boolean, soundLevel: number): PlannedLayer[] {\n const pending = drawLayer(layer, scope)\n const duration = pending.duration ?? defaults.duration\n if (duration === undefined) throw new Error('game-audio: a layer needs a duration (its own or the recipe’s)')\n const offset = drawOffset(layer.source, duration, scope, defaults.noiseSeconds)\n const level = pending.gain * soundLevel\n const sourceFrequency = layer.source.kind === 'noise' ? 0 : startFrequency(pending.automation ?? pending.voice?.frequency ?? {})\n const planned: PlannedLayer = {\n at: pending.at,\n duration,\n tail: layer.tail ?? defaults.tail ?? DEFAULT_TAIL,\n level,\n ...(layer.wet === undefined ? {} : { wet: layer.wet }),\n source: finishSource(layer, pending, duration, offset),\n ...(layer.filters\n ? {\n filters: {\n mode: layer.filters.mode,\n bank: pending.filters.map(({ spec, frequency, q, gain, level: filterLevel }) => ({\n type: spec.type,\n frequency: finishAutomation(frequency, duration),\n ...(q === undefined ? {} : { q }),\n ...(gain === undefined ? {} : { gain }),\n ...(filterLevel === undefined ? {} : { level: filterLevel }),\n })),\n },\n }\n : {}),\n modulators: pending.modulators.map((modulator) => finishModulator(modulator, sourceFrequency)),\n envelope: finishEnvelope(layer.envelope, duration, levelInEnvelope ? level : 1),\n }\n if (!layer.repeat) return [planned]\n return Array.from({ length: layer.repeat.count }, (_, index) => ({ ...planned, at: planned.at + index * (layer.repeat?.spacing ?? 0) }))\n}\n\nfunction scaleAutomation(automation: PlannedAutomation, divisor: number): PlannedAutomation {\n const scale = (value: number | undefined): number | undefined => (value === undefined ? undefined : value / divisor)\n const scaled: Record<string, unknown> = { ...automation }\n for (const key of ['value', 'from', 'to'] as const) if (automation[key] !== undefined) scaled[key] = scale(automation[key])\n return scaled as PlannedAutomation\n}\n\n// distance muffling and occlusion lower every lowpass cutoff of the sound\nfunction muffle(layer: PlannedLayer, divisor: number): PlannedLayer {\n if (divisor === 1 || !layer.filters) return layer\n const bank = layer.filters.bank.map((filter) => (filter.type === 'lowpass' ? { ...filter, frequency: scaleAutomation(filter.frequency, divisor) } : filter))\n return { ...layer, filters: { ...layer.filters, bank } }\n}\n\nconst layerEnd = (layer: PlannedLayer): number => layer.at + layer.duration + layer.tail\n\n/**\n * Turns a recipe into a plan: pure, Node-safe, the same plan for the same `random`. Numbers are drawn in this order: `vars` (in the order written),\n * `duration`, then each layer in the order its fields are written, the noise start point last in its layer. A sound below its falloff's `minGain`\n * gives `null` (or a silent plan with `keepSilent`) before any number is drawn.\n */\nexport function planSound(recipe: SoundRecipe, input: PlanInput = {}): SoundPlan | null {\n const listener = input.listener ?? DEFAULT_LISTENER\n const distance = input.distance ?? (input.position ? listenerDistance(listener, input.position, input.distanceMode) : 0)\n const occlusion = Math.min(1, Math.max(0, input.occlusion ?? 0))\n const order = recipe.order ?? 'layered'\n const falloffLevel = falloffGain(recipe.falloff, input.volume ?? 1, distance)\n const level = occlusion > 0 ? falloffLevel * (1 - OCCLUSION_GAIN * occlusion) : falloffLevel\n const silent = isSilent(recipe.falloff, falloffLevel)\n const base = {\n id: recipe.id,\n bus: recipe.bus,\n order,\n ...(recipe.group === undefined ? {} : { group: recipe.group }),\n priority: recipe.priority ?? busPriority(recipe.bus),\n level,\n distance,\n ...(recipe.pan ? { pan: input.position ? panFor(listener, input.position) : 0 } : {}),\n }\n if (silent) return recipe.keepSilent ? { ...base, silent: true, length: 0, layers: [] } : null\n\n const scope: Scope = { random: input.random ?? createRng(1), params: { ...input.params } }\n for (const [name, range] of Object.entries(recipe.vars ?? {})) if (scope.params[name] === undefined) scope.params[name] = draw(range, scope)\n const defaults: LayerDefaults = {\n ...(recipe.duration === undefined ? {} : { duration: draw(recipe.duration, scope) }),\n ...(recipe.tail === undefined ? {} : { tail: recipe.tail }),\n noiseSeconds: input.noiseSeconds ?? DEFAULT_NOISE_SECONDS,\n }\n const divisor = cutoffDivisor(recipe.falloff, distance) / (1 - OCCLUSION_CUTOFF * occlusion)\n const layers = recipe.layers.flatMap((layer) => planLayer(layer, scope, defaults, order !== 'layered', level)).map((layer) => muffle(layer, divisor))\n return { ...base, silent: false, length: Math.max(0, ...layers.map(layerEnd)), layers }\n}\n","/**\n * Sounds made of recorded files (`.ogg`), as data. A `SampleSound` lists the takes of each layer: `close` (the sound as heard near, the only one\n * required), `far` (the same event heard from far away: a muffled bang with its echo) and the tail of the place it happens in (`indoor` / `outdoor`).\n * `planSample` decides, from a seeded stream, which take plays (round-robin: never the same take twice in a row), the pitch (± a fraction), how the\n * near and far layers cross over with the distance, the level, the pan and the distance lowpass. It is pure, so it runs in Node and in tests; the\n * WebAudio layer (`realizeSample`) plays the plan from decoded buffers.\n */\nimport type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { falloffGain, isSilent } from './falloff'\nimport { DEFAULT_LISTENER, listenerDistance, panFor } from './listener'\nimport type { DistanceMode, Listener } from './listener'\nimport type { BusId, Falloff, SampleCrossover, SampleEnvironment, SampleRef, SampleSound, SampleTier } from './recipe'\nimport { busPriority } from './voices'\n\nexport type { SampleCrossover, SampleEnvironment, SampleRef, SampleSound, SampleTail, SampleTier } from './recipe'\n\nexport const SAMPLE_ENVIRONMENTS = ['indoor', 'outdoor'] as const satisfies readonly SampleEnvironment[]\n\n/** The role of a layer in a plan. */\nexport type SampleLayerRole = 'close' | 'far' | 'tail'\n\nexport const DEFAULT_SAMPLE_FALLOFF: Falloff = { model: 'inverse_square', k: 0.002, minGain: 0.002 }\nexport const DEFAULT_CROSSOVER: SampleCrossover = { from: 30, to: 80 }\nexport const DEFAULT_SAMPLE_PITCH = 0.04\nexport const DEFAULT_TAIL_GAIN = 0.6\nexport const DEFAULT_SAMPLE_CUTOFF_K = 0.01\n/** The open lowpass: at or above it the realizer leaves the filter out. */\nexport const OPEN_CUTOFF = 20000\n/** A layer quieter than this is left out of the plan. */\nexport const LAYER_FLOOR = 0.001\n\n/** One file to play: which take, at what level (already times the sound level), rate and start. */\nexport type PlannedSampleLayer = {\n readonly role: SampleLayerRole\n readonly url: string\n /** Index of the take in its list. */\n readonly take: number\n readonly gain: number\n readonly rate: number\n readonly at: number\n}\n\nexport type SamplePlan = {\n readonly kind: 'sample'\n readonly id: string\n readonly bus: BusId\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** Lowpass cutoff in Hz (`OPEN_CUTOFF` = no filter). */\n readonly cutoff: number\n /** Playback rate of every layer (the pitch drawn for this play). */\n readonly rate: number\n readonly environment: SampleEnvironment\n /** The tier played (`undefined` without tiers or intensity). */\n readonly tier?: string\n /** 0 = all near, 1 = all far. */\n readonly farMix: number\n readonly layers: readonly PlannedSampleLayer[]\n readonly priority: number\n readonly group?: string\n}\n\n/** The last take each sound layer played (`<id>/<role>` → index), so the next play never repeats it. Keep one per engine or channel. */\nexport type SampleMemory = Map<string, number>\n\nexport type SamplePlanInput = {\n readonly random: () => number\n readonly listener?: Listener\n readonly distanceMode?: DistanceMode\n readonly position?: Vec3\n /** Metres; overrides `position` for the distance (not for the pan). */\n readonly distance?: number\n readonly volume?: number\n /** Default `outdoor`. */\n readonly environment?: SampleEnvironment\n /** 0 (clear) to 1 (behind a wall): lowers the level and closes the lowpass. */\n readonly occlusion?: number\n /** Round-robin memory; without it each plan is drawn on its own (and may repeat). */\n readonly memory?: SampleMemory\n /** Limiter priority when the sound has none. */\n readonly priority?: number\n /** 0 (light) to 1 (heavy): picks the tier (see `SampleTier`). */\n readonly intensity?: number\n}\n\n/**\n * Round-robin without repeat: a take drawn among all but the last one played. With one take it is always 0; without `last` any take may come.\n * One random number per call.\n */\nexport function pickTake(count: number, last: number | undefined, random: () => number): number {\n if (count <= 1) return 0\n if (last === undefined || last < 0 || last >= count) return Math.min(count - 1, Math.floor(random() * count))\n const drawn = Math.min(count - 2, Math.floor(random() * (count - 1)))\n return drawn >= last ? drawn + 1 : drawn\n}\n\n/** 0 at or below `from`, 1 at or beyond `to`, linear between. */\nexport function farMixAt(crossover: SampleCrossover, distance: number): number {\n if (crossover.to <= crossover.from) return distance >= crossover.to ? 1 : 0\n const t = (distance - crossover.from) / (crossover.to - crossover.from)\n return t <= 0 ? 0 : t >= 1 ? 1 : t\n}\n\n/** Equal-power gains of the near and far layers for a far mix (so the crossover has no dip in loudness). */\nexport function crossGains(farMix: number): { readonly close: number; readonly far: number } {\n return { close: Math.cos((farMix * Math.PI) / 2), far: Math.sin((farMix * Math.PI) / 2) }\n}\n\n/** The distance lowpass, closed further behind a wall (an occluded sound loses its highs first). */\nexport function sampleCutoff(cutoffK: number, distance: number, occlusion = 0): number {\n const byDistance = cutoffK > 0 ? OPEN_CUTOFF / (1 + distance * cutoffK) : OPEN_CUTOFF\n const occluded = occlusion > 0 ? byDistance / (1 + occlusion * 9) : byDistance\n return Math.max(80, Math.min(OPEN_CUTOFF, occluded))\n}\n\n/** Every file a sound may play (to load before its first play). */\nexport function sampleUrls(sound: SampleSound): string[] {\n const tiers = (sound.tiers ?? []).flatMap((tier) => [...tier.close, ...(tier.far ?? [])])\n const all = [...sound.close, ...(sound.far ?? []), ...tiers, ...(sound.tail?.indoor ?? []), ...(sound.tail?.outdoor ?? [])].map((ref) => ref.url)\n return [...new Set(all)]\n}\n\n/** The tier for an intensity: the last whose `from` is at or below it. */\nexport function tierFor(sound: SampleSound, intensity: number | undefined): SampleTier | undefined {\n if (intensity === undefined || !sound.tiers) return undefined\n let chosen: SampleTier | undefined\n for (const tier of sound.tiers) if (tier.from <= intensity) chosen = tier\n return chosen ?? sound.tiers[0]\n}\n\n/**\n * The plan of one play, or `null` when the sound is too far to be heard. Random numbers, in order: the pitch, the near take, the far take, the\n * tail take (each drawn only when that layer has more than zero takes and is heard).\n */\nexport function planSample(sound: SampleSound, input: SamplePlanInput): SamplePlan | null {\n if (sound.close.length === 0) throw new Error(`sample sound ${sound.id} has no close take`)\n const listener = input.listener ?? DEFAULT_LISTENER\n const distance = input.distance ?? (input.position ? listenerDistance(listener, input.position, input.distanceMode) : 0)\n const falloff = sound.falloff ?? DEFAULT_SAMPLE_FALLOFF\n const occlusion = Math.max(0, Math.min(1, input.occlusion ?? 0))\n const level = falloffGain(falloff, (input.volume ?? 1) * (sound.gain ?? 1), distance) * (1 - 0.45 * occlusion)\n if (isSilent(falloff, level) || level <= 0) return null\n\n const pitch = sound.pitch ?? DEFAULT_SAMPLE_PITCH\n const rate = pitch > 0 ? 1 + (input.random() * 2 - 1) * pitch : 1\n const environment = input.environment ?? 'outdoor'\n const tier = tierFor(sound, input.intensity)\n const close = tier?.close.length ? tier.close : sound.close\n const far = tier?.far?.length ? tier.far : (sound.far ?? [])\n const farMix = far.length > 0 ? farMixAt(sound.crossover ?? DEFAULT_CROSSOVER, distance) : 0\n const gains = crossGains(farMix)\n const layers: PlannedSampleLayer[] = []\n const take = (role: SampleLayerRole, refs: readonly SampleRef[], gain: number, at: number): void => {\n if (refs.length === 0 || gain < LAYER_FLOOR) return\n const key = `${sound.id}/${tier && role !== 'tail' ? `${tier.name}/` : ''}${role}`\n const index = pickTake(refs.length, input.memory?.get(key), input.random)\n input.memory?.set(key, index)\n const ref = refs[index] as SampleRef\n layers.push({ role, url: ref.url, take: index, gain: gain * (ref.gain ?? 1) * level, rate, at })\n }\n take('close', close, gains.close, 0)\n take('far', far, gains.far, 0)\n const tails = sound.tail?.[environment] ?? []\n take('tail', tails, sound.tail?.gain ?? DEFAULT_TAIL_GAIN, sound.tail?.at ?? 0)\n\n const pan = (sound.pan ?? true) && input.position ? panFor(listener, input.position) : undefined\n return {\n kind: 'sample',\n id: sound.id,\n bus: sound.bus,\n level,\n distance,\n ...(pan === undefined ? {} : { pan }),\n cutoff: sampleCutoff(sound.cutoffK ?? DEFAULT_SAMPLE_CUTOFF_K, distance, occlusion),\n rate,\n environment,\n ...(tier ? { tier: tier.name } : {}),\n farMix,\n layers,\n priority: sound.priority ?? input.priority ?? busPriority(sound.bus),\n ...(sound.group ? { group: sound.group } : {}),\n }\n}\n","/**\n * The calibration sound of the measuring harness: a sample sound made by the kit in code (no file, no licence), with every layer the criteria ask\n * for, so the harness can prove the whole file path (bytes → decode → plan → WebAudio) before any real file exists. Each take is a WAV built here:\n * an attack on the first sample (a click and a short noise burst over a low thump that decays), four near takes with their own pitch and noise, a far\n * take (darker, slower attack of the echo), light and heavy tiers and the two tails (a short dense room, a long thin field).\n */\nimport { createRng } from '../rng'\nimport type { SampleSound } from '../sample'\nimport type { SampleLoader } from '../webaudio/sample-store'\n\nexport const CALIBRATION_ID = 'calibration_shot'\nexport const CALIBRATION_RATE = 48000\n\n/** 16-bit PCM mono WAV bytes of the samples (clamped to ±1). */\nexport function encodeWav(samples: Float32Array, sampleRate = CALIBRATION_RATE): ArrayBuffer {\n const bytes = new ArrayBuffer(44 + samples.length * 2)\n const view = new DataView(bytes)\n const text = (at: number, value: string): void => {\n for (let index = 0; index < value.length; index++) view.setUint8(at + index, value.charCodeAt(index))\n }\n text(0, 'RIFF')\n view.setUint32(4, 36 + samples.length * 2, true)\n text(8, 'WAVE')\n text(12, 'fmt ')\n view.setUint32(16, 16, true)\n view.setUint16(20, 1, true)\n view.setUint16(22, 1, true)\n view.setUint32(24, sampleRate, true)\n view.setUint32(28, sampleRate * 2, true)\n view.setUint16(32, 2, true)\n view.setUint16(34, 16, true)\n text(36, 'data')\n view.setUint32(40, samples.length * 2, true)\n for (let index = 0; index < samples.length; index++) {\n const value = Math.max(-1, Math.min(1, samples[index] as number))\n view.setInt16(44 + index * 2, value < 0 ? value * 0x8000 : value * 0x7fff, true)\n }\n return bytes\n}\n\ntype Shot = { readonly seconds: number; readonly thump: number; readonly noise: number; readonly decay: number; readonly brightness: number; readonly gain: number; readonly seed: number; readonly attack?: number }\n\n/** One take: a thump (sine glide) and a noise burst, both decaying, smoothed by a one-pole lowpass (`brightness` 0..1), faded out at the end. */\nexport function shotSamples(shot: Shot, sampleRate = CALIBRATION_RATE): Float32Array {\n const random = createRng(shot.seed)\n const length = Math.round(shot.seconds * sampleRate)\n const samples = new Float32Array(length)\n let low = 0\n let phase = 0\n const attack = Math.max(1, Math.round((shot.attack ?? 0) * sampleRate))\n for (let index = 0; index < length; index++) {\n const time = index / sampleRate\n const envelope = Math.exp(-time / shot.decay) * Math.min(1, (index + 1) / attack)\n phase += (2 * Math.PI * shot.thump * (1 + 0.6 * Math.exp(-time * 30))) / sampleRate\n const noise = random() * 2 - 1\n low += shot.brightness * (noise - low)\n const fade = Math.min(1, (length - index) / (0.01 * sampleRate))\n samples[index] = shot.gain * envelope * fade * (0.55 * Math.sin(phase) + shot.noise * low)\n }\n return samples\n}\n\nconst TAKES: Readonly<Record<string, Shot>> = {\n 'close_1.wav': { seconds: 0.4, thump: 150, noise: 1, decay: 0.06, brightness: 0.9, gain: 0.85, seed: 1 },\n 'close_2.wav': { seconds: 0.4, thump: 160, noise: 1, decay: 0.065, brightness: 0.85, gain: 0.85, seed: 2 },\n 'close_3.wav': { seconds: 0.4, thump: 142, noise: 1, decay: 0.055, brightness: 0.95, gain: 0.85, seed: 3 },\n 'close_4.wav': { seconds: 0.4, thump: 170, noise: 1, decay: 0.07, brightness: 0.8, gain: 0.85, seed: 4 },\n 'far_1.wav': { seconds: 0.9, thump: 90, noise: 0.8, decay: 0.2, brightness: 0.08, gain: 0.7, seed: 5, attack: 0.004 },\n 'far_2.wav': { seconds: 0.9, thump: 95, noise: 0.8, decay: 0.22, brightness: 0.07, gain: 0.7, seed: 6, attack: 0.004 },\n 'light_1.wav': { seconds: 0.25, thump: 220, noise: 0.6, decay: 0.03, brightness: 0.6, gain: 0.35, seed: 7 },\n 'light_2.wav': { seconds: 0.25, thump: 230, noise: 0.6, decay: 0.03, brightness: 0.55, gain: 0.35, seed: 8 },\n 'heavy_1.wav': { seconds: 0.6, thump: 110, noise: 1.2, decay: 0.11, brightness: 0.95, gain: 0.95, seed: 9 },\n 'heavy_2.wav': { seconds: 0.6, thump: 105, noise: 1.2, decay: 0.12, brightness: 0.9, gain: 0.95, seed: 10 },\n 'tail_in.wav': { seconds: 0.5, thump: 0, noise: 1, decay: 0.08, brightness: 0.4, gain: 0.25, seed: 11, attack: 0.01 },\n 'tail_out.wav': { seconds: 2, thump: 0, noise: 1, decay: 0.45, brightness: 0.25, gain: 0.2, seed: 12, attack: 0.02 },\n 'loop_1.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.5, gain: 0.5, seed: 13, attack: 0.01 },\n 'loop_2.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.45, gain: 0.5, seed: 14, attack: 0.01 },\n 'loop_3.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.55, gain: 0.5, seed: 15, attack: 0.01 },\n}\n\nconst PREFIX = 'calibration/'\nconst url = (name: string): string => `${PREFIX}${name}`\n\n/** The calibration sound (weapons bus, every layer, fallback to the game's pistol noise class). */\nexport const CALIBRATION_SOUND: SampleSound = {\n id: CALIBRATION_ID,\n bus: 'weapons',\n close: ['close_1.wav', 'close_2.wav', 'close_3.wav', 'close_4.wav'].map((name) => ({ url: url(name) })),\n far: ['far_1.wav', 'far_2.wav'].map((name) => ({ url: url(name) })),\n tiers: [\n { name: 'light', from: 0, close: ['light_1.wav', 'light_2.wav'].map((name) => ({ url: url(name) })) },\n { name: 'medium', from: 0.34, close: ['close_1.wav', 'close_2.wav', 'close_3.wav', 'close_4.wav'].map((name) => ({ url: url(name) })) },\n { name: 'heavy', from: 0.67, close: ['heavy_1.wav', 'heavy_2.wav'].map((name) => ({ url: url(name) })) },\n ],\n tail: { indoor: [{ url: url('tail_in.wav') }], outdoor: [{ url: url('tail_out.wav') }] },\n pitch: 0.04,\n choke: { voices: 2 },\n fallback: 'sfx_pistol',\n sources: ['sdk: calibration takes synthesized by the harness (measure/calibration.ts), no file, no licence'],\n}\n\nexport const CALIBRATION_LOOP_ID = 'calibration_loop'\n\n/** A steady hiss in three 0.6 s takes, crossed in 0.15 s: the loop the harness checks for seams (no dip, no gap where two takes meet). */\nexport const CALIBRATION_LOOP_SOUND: SampleSound = {\n id: CALIBRATION_LOOP_ID,\n bus: 'ambience',\n close: ['loop_1.wav', 'loop_2.wav', 'loop_3.wav'].map((name) => ({ url: url(name) })),\n loop: { crossfade: 0.15 },\n sources: ['sdk: calibration takes synthesized by the harness (measure/calibration.ts), no file, no licence'],\n}\n\n/** Whether a url is one of the calibration takes. */\nexport const isCalibrationUrl = (url: string): boolean => url.startsWith(PREFIX)\n\n/** Bytes of the calibration takes (made on demand, the same for the same name). Falls through to `next` for any other url. */\nexport function calibrationLoader(next?: SampleLoader): SampleLoader {\n const made = new Map<string, ArrayBuffer>()\n return async (requested) => {\n if (!requested.startsWith(PREFIX)) {\n if (next) return next(requested)\n throw new Error(`not a calibration file: ${requested}`)\n }\n const name = requested.slice(PREFIX.length)\n const shot = TAKES[name]\n if (!shot) throw new Error(`no calibration take ${name}`)\n let bytes = made.get(name)\n if (!bytes) {\n bytes = encodeWav(shotSamples(shot))\n made.set(name, bytes)\n }\n // decodeAudioData detaches what it gets: every load gets its own copy\n return bytes.slice(0)\n }\n}\n","import type { LoopRecipe, SoundBank, SoundRecipe, SoundSet } from './recipe'\nimport type { SampleSound } from './sample'\n\nexport type DeepPartial<TValue> = TValue extends readonly unknown[] ? TValue : TValue extends object ? { readonly [Key in keyof TValue]?: DeepPartial<TValue[Key]> } : TValue\n\n/** Every sound and loop the engine knows, by id. Banks register in order; a later bank replaces an earlier recipe with the same id. */\nexport type SoundRegistry = {\n register(bank: SoundBank): void\n /** Merged into the recipe by id (objects merge, arrays such as `layers` are replaced); an unknown id is ignored. */\n patch(id: string, patch: DeepPartial<SoundRecipe> | DeepPartial<LoopRecipe> | DeepPartial<SampleSound>): void\n remove(id: string): void\n sound(id: string): SoundRecipe | undefined\n loop(id: string): LoopRecipe | undefined\n /** The set an id names (`SoundBank.sets`), if any; a recipe with the same id wins in `play`. */\n set(id: string): SoundSet | undefined\n sample(id: string): SampleSound | undefined\n soundIds(): string[]\n setIds(): string[]\n loopIds(): string[]\n sampleIds(): string[]\n /** Which bank each id came from. */\n bankOf(id: string): string | undefined\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// keys keep their place, so a patched range is still drawn where it was\nfunction mergeRecords(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = merged[key]\n merged[key] = isPlainObject(current) && isPlainObject(value) ? mergeRecords(current, value) : value\n }\n return merged\n}\n\nexport function createSoundRegistry(banks: readonly SoundBank[] = []): SoundRegistry {\n const sounds = new Map<string, SoundRecipe>()\n const loops = new Map<string, LoopRecipe>()\n const sets = new Map<string, SoundSet>()\n const samples = new Map<string, SampleSound>()\n const owners = new Map<string, string>()\n const registry: SoundRegistry = {\n register(bank) {\n for (const sound of bank.sounds ?? []) {\n sounds.set(sound.id, sound)\n owners.set(sound.id, bank.id)\n }\n for (const loop of bank.loops ?? []) {\n loops.set(loop.id, loop)\n owners.set(loop.id, bank.id)\n }\n for (const set of bank.sets ?? []) {\n if (set.variants.length === 0) throw new Error(`sound set ${set.id} has no variant`)\n sets.set(set.id, set)\n owners.set(set.id, bank.id)\n }\n for (const sample of bank.samples ?? []) {\n samples.set(sample.id, sample)\n owners.set(sample.id, bank.id)\n }\n },\n patch(id, patch) {\n const sound = sounds.get(id)\n if (sound) sounds.set(id, mergeRecords(sound, patch as Record<string, unknown>) as SoundRecipe)\n const loop = loops.get(id)\n if (loop) loops.set(id, mergeRecords(loop, patch as Record<string, unknown>) as LoopRecipe)\n const sample = samples.get(id)\n if (sample) samples.set(id, mergeRecords(sample, patch as Record<string, unknown>) as SampleSound)\n },\n remove(id) {\n sounds.delete(id)\n loops.delete(id)\n sets.delete(id)\n samples.delete(id)\n owners.delete(id)\n },\n sound: (id) => sounds.get(id),\n loop: (id) => loops.get(id),\n set: (id) => sets.get(id),\n sample: (id) => samples.get(id),\n soundIds: () => [...sounds.keys()],\n setIds: () => [...sets.keys()],\n loopIds: () => [...loops.keys()],\n sampleIds: () => [...samples.keys()],\n bankOf: (id) => owners.get(id),\n }\n for (const bank of banks) registry.register(bank)\n return registry\n}\n","[\n {\n \"id\": \"game\",\n \"master\": 0.5,\n \"noise\": {\n \"seconds\": 1.5,\n \"create\": \"lazy\"\n },\n \"sources\": [\n \"jogo:L62077-62081 master 0.5 to the output\",\n \"jogo:L62082-62088 noise 1.5 s made by the first sound that needs it\"\n ]\n },\n {\n \"id\": \"art_scene\",\n \"master\": 0.85,\n \"compressor\": {\n \"threshold\": -12,\n \"ratio\": 5\n },\n \"reverb\": {\n \"seconds\": 2.2,\n \"decay\": 3.4,\n \"wet\": 0.4\n },\n \"noise\": {\n \"seconds\": 2,\n \"create\": \"eager\"\n },\n \"sources\": [\n \"cena:L1308 compressor -12 dB, ratio 5\",\n \"cena:L1309 master 0.85\",\n \"cena:L1310 convolver, impulse 2.2 s of (1 - i/len)^3.4\",\n \"cena:L1311 wet 0.4\",\n \"cena:L1312 noise 2 s made with the chain\"\n ]\n },\n {\n \"id\": \"kit\",\n \"master\": 0.85,\n \"compressor\": {\n \"threshold\": -12,\n \"ratio\": 5\n },\n \"reverb\": {\n \"seconds\": 2.2,\n \"decay\": 3.4,\n \"wet\": 0.4\n },\n \"noise\": {\n \"seconds\": 2,\n \"create\": \"eager\"\n },\n \"sources\": [\n \"sdk: the art scene chain (cena L1308-L1312) with a limiter after the compressor: the page has none, and a blast with its debris and a fire catching reached +7 dBFS\"\n ],\n \"limiter\": {\n \"ceiling\": -1,\n \"knee\": -6\n }\n }\n]\n","import mixProfilesJson from './data/mix-profiles.json'\nimport type { BusId } from './recipe'\n\nexport type BusSetting = { readonly gain?: number; readonly muted?: boolean }\n\n/**\n * A mixing chain. `master` → (compressor) → (limiter) → output; with `reverb`, a wet bus → convolver (an impulse from the engine's seed) → master. `noise` is\n * the shared noise buffer: its length, and whether it is made with the chain (`eager`, the art scene) or by the first sound that needs it (`lazy`,\n * the game). Buses sit under the master and have no node until one is changed.\n */\nexport type MixProfile = {\n readonly id: string\n readonly master: number\n readonly compressor?: { readonly threshold: number; readonly ratio: number; readonly knee?: number; readonly attack?: number; readonly release?: number }\n readonly reverb?: { readonly seconds: number; readonly decay: number; readonly wet: number }\n /**\n * A last stage after the compressor that keeps every peak under `ceiling` dBFS: below `knee` dBFS the sound passes untouched, above it the peak\n * bends smoothly toward the ceiling (a soft clipper, no lookahead and no delay), so a blast with its debris and a fire catching all at once never\n * clips the output. `range` is the loudest input it shapes, as a factor of full scale (default 4, +12 dB); louder is held at the ceiling.\n */\n readonly limiter?: { readonly ceiling: number; readonly knee: number; readonly range?: number }\n readonly noise: { readonly seconds: number; readonly create: 'lazy' | 'eager' }\n readonly buses?: Readonly<Partial<Record<BusId, BusSetting>>>\n readonly sources: readonly string[]\n}\n\n/** The two team chains: `game` (master 0.5, jogo L62080) and `art_scene` (compressor and reverb, cena L1305–1313). */\nexport const MIX_PROFILES: Readonly<Record<string, MixProfile>> = Object.fromEntries(\n (mixProfilesJson as unknown as readonly MixProfile[]).map((profile) => [profile.id, profile]),\n)\n/** Q1: the kit plays through the art scene chain (compressor and reverb) with a limiter at the end (`kit`); `mix: 'art_scene'` is the page as it was, `mix: 'game'` the game's. */\nexport const DEFAULT_MIX = 'kit'\n\n/** A profile by id from `profiles`, or the profile itself. */\nexport function resolveMix(mix: string | MixProfile, profiles: Readonly<Record<string, MixProfile>> = MIX_PROFILES): MixProfile {\n if (typeof mix !== 'string') return mix\n const profile = profiles[mix]\n if (!profile) throw new Error(`game-audio: unknown mix profile \"${mix}\" (known: ${Object.keys(profiles).join(', ')})`)\n return profile\n}\n\n/** The gain a bus plays at: 0 when muted, its gain (default 1) otherwise. */\nexport function busGain(setting: BusSetting | undefined): number {\n if (!setting) return 1\n return setting.muted ? 0 : (setting.gain ?? 1)\n}\n","/** `length` samples of white noise, `random × 2 − 1`, drawn in order (jogo L62086, cena L1312). */\nexport function fillNoise(random: () => number, length: number): Float32Array {\n const samples = new Float32Array(length)\n for (let index = 0; index < length; index++) samples[index] = random() * 2 - 1\n return samples\n}\n\n/**\n * A reverb impulse: per channel, noise times `(1 − i / length)^decay` (cena L1310). `length` is `sampleRate × seconds` as the art scene computes it,\n * which is not always whole (48000 × 2.2 = 105600.00000000001): the loop runs while `i < length`, so one more number is drawn than the buffer holds,\n * exactly like the team code. The power is `exp(decay × log(base))`, which every engine computes the same.\n */\nexport function fillImpulse(random: () => number, options: { readonly channels: number; readonly length: number; readonly decay: number }): Float32Array[] {\n const size = Math.floor(options.length)\n return Array.from({ length: options.channels }, () => {\n const samples = new Float32Array(size)\n for (let index = 0; index < options.length; index++) {\n const value = (random() * 2 - 1) * Math.exp(options.decay * Math.log(1 - index / options.length))\n if (index < size) samples[index] = value\n }\n return samples\n })\n}\n\n/** An AudioBuffer holding the samples (one channel per array). */\nexport function bufferOf(context: AudioContext, channels: readonly Float32Array[], requestedLength: number): AudioBuffer {\n const buffer = context.createBuffer(channels.length, requestedLength, context.sampleRate)\n channels.forEach((samples, channel) => buffer.getChannelData(channel).set(samples))\n return buffer\n}\n","import type { MixProfile } from '../mix'\nimport { bufferOf, fillImpulse } from './noise'\n\nexport type MixChain = { readonly master: GainNode; readonly wet?: GainNode; disconnect(): void }\n\nconst LIMITER_POINTS = 4097\n\n/**\n * The limiter's curve over inputs `-range..range` (full scale 1): untouched up to the knee, then `knee + (ceiling − knee) × tanh((|x| − knee) / (ceiling − knee))`,\n * which leaves the knee with the same slope and never passes the ceiling.\n */\nexport function limiterCurve(ceilingDb: number, kneeDb: number, range: number, points = LIMITER_POINTS): Float32Array<ArrayBuffer> {\n const ceiling = 10 ** (ceilingDb / 20)\n const knee = Math.min(10 ** (kneeDb / 20), ceiling)\n const curve = new Float32Array(new ArrayBuffer(points * 4))\n for (let i = 0; i < points; i++) {\n const x = ((i / (points - 1)) * 2 - 1) * range\n const a = Math.abs(x)\n const y = a <= knee || ceiling === knee ? Math.min(a, ceiling) : knee + (ceiling - knee) * Math.tanh((a - knee) / (ceiling - knee))\n curve[i] = Math.sign(x) * y\n }\n return curve\n}\n\n/**\n * The mixing chain in the team order (cena L1308–1311; jogo L62080): compressor to the output, master into it (or straight to the output), then the\n * convolver with an impulse drawn from `random` and the wet bus into it, back into the master.\n */\nexport function buildChain(context: AudioContext, profile: MixProfile, random: () => number): MixChain {\n // the limiter is the last stage: a gain that brings `range` × full scale into the shaper's -1..1, and a curve that gives the level back, bent above the knee\n let limiter: { readonly input: GainNode; readonly shaper: WaveShaperNode } | undefined\n if (profile.limiter) {\n const range = profile.limiter.range ?? 4\n const input = context.createGain()\n input.gain.value = 1 / range\n const shaper = context.createWaveShaper()\n shaper.curve = limiterCurve(profile.limiter.ceiling, profile.limiter.knee, range)\n input.connect(shaper)\n shaper.connect(context.destination)\n limiter = { input, shaper }\n }\n const output: AudioNode = limiter?.input ?? context.destination\n let compressor: DynamicsCompressorNode | undefined\n if (profile.compressor) {\n compressor = context.createDynamicsCompressor()\n compressor.threshold.value = profile.compressor.threshold\n compressor.ratio.value = profile.compressor.ratio\n if (profile.compressor.knee !== undefined) compressor.knee.value = profile.compressor.knee\n if (profile.compressor.attack !== undefined) compressor.attack.value = profile.compressor.attack\n if (profile.compressor.release !== undefined) compressor.release.value = profile.compressor.release\n compressor.connect(output)\n }\n const master = context.createGain()\n master.gain.value = profile.master\n master.connect(compressor ?? output)\n if (!profile.reverb) {\n return {\n master,\n disconnect: () => {\n master.disconnect()\n compressor?.disconnect()\n limiter?.input.disconnect()\n limiter?.shaper.disconnect()\n },\n }\n }\n const convolver = context.createConvolver()\n const length = context.sampleRate * profile.reverb.seconds\n convolver.buffer = bufferOf(context, fillImpulse(random, { channels: 2, length, decay: profile.reverb.decay }), length)\n const wet = context.createGain()\n wet.gain.value = profile.reverb.wet\n wet.connect(convolver)\n convolver.connect(master)\n return {\n master,\n wet,\n disconnect: () => {\n wet.disconnect()\n convolver.disconnect()\n master.disconnect()\n compressor?.disconnect()\n limiter?.input.disconnect()\n limiter?.shaper.disconnect()\n },\n }\n}\n","type AudioContextConstructor = new () => AudioContext\n\n/** A new context from the page (`AudioContext` or the old `webkitAudioContext`), or `null` in Node and workers. */\nexport function globalContext(): AudioContext | null {\n const scope = globalThis as { AudioContext?: AudioContextConstructor; webkitAudioContext?: AudioContextConstructor }\n const Constructor = scope.AudioContext ?? scope.webkitAudioContext\n return Constructor ? new Constructor() : null\n}\n\n/** Browsers start a context suspended until a click or key; call from one. */\nexport function unlockContext(context: AudioContext): void {\n // an OfflineAudioContext (no `close`) is started by `startRendering`, never resumed\n if (context.state === 'suspended' && typeof context.close === 'function') void context.resume()\n}\n","import type { LoopRecipe } from './recipe'\n\n/** jogo L62112: a loop's nodes exist only once its volume reaches 0.002. */\nexport const LOOP_START_ABOVE = 0.002\n/** jogo L62125–62126: `setTargetAtTime` time constants. */\nexport const LOOP_SMOOTHING = { volume: 0.15, frequency: 0.08 } as const\n\n/** What the realizer does for one `set`: create the nodes first (once), then glide the volume and, for an oscillator, the frequency. */\nexport type LoopAction = { readonly create: boolean; readonly volume: number; readonly frequency?: number }\n\nexport type LoopState = {\n /** `null` while the loop has no nodes and the volume is still below the start threshold. */\n set(state: { readonly volume?: number; readonly frequency?: number }): LoopAction | null\n /** Whether the nodes exist. */\n readonly created: boolean\n /** The nodes were torn down (`stop`): the next audible `set` creates them again. */\n reset(): void\n}\n\n/**\n * The game's `loopSet` as state: nodes on the first volume at or above `startAbove`, then every `set` glides. The volume set last is kept, so a\n * `set` of only the frequency keeps the level. `chain_loop` recipes open with their nodes already made (`open` is true).\n */\nexport function createLoopState(recipe: LoopRecipe, open = false): LoopState {\n const startAbove = recipe.startAbove ?? LOOP_START_ABOVE\n let created = open\n let volume = recipe.volume ?? 0\n return {\n set(state) {\n volume = state.volume ?? volume\n const create = !created\n if (create && !(volume >= startAbove)) return null\n created = true\n const frequency = recipe.source.kind === 'osc' && state.frequency ? state.frequency : undefined\n return { create, volume, ...(frequency === undefined ? {} : { frequency }) }\n },\n get created() {\n return created\n },\n reset() {\n created = false\n },\n }\n}\n","import type { PlannedAutomation, PlannedEnvelopePoint, PlannedFilter } from '../plan'\n\n/** Where a plan is built: the context, the bus it plays into, the reverb send (if the mix has one), the shared noise and the start time. */\nexport type RealizeTarget = {\n readonly context: AudioContext\n readonly output: AudioNode\n readonly wet?: AudioNode\n /** The noise buffer; made on the first call when the mix makes it on demand. */\n readonly noise: () => AudioBuffer\n readonly time: number\n}\n\n/** What `realize` built: every scheduled source (so the voice can be cut short) and `stop`. */\nexport type RealizedVoice = { readonly sources: readonly AudioScheduledSourceNode[]; stop(): void }\n\n/** `.value = value`, or `setValueAtTime(from)` at `time`. */\nexport function assign(param: AudioParam, automation: PlannedAutomation, time: number): void {\n if (automation.value !== undefined) param.value = automation.value\n if (automation.from !== undefined) param.setValueAtTime(automation.from, time)\n}\n\nexport function ramp(param: AudioParam, curve: 'set' | 'linear' | 'exp', value: number, at: number): void {\n if (curve === 'set') param.setValueAtTime(value, at)\n else if (curve === 'exp') param.exponentialRampToValueAtTime(value, at)\n else param.linearRampToValueAtTime(value, at)\n}\n\n/** The ramp of an automation, if it has one. */\nexport function rampTo(param: AudioParam, automation: PlannedAutomation, time: number): void {\n if (automation.to !== undefined && automation.at !== undefined) ramp(param, automation.curve ?? 'linear', automation.to, time + automation.at)\n}\n\nexport function applyEnvelope(param: AudioParam, points: readonly PlannedEnvelopePoint[], time: number): void {\n for (const point of points) ramp(param, point.curve, point.value, time + point.time)\n}\n\n/** A noise source on the shared buffer (`loop` set only when asked, as the art scene's `nsrc` does). */\nexport function noiseSource(target: RealizeTarget, loop: boolean): AudioBufferSourceNode {\n const source = target.context.createBufferSource()\n source.buffer = target.noise()\n if (loop) source.loop = true\n return source\n}\n\n/** The art scene's `bq`: type, frequency, then Q and gain when given. The frequency ramp is left to the caller. */\nexport function filterNode(context: AudioContext, filter: PlannedFilter, time: number): BiquadFilterNode {\n const node = context.createBiquadFilter()\n node.type = filter.type\n assign(node.frequency, filter.frequency, time)\n if (filter.q !== undefined) node.Q.value = filter.q\n if (filter.gain !== undefined) node.gain.value = filter.gain\n return node\n}\n\nexport function gainNode(context: AudioContext, value: number): GainNode {\n const node = context.createGain()\n node.gain.value = value\n return node\n}\n\nexport function voiceOf(sources: readonly AudioScheduledSourceNode[]): RealizedVoice {\n return {\n sources,\n stop() {\n for (const source of sources) {\n try {\n source.stop()\n } catch {\n // already stopped\n }\n }\n },\n }\n}\n","// Loop nodes in the two team orders: the game's `loopSet` (jogo L62109–62127) and the art scene's loops in `initAudio` (cena L1314–1316).\nimport type { Automation, LoopRecipe, Range } from '../recipe'\nimport { filterNode, gainNode, noiseSource } from './nodes'\nimport type { RealizeTarget } from './nodes'\n\nexport type RealizedLoop = {\n readonly gain: GainNode\n /** The node wired to the bus: the panner when the recipe pans, else the gain. */\n readonly out: AudioNode\n readonly panner?: StereoPannerNode\n readonly source: AudioScheduledSourceNode\n readonly frequency?: AudioParam\n /** The first filter's cutoff, for `set({ cutoff })`. */\n readonly cutoff?: AudioParam\n stop(): void\n}\n\n// a panning loop goes gain → panner → bus; the others keep the team wiring (gain → bus)\nfunction outputStage(recipe: LoopRecipe, target: RealizeTarget, gain: GainNode): { out: AudioNode; panner?: StereoPannerNode } {\n if (!recipe.pan) {\n gain.connect(target.output)\n return { out: gain }\n }\n const panner = target.context.createStereoPanner()\n gain.connect(panner)\n panner.connect(target.output)\n return { out: panner, panner }\n}\n\n// loops take fixed numbers: a range or a param in a loop recipe reads as 0\nconst fixed = (range: Range | undefined): number => (typeof range === 'number' ? range : 0)\nconst fixedFrequency = (automation: Automation): number => fixed('set' in automation ? automation.set : automation.from)\n\nfunction sourceOf(recipe: LoopRecipe, target: RealizeTarget): { source: AudioScheduledSourceNode; frequency?: AudioParam } {\n if (recipe.source.kind === 'noise') return { source: noiseSource(target, true) }\n const oscillator = target.context.createOscillator()\n oscillator.type = recipe.source.wave\n if (recipe.source.frequency) oscillator.frequency.value = fixedFrequency(recipe.source.frequency)\n return { source: oscillator, frequency: oscillator.frequency }\n}\n\nfunction stopAll(sources: readonly AudioScheduledSourceNode[]): () => void {\n return () => {\n for (const source of sources) {\n try {\n source.stop()\n } catch {\n // already stopped\n }\n }\n }\n}\n\n/** `loopSet` on first use: gain from 0 and filter wired first, the source and filter set, an optional blade-beat stage, then the source starts. */\nexport function realizeGameLoop(recipe: LoopRecipe, target: RealizeTarget): RealizedLoop {\n const { context } = target\n const gain = context.createGain()\n const filters = (recipe.filters?.bank ?? []).map(() => context.createBiquadFilter())\n gain.gain.value = 0\n const last = filters.reduce<AudioNode | undefined>((previous, filter) => (previous ? previous.connect(filter) : filter), undefined)\n last?.connect(gain)\n const output = outputStage(recipe, target, gain)\n const { source, frequency } = sourceOf(recipe, target)\n recipe.filters?.bank.forEach((spec, index) => {\n const filter = filters[index] as BiquadFilterNode\n filter.type = spec.type\n filter.frequency.value = fixedFrequency(spec.frequency)\n if (spec.q !== undefined) filter.Q.value = fixed(spec.q)\n })\n const sources: AudioScheduledSourceNode[] = [source]\n for (const modulator of recipe.modulators ?? []) {\n const lfo = context.createOscillator()\n const depth = context.createGain()\n const stage = context.createGain()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = fixed(modulator.rate)\n depth.gain.value = fixed(modulator.depth as Range)\n stage.gain.value = modulator.base ?? 0\n lfo.connect(depth)\n depth.connect(stage.gain)\n last?.disconnect()\n last?.connect(stage)\n stage.connect(gain)\n lfo.start()\n sources.push(lfo)\n }\n source.connect(filters[0] ?? gain)\n source.start()\n return { gain, ...output, source, ...(frequency ? { frequency } : {}), ...(filters[0] ? { cutoff: filters[0].frequency } : {}), stop: stopAll(sources) }\n}\n\n/** The art scene's loops: source, filters, gain at its starting volume, a gain LFO, wired, started. */\nexport function realizeChainLoop(recipe: LoopRecipe, target: RealizeTarget, volume: number): RealizedLoop {\n const { context } = target\n const { source, frequency } = sourceOf(recipe, target)\n const filters = (recipe.filters?.bank ?? []).map((spec) =>\n filterNode(context, { type: spec.type, frequency: { value: fixedFrequency(spec.frequency) }, ...(spec.q === undefined ? {} : { q: fixed(spec.q) }) }, target.time),\n )\n const gain = gainNode(context, volume)\n const lfos = (recipe.modulators ?? []).map((modulator) => {\n const lfo = context.createOscillator()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = fixed(modulator.rate)\n const depth = gainNode(context, fixed(modulator.depth as Range))\n lfo.connect(depth)\n depth.connect(gain.gain)\n return lfo\n })\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(gain)\n const output = outputStage(recipe, target, gain)\n source.start()\n for (const lfo of lfos) lfo.start()\n return { gain, ...output, source, ...(frequency ? { frequency } : {}), ...(filters[0] ? { cutoff: filters[0].frequency } : {}), stop: stopAll([source, ...lfos]) }\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { cutoffDivisor, falloffGain } from '../falloff'\nimport { listenerDistance, panFor } from '../listener'\nimport type { DistanceMode, Listener } from '../listener'\nimport { LOOP_SMOOTHING, createLoopState } from '../loops'\nimport type { BusId, LoopRecipe } from '../recipe'\nimport type { RealizeTarget } from './nodes'\nimport { realizeChainLoop, realizeGameLoop } from './realize-loop'\nimport type { RealizedLoop } from './realize-loop'\n\n/**\n * What one `set` changes. `volume` and `frequency` glide as in the team loops. `position` places the loop: with a recipe `falloff` the level falls\n * with the distance from the listener (and the cutoff with `cutoffK`), with `pan` it goes to the listener's side. `cutoff` glides the first filter\n * (an engine opening up under load, a skid getting brighter).\n */\nexport type LoopSet = { readonly volume?: number; readonly frequency?: number; readonly position?: Vec3; readonly cutoff?: number }\n\n/** A continuous sound: `set` glides the volume and, for an oscillator, the frequency; `stop` tears the nodes down. */\nexport type AudioLoopHandle = {\n set(state: LoopSet): void\n stop(): void\n}\n\nexport type LoopEntry = { rewire(): void; stop(): void; readonly created: boolean }\n\n/** What a loop needs from its engine. */\nexport type LoopHost = {\n ready(): AudioContext | null\n output(bus: BusId): AudioNode\n prepareNoise(): unknown\n noise(): AudioBuffer\n register(loop: LoopEntry): void\n unregister(loop: LoopEntry): void\n /** Where the ears are now, for a loop with a `falloff` or `pan`. */\n listener?(): Listener\n readonly distance?: DistanceMode\n}\n\nconst INERT: AudioLoopHandle = { set() {}, stop() {} }\n\n/** A `game_loop` makes its nodes on the first audible `set`; a `chain_loop` makes them when it opens, at `volume` (default the recipe's). */\nexport function createLoopHandle(recipe: LoopRecipe | undefined, host: LoopHost, volume?: number): AudioLoopHandle {\n if (!recipe) return INERT\n const loopRecipe = recipe\n const isChain = loopRecipe.order === 'chain_loop'\n const opening = volume ?? loopRecipe.volume ?? 0\n const smoothing = loopRecipe.smoothing ?? LOOP_SMOOTHING\n let state = createLoopState(loopRecipe)\n let nodes: RealizedLoop | undefined\n\n const entry: LoopEntry = {\n get created() {\n return nodes !== undefined\n },\n rewire() {\n nodes?.out.disconnect()\n nodes?.out.connect(host.output(loopRecipe.bus))\n },\n stop() {\n nodes?.stop()\n nodes?.out.disconnect()\n nodes = undefined\n state = createLoopState(loopRecipe)\n host.unregister(entry)\n },\n }\n\n const create = (context: AudioContext, startVolume: number): RealizedLoop => {\n if (loopRecipe.source.kind === 'noise') host.prepareNoise()\n const target: RealizeTarget = { context, output: host.output(loopRecipe.bus), noise: host.noise, time: context.currentTime }\n const made = isChain ? realizeChainLoop(loopRecipe, target, startVolume) : realizeGameLoop(loopRecipe, target)\n host.register(entry)\n return made\n }\n\n const open = (): void => {\n const context = host.ready()\n if (!context) return\n nodes = create(context, opening)\n state = createLoopState({ ...loopRecipe, volume: opening }, true)\n }\n if (isChain) open()\n\n let position: Vec3 | undefined\n let cutoff: number | undefined\n const placed = loopRecipe.falloff !== undefined || loopRecipe.pan === true\n return {\n set(next) {\n if (isChain && !nodes) open()\n const context = host.ready()\n if (!context) return\n position = next.position ?? position\n cutoff = next.cutoff ?? cutoff\n const action = state.set(next)\n if (!action) return\n nodes ??= create(context, 0)\n const listener = placed && position ? host.listener?.() : undefined\n const distance = listener && position ? listenerDistance(listener, position, host.distance) : 0\n const level = listener ? falloffGain(loopRecipe.falloff, action.volume, distance) : action.volume\n nodes.gain.gain.setTargetAtTime(level, context.currentTime, smoothing.volume)\n if (action.frequency !== undefined && nodes.frequency) nodes.frequency.setTargetAtTime(action.frequency, context.currentTime, smoothing.frequency)\n if (cutoff !== undefined && nodes.cutoff) nodes.cutoff.setTargetAtTime(cutoff / cutoffDivisor(loopRecipe.falloff, distance), context.currentTime, smoothing.frequency)\n if (listener && position && nodes.panner) nodes.panner.pan.setTargetAtTime(panFor(listener, position), context.currentTime, smoothing.frequency)\n },\n stop: entry.stop,\n }\n}\n","/**\n * A continuous sound played from files (fire, rain, an engine idling): `SampleSound.loop` turns a sample sound into a loop that `engine.loop(id)` plays.\n * The takes are chained without a seam: each one starts `crossfade` seconds before the last one ends, the two crossed with equal-power ramps, and\n * the next take is drawn by the round-robin (never the same twice in a row while there are two or more). A take shorter than two crossfades\n * loops on itself (`AudioBufferSourceNode.loop`). While the files are not decoded the recipe loop of the fallback (or of the same id) plays, and\n * the files take over when they are ready, at the volume the loop has then.\n */\nimport { pickTake } from '../sample'\nimport type { BusId, SampleSound } from '../recipe'\nimport type { AudioLoopHandle, LoopEntry } from './engine-loop'\n\n/** The crossfade between two takes of a loop, in seconds, when `loop: true` gives none. */\nexport const DEFAULT_LOOP_CROSSFADE = 0.25\n/** Takes are scheduled until this far (seconds) past the clock, so a busy main thread (a heavy frame, a late timer) never leaves a gap. */\nconst LOOKAHEAD = 1.5\nconst VOLUME_SMOOTHING = 0.05\n\n/** The crossfade of a looping sample sound, or `undefined` when it does not loop. */\nexport function loopCrossfade(sound: SampleSound): number | undefined {\n if (!sound.loop) return undefined\n return sound.loop === true ? DEFAULT_LOOP_CROSSFADE : Math.max(0, sound.loop.crossfade ?? DEFAULT_LOOP_CROSSFADE)\n}\n\n/** Steps of the equal-power ramps (straight lines between points of the sine and cosine quarter). */\nexport const CROSSFADE_STEPS = 8\n\n/** The gain of an equal-power crossfade at `t` (0..1) for the take coming in; the take going out has the gain at `1 − t`. */\nexport const equalPowerIn = (t: number): number => Math.sin((Math.max(0, Math.min(1, t)) * Math.PI) / 2)\n\n// a quarter sine (in) or cosine (out) drawn as straight ramps, so it runs on any AudioParam (and on the recorder of the tests)\nconst ramp = (param: AudioParam, direction: 'in' | 'out', at: number, seconds: number): void => {\n const value = (t: number): number => (direction === 'in' ? equalPowerIn(t) : equalPowerIn(1 - t))\n param.setValueAtTime(value(0), at)\n for (let step = 1; step <= CROSSFADE_STEPS; step++) param.linearRampToValueAtTime(value(step / CROSSFADE_STEPS), at + (seconds * step) / CROSSFADE_STEPS)\n}\n\n/** What a sample loop needs from its engine. */\nexport type SampleLoopHost = {\n ready(): AudioContext | null\n /** The node sample voices of a bus go to (the limiter of the bus). */\n output(bus: BusId): AudioNode\n buffer(url: string): AudioBuffer | undefined\n isReady(sound: SampleSound): boolean\n /** Loads the files of the sound (resolves when they are decoded or failed). */\n load(sound: SampleSound): Promise<unknown>\n /** The recipe loop that plays while the files are not ready. */\n fallback(volume: number): AudioLoopHandle\n random(): number\n register(loop: LoopEntry): void\n unregister(loop: LoopEntry): void\n /** Whether a bus is muted now. */\n muted(bus: BusId): boolean\n}\n\ntype Segment = { readonly source: AudioBufferSourceNode; readonly gain: GainNode; readonly end: number }\n\n/** Plays a looping sample sound; falls back to the recipe loop while its files load. `volume` is the opening level (default 0, opened by `set`). */\nexport function createSampleLoopHandle(sound: SampleSound, host: SampleLoopHost, volume = 0): AudioLoopHandle {\n const crossfade = loopCrossfade(sound) ?? DEFAULT_LOOP_CROSSFADE\n let level = volume\n let stopped = false\n let fallback: AudioLoopHandle | undefined\n let master: GainNode | undefined\n let segments: Segment[] = []\n let last: number | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const entry: LoopEntry = {\n get created() {\n return master !== undefined\n },\n rewire() {\n master?.disconnect()\n master?.connect(host.output(sound.bus))\n },\n stop() {\n stopped = true\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n for (const segment of segments) {\n try {\n segment.source.stop()\n } catch {\n // already stopped\n }\n segment.source.disconnect()\n segment.gain.disconnect()\n }\n segments = []\n master?.disconnect()\n master = undefined\n fallback?.stop()\n fallback = undefined\n host.unregister(entry)\n },\n }\n\n const nextBuffer = (): AudioBuffer | undefined => {\n const takes = sound.close\n const take = pickTake(takes.length, last, host.random)\n last = take\n const ref = takes[take]\n return ref ? host.buffer(ref.url) : undefined\n }\n\n // schedules one take from `at`; returns when the next one starts\n const schedule = (context: AudioContext, output: AudioNode, at: number, first: boolean): number | undefined => {\n const buffer = nextBuffer()\n if (!buffer) return undefined\n const source = context.createBufferSource()\n source.buffer = buffer\n const gain = context.createGain()\n source.connect(gain)\n gain.connect(output)\n const fade = Math.min(crossfade, buffer.duration / 2)\n if (buffer.duration < 2 * crossfade || sound.close.length === 1) {\n // one take (or a take too short to cross): it loops on itself\n source.loop = true\n if (!first) ramp(gain.gain, 'in', at, Math.max(0.001, fade))\n source.start(at)\n segments.push({ source, gain, end: Number.POSITIVE_INFINITY })\n return undefined\n }\n if (first) gain.gain.setValueAtTime(1, at)\n else ramp(gain.gain, 'in', at, fade)\n const end = at + buffer.duration\n ramp(gain.gain, 'out', end - fade, fade)\n source.start(at)\n source.stop(end)\n segments.push({ source, gain, end })\n source.onended = () => {\n segments = segments.filter((segment) => segment.source !== source)\n source.disconnect()\n gain.disconnect()\n }\n return end - fade\n }\n\n const pump = (context: AudioContext, output: AudioNode, at: number, first: boolean): void => {\n if (stopped) return\n let next = schedule(context, output, at, first)\n // a late timer: catch up from the clock instead of stacking takes in the past\n while (next !== undefined && next < context.currentTime + LOOKAHEAD) next = schedule(context, output, Math.max(next, context.currentTime), false)\n if (next === undefined) return\n const wait = Math.max(0, (next - context.currentTime - LOOKAHEAD / 2) * 1000)\n timer = setTimeout(() => {\n timer = undefined\n pump(context, output, next, false)\n }, wait)\n }\n\n // the files play at the sound's own level (`SampleSound.gain`); the fallback recipe loop has its own\n const fileLevel = (): number => level * (sound.gain ?? 1)\n\n const startFiles = (): boolean => {\n if (stopped || master || !host.isReady(sound)) return master !== undefined\n const context = host.ready()\n if (!context) return false\n master = context.createGain()\n master.gain.setValueAtTime(fileLevel(), context.currentTime)\n master.connect(host.output(sound.bus))\n host.register(entry)\n pump(context, master, context.currentTime, true)\n if (fallback) {\n fallback.set({ volume: 0 })\n const old = fallback\n fallback = undefined\n setTimeout(() => old.stop(), VOLUME_SMOOTHING * 6000)\n }\n return true\n }\n\n const ensure = (): void => {\n if (stopped || master) return\n if (startFiles()) return\n if (!fallback) {\n fallback = host.fallback(level)\n void host\n .load(sound)\n .then(() => {\n if (level > 0 || master) startFiles()\n })\n .catch(() => undefined)\n }\n }\n\n if (volume > 0) ensure()\n\n return {\n set(next) {\n if (stopped) return\n if (next.volume !== undefined) level = host.muted(sound.bus) ? 0 : Math.max(0, next.volume)\n if (level > 0) ensure()\n const context = host.ready()\n if (master && context) master.gain.setTargetAtTime(fileLevel(), context.currentTime, VOLUME_SMOOTHING)\n fallback?.set(next.volume === undefined ? next : { ...next, volume: level })\n },\n stop: entry.stop,\n }\n}\n","import { bufferOf, fillNoise } from './noise'\n\n/** One noise buffer and the stream it is filled from. The samples are drawn before the sound that first needs them draws its own numbers. */\nexport type NoiseStore = { readonly random: () => number; samples?: Float32Array; buffer?: AudioBuffer; reset(): void }\n\nexport function createNoiseStore(random: () => number): NoiseStore {\n const store: NoiseStore = {\n random,\n reset() {\n store.samples = undefined\n store.buffer = undefined\n },\n }\n return store\n}\n\n/** Draws the samples (once): `sampleRate × seconds` of them, as the team code sizes its buffer. */\nexport function prepareNoise(store: NoiseStore, context: AudioContext, seconds: number): Float32Array {\n store.samples ??= fillNoise(store.random, Math.floor(context.sampleRate * seconds))\n return store.samples\n}\n\n/** The AudioBuffer (made on the first call, which is where the team code calls its `noise()`). */\nexport function noiseBuffer(store: NoiseStore, context: AudioContext, seconds: number): AudioBuffer {\n const samples = prepareNoise(store, context, seconds)\n store.buffer ??= bufferOf(context, [samples], context.sampleRate * seconds)\n return store.buffer\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n}\n\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\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 * `min(maxSpeed, sqrt(2 * energy * reach * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n const speed = Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * (blast.reach ?? 1) * 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","import { blastShove } from './blast-shove'\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\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}\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`: the shove of `game-contracts` taken at the chest, a hop when it goes up, and a fall when it is strong enough. Undefined when the blast does not\n * reach it. The numbers are the host's (`ModuleHost.blastShove`), the same ones that throw its loose items.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions): Knock | undefined {\n const hit = blastShove(blast, { position: [feet[0], feet[1] + CHEST, feet[2]], mass }, options)\n if (!hit) return undefined\n const [dx, dy, dz] = hit.direction\n return { velocity: [dx * hit.speed, Math.max(0, dy * hit.speed), dz * hit.speed], airborne: dy > 0, lying: 0, lieLeft: 0, down: hit.speed >= KNOCK_DOWN_SPEED }\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 if (moving) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else {\n knock.lying = 1\n 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 }\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","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present' },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n 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 wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n Dent,\n DestructibleSpec,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartShape,\n PartSpec,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { bodyMass, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, stepKnock } from './blast-knock'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, checkDeferredQueue } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, ModuleArea, ModuleHost, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\n","import { DEFERRED_QUEUE_ID } from '@adatechnology/game-contracts'\nimport type { DeferredQueue } from '@adatechnology/game-contracts'\n\n/** A sound waiting to be built: `run` builds it, `drop` gives its voice back when it waited too long to still make sense. */\nexport type StartJob = { readonly queuedAt: number; run(): void; drop(): void }\n\nexport type StartQueueOptions = {\n /** Most milliseconds of main-thread work one task spends building voices (at least one voice is always built). Default 2. */\n readonly budgetMs?: number\n /** A voice still waiting after this many milliseconds is dropped instead of starting late. Default 250. */\n readonly maxLatencyMs?: number\n}\n\nexport type StartQueue = {\n push(job: Omit<StartJob, 'queuedAt'>): void\n clear(): void\n readonly size: number\n /** The same queue as a `DeferredQueue` for a shared frame budget. Asking for it changes nothing: the queue drains by itself until a budget attaches it. */\n deferredQueue?(): DeferredQueue\n}\n\nconst nowMs = (): number => (typeof performance === 'undefined' ? Date.now() : performance.now())\n\nfunction scheduleTask(task: () => void): void {\n if (typeof MessageChannel === 'undefined') {\n setTimeout(task, 0)\n return\n }\n const channel = new MessageChannel()\n channel.port1.onmessage = () => {\n channel.port1.close()\n task()\n }\n channel.port2.postMessage(0)\n}\n\n/** Builds voices in small timed slices between frames, so a burst (an explosion's debris, glass and metal) never lands inside one frame. */\n/** The queue this package makes always has its `deferredQueue`; a third-party `StartQueue` may leave it out. */\nexport type OwnStartQueue = StartQueue & { deferredQueue(): DeferredQueue }\n\nexport function createStartQueue(options: StartQueueOptions = {}): OwnStartQueue {\n const budgetMs = options.budgetMs ?? 2\n const maxLatencyMs = options.maxLatencyMs ?? 250\n let jobs: StartJob[] = []\n let scheduled = false\n // true once a frame budget owns the draining: nothing schedules a task by itself\n let attached = false\n\n const runNext = (): void => {\n const job = jobs.shift() as StartJob\n if (nowMs() - job.queuedAt > maxLatencyMs) job.drop()\n else job.run()\n }\n\n const drain = (): void => {\n scheduled = false\n if (attached) return\n const began = nowMs()\n while (jobs.length > 0) {\n runNext()\n if (nowMs() - began >= budgetMs) break\n }\n if (jobs.length > 0) schedule()\n }\n\n const schedule = (): void => {\n if (scheduled || attached) return\n scheduled = true\n scheduleTask(drain)\n }\n\n const queue: OwnStartQueue = {\n push(job) {\n jobs.push({ ...job, queuedAt: nowMs() })\n schedule()\n },\n clear() {\n for (const job of jobs) job.drop()\n jobs = []\n },\n get size() {\n return jobs.length\n },\n deferredQueue: () => deferredQueue,\n }\n\n const deferredQueue: DeferredQueue = {\n id: DEFERRED_QUEUE_ID.AUDIO_VOICES,\n pending: () => jobs.length,\n run(deadline, clock) {\n let ran = 0\n while (jobs.length > 0) {\n runNext()\n ran++\n if (clock() >= deadline) break\n }\n return ran\n },\n flush() {\n while (jobs.length > 0) runNext()\n },\n attach() {\n attached = true\n },\n detach() {\n attached = false\n if (jobs.length > 0) schedule()\n },\n }\n return queue\n}\n","// The game's routines (jogo.js), one builder each: the nodes are created, set and wired in the routine's own order, so the trace of a plan\n// matches the trace of the team function. The level is already in the envelope; every builder connects straight to the bus.\nimport type { PlannedFilter, PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nconst end = (layer: PlannedLayer, start: number): number => start + layer.duration + layer.tail\nconst firstFilter = (layer: PlannedLayer): PlannedFilter | undefined => layer.filters?.bank[0]\nconst offsetOf = (layer: PlannedLayer): number => (layer.source.kind === 'noise' ? layer.source.offset : 0)\n\nfunction setFilter(node: BiquadFilterNode, filter: PlannedFilter | undefined, time: number): void {\n if (!filter) return\n node.type = filter.type\n assign(node.frequency, filter.frequency, time)\n if (filter.q !== undefined) node.Q.value = filter.q\n}\n\n/** `sfx` (L62089): gain to the bus first, then the noise, its lowpass, the envelope, and a random start in the noise. */\nexport function realizeBurst(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const gain = context.createGain()\n gain.connect(target.output)\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filter = context.createBiquadFilter()\n source.connect(filter)\n filter.connect(gain)\n setFilter(filter, firstFilter(layer), time)\n applyEnvelope(gain.gain, layer.envelope, time)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n return voiceOf([source])\n}\n\n/** `grito` (L62128): noise through a parallel formant bank (each band with its own level), a gain LFO for roughness. */\nexport function realizeScream(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const gain = context.createGain()\n gain.connect(target.output)\n for (const band of layer.filters?.bank ?? []) {\n const filter = context.createBiquadFilter()\n filter.type = band.type\n if (band.q !== undefined) filter.Q.value = band.q\n assign(filter.frequency, band.frequency, time)\n rampTo(filter.frequency, band.frequency, time)\n const level = context.createGain()\n level.gain.value = band.level ?? 1\n source.connect(filter)\n filter.connect(level)\n level.connect(gain)\n }\n const sources: AudioScheduledSourceNode[] = [source]\n const lfos = layer.modulators.map((modulator) => {\n const lfo = context.createOscillator()\n const depth = context.createGain()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = modulator.rate\n depth.gain.value = modulator.depth\n lfo.connect(depth)\n depth.connect(gain.gain)\n return lfo\n })\n applyEnvelope(gain.gain, layer.envelope, time)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n for (const lfo of lfos) {\n lfo.start(time)\n lfo.stop(end(layer, time))\n sources.push(lfo)\n }\n return voiceOf(sources)\n}\n\n/** `voz` (L62143): oscillator → bandpass → gain; the filter frequency is set after the pitch sweep. */\nexport function realizeGroan(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n const gain = context.createGain()\n const filter = context.createBiquadFilter()\n const band = firstFilter(layer)\n if (layer.source.kind === 'osc') oscillator.type = layer.source.wave\n if (band) {\n filter.type = band.type\n if (band.q !== undefined) filter.Q.value = band.q\n }\n if (layer.source.kind === 'osc') {\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n if (band) assign(filter.frequency, band.frequency, time)\n applyEnvelope(gain.gain, layer.envelope, time)\n oscillator.connect(filter)\n filter.connect(gain)\n gain.connect(target.output)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return voiceOf([oscillator])\n}\n\n/** `boom` (L68278): one oscillator sweeping down into a gain. */\nexport function realizeBoom(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n const gain = context.createGain()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n applyEnvelope(gain.gain, layer.envelope, time)\n oscillator.connect(gain)\n gain.connect(target.output)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return voiceOf([oscillator])\n}\n\n/** `chiado` (L69998): gain, noise and bandpass created first, then set, then wired. */\nexport function realizeStatic(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const gain = context.createGain()\n const source = context.createBufferSource()\n const filter = context.createBiquadFilter()\n source.buffer = target.noise()\n setFilter(filter, firstFilter(layer), time)\n applyEnvelope(gain.gain, layer.envelope, time)\n source.connect(filter)\n filter.connect(gain)\n gain.connect(target.output)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n return voiceOf([source])\n}\n\n/** `buzina` (L70272): one oscillator per layer into one gain with the first layer's envelope. */\nexport function realizeChord(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layers = plan.layers\n const oscillators = layers.map(() => context.createOscillator())\n const gain = context.createGain()\n // the team writes `o.type = o2.type = 'square'`, which assigns right to left\n for (let index = layers.length - 1; index >= 0; index--) {\n const source = (layers[index] as PlannedLayer).source\n if (source.kind === 'osc') (oscillators[index] as OscillatorNode).type = source.wave\n }\n layers.forEach((layer, index) => {\n if (layer.source.kind === 'osc') assign((oscillators[index] as OscillatorNode).frequency, layer.source.frequency, target.time + layer.at)\n })\n applyEnvelope(gain.gain, (layers[0] as PlannedLayer).envelope, target.time + (layers[0] as PlannedLayer).at)\n for (const oscillator of oscillators) oscillator.connect(gain)\n gain.connect(target.output)\n layers.forEach((layer, index) => (oscillators[index] as OscillatorNode).start(target.time + layer.at))\n layers.forEach((layer, index) => (oscillators[index] as OscillatorNode).stop(end(layer, target.time + layer.at)))\n return voiceOf(oscillators)\n}\n\n/**\n * `bichoSom` (L66625): gain and filter are created before the level is checked (a silent plan stops there), then each repeat is an oscillator\n * with its own envelope into the shared filter, whose frequency and Q are set again on every repeat.\n */\nexport function realizeCalls(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const gain = context.createGain()\n const filter = context.createBiquadFilter()\n if (plan.silent) return voiceOf([])\n const band = firstFilter(plan.layers[0] as PlannedLayer)\n if (band) filter.type = band.type\n filter.connect(gain)\n gain.connect(target.output)\n const oscillators = plan.layers.map((layer) => {\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n if (band) {\n assign(filter.frequency, band.frequency, time)\n if (band.q !== undefined) filter.Q.value = band.q\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope)\n envelope.connect(filter)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return oscillator\n })\n return voiceOf(oscillators)\n}\n","// The art scene's primitives (cena L1319–1328, L1369): `sNoise`, `sTone` and `voice`, each layer with its own output stage (`outAt`: distance\n// gain, pan, reverb send), and the siren straight to the bus. Built in the team's order so the traces match node for node.\nimport type { PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, filterNode, gainNode, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nconst end = (layer: PlannedLayer, start: number): number => start + layer.duration + layer.tail\n\n/** `outAt`: the layer level, the stereo panner when the plan pans and the context has one, the bus, then the reverb send. */\nfunction outputStage(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): GainNode {\n const { context } = target\n const level = gainNode(context, layer.level)\n let node: AudioNode = level\n if (plan.pan !== undefined && typeof context.createStereoPanner === 'function') {\n const panner = context.createStereoPanner()\n panner.pan.value = plan.pan\n level.connect(panner)\n node = panner\n }\n node.connect(target.output)\n if (layer.wet && target.wet) {\n const send = gainNode(context, layer.wet)\n node.connect(send)\n send.connect(target.wet)\n }\n return level\n}\n\nfunction realizeNoiseLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const { context } = target\n const time = target.time + layer.at\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filters = (layer.filters?.bank ?? []).map((filter) => {\n const node = filterNode(context, filter, time)\n rampTo(node.frequency, filter.frequency, time)\n return node\n })\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n source.start(time, layer.source.kind === 'noise' ? layer.source.offset : 0)\n source.stop(end(layer, time))\n return [source]\n}\n\nfunction realizeToneLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const { context } = target\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return [oscillator]\n}\n\nfunction realizeVoiceLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const source = layer.source\n if (source.kind !== 'formant_voice') return []\n const { context } = target\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n oscillator.type = source.wave\n assign(oscillator.frequency, source.frequency, time)\n rampTo(oscillator.frequency, source.frequency, time)\n const vibrato = context.createOscillator()\n vibrato.frequency.value = source.vibrato.rate\n const vibratoDepth = gainNode(context, source.vibrato.depth)\n vibrato.connect(vibratoDepth)\n vibratoDepth.connect(oscillator.frequency)\n const formants = source.formants.map((formant) => filterNode(context, { type: 'bandpass', frequency: { value: formant.frequency }, q: formant.q }, time))\n const breath = noiseSource(target, true)\n const breathBand = filterNode(context, { type: 'bandpass', frequency: { value: source.breath.frequency }, q: source.breath.q }, time)\n const breathLevel = gainNode(context, source.breath.gain)\n const mix = gainNode(context, source.mix)\n for (const formant of formants) oscillator.connect(formant)\n breath.connect(breathBand)\n breathBand.connect(breathLevel)\n for (const formant of formants) formant.connect(mix)\n breathLevel.connect(mix)\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n mix.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n const stop = end(layer, time)\n oscillator.start(time)\n vibrato.start(time)\n breath.start(time, source.breath.offset)\n oscillator.stop(stop)\n vibrato.stop(stop)\n breath.stop(stop)\n return [oscillator, vibrato, breath]\n}\n\n/** Every layer in order, each with its own output stage. */\nexport function realizeLayered(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const sources = plan.layers.flatMap((layer) => {\n if (layer.source.kind === 'noise') return realizeNoiseLayer(plan, layer, target)\n if (layer.source.kind === 'osc') return realizeToneLayer(plan, layer, target)\n return realizeVoiceLayer(plan, layer, target)\n })\n return voiceOf(sources)\n}\n\n/** The siren: oscillator with a frequency LFO, envelope, lowpass, straight to the bus with a reverb send. */\nexport function realizeSiren(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const depths = layer.modulators.map((modulator) => {\n const lfo = context.createOscillator()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = modulator.rate\n const depth = gainNode(context, modulator.depth)\n lfo.connect(depth)\n if (modulator.target === 'frequency') depth.connect(oscillator.frequency)\n return { lfo, depth, target: modulator.target }\n })\n const lfos = depths.map(({ lfo }) => lfo)\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n for (const { depth, target: modulated } of depths) if (modulated === 'gain') depth.connect(envelope.gain)\n const filters = (layer.filters?.bank ?? []).map((filter) => filterNode(context, filter, time))\n let tail: AudioNode = oscillator\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope)\n envelope.connect(target.output)\n if (layer.wet && target.wet) {\n const send = gainNode(context, layer.wet)\n envelope.connect(send)\n send.connect(target.wet)\n }\n const stop = end(layer, time)\n oscillator.start(time)\n for (const lfo of lfos) lfo.start(time)\n oscillator.stop(stop)\n for (const lfo of lfos) lfo.stop(stop)\n return voiceOf([oscillator, ...lfos])\n}\n","// The weapon audio of the kit (`weapons-three`, first written against raw WebAudio): per layer, either a noise burst (source, filter, envelope gain)\n// or an oscillator (oscillator, envelope gain), created in that order and chained straight to the bus. The level is already in the envelope.\nimport type { PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, filterNode, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nfunction noiseLayer(layer: PlannedLayer, target: RealizeTarget, time: number): AudioScheduledSourceNode {\n const { context } = target\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filters = (layer.filters?.bank ?? []).map((filter) => filterNode(context, filter, time))\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope).connect(target.output)\n source.start(time, layer.source.kind === 'noise' ? layer.source.offset : 0)\n source.stop(time + layer.duration + layer.tail)\n return source\n}\n\nfunction toneLayer(layer: PlannedLayer, target: RealizeTarget, time: number): AudioScheduledSourceNode {\n const { context } = target\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope).connect(target.output)\n oscillator.start(time)\n oscillator.stop(time + layer.duration + layer.tail)\n return oscillator\n}\n\n/** One noise burst or one tone per layer, in the order written. */\nexport function realizeWeapon(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const sources = plan.layers.map((layer) => {\n const time = target.time + layer.at\n return layer.source.kind === 'noise' ? noiseLayer(layer, target, time) : toneLayer(layer, target, time)\n })\n return voiceOf(sources)\n}\n","import type { SoundPlan } from '../plan'\nimport type { BuildOrder } from '../recipe'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\nimport { realizeBoom, realizeBurst, realizeCalls, realizeChord, realizeGroan, realizeScream, realizeStatic } from './realize-game'\nimport { realizeLayered, realizeSiren } from './realize-layered'\nimport { realizeWeapon } from './realize-weapon'\n\nconst BUILDERS: Readonly<Record<BuildOrder, (plan: SoundPlan, target: RealizeTarget) => RealizedVoice>> = {\n layered: realizeLayered,\n burst: realizeBurst,\n scream: realizeScream,\n groan: realizeGroan,\n boom: realizeBoom,\n static: realizeStatic,\n chord: realizeChord,\n calls: realizeCalls,\n siren: realizeSiren,\n weapon: realizeWeapon,\n}\n\n/** Builds a plan's nodes on `target`, in the node order of the team routine its `order` names. */\nexport function realize(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n return BUILDERS[plan.order](plan, target)\n}\n","import type { PlannedAutomation, PlannedFilter, PlannedLayer, PlannedModulator, PlannedSource, SoundPlan } from './plan'\nimport type { SoundSet } from './recipe'\n\nconst tuneAutomation = (automation: PlannedAutomation, rate: number): PlannedAutomation => {\n const tuned: { -readonly [K in keyof PlannedAutomation]: PlannedAutomation[K] } = { ...automation }\n if (automation.value !== undefined) tuned.value = automation.value * rate\n if (automation.from !== undefined) tuned.from = automation.from * rate\n if (automation.to !== undefined) tuned.to = automation.to * rate\n if (automation.at !== undefined) tuned.at = automation.at / rate\n return tuned\n}\n\nconst tuneFilter = (filter: PlannedFilter, rate: number): PlannedFilter => ({ ...filter, frequency: tuneAutomation(filter.frequency, rate) })\n\nconst tuneSource = (source: PlannedSource, rate: number): PlannedSource => {\n switch (source.kind) {\n case 'noise':\n return source\n case 'osc':\n return { ...source, frequency: tuneAutomation(source.frequency, rate) }\n case 'formant_voice':\n return {\n ...source,\n frequency: tuneAutomation(source.frequency, rate),\n formants: source.formants.map((formant) => ({ ...formant, frequency: formant.frequency * rate })),\n breath: { ...source.breath, frequency: source.breath.frequency * rate },\n }\n }\n}\n\nconst tuneModulator = (modulator: PlannedModulator, rate: number): PlannedModulator => ({\n ...modulator,\n rate: modulator.rate * rate,\n ...(modulator.target === 'frequency' ? { depth: modulator.depth * rate } : {}),\n})\n\nconst tuneLayer = (layer: PlannedLayer, rate: number): PlannedLayer => ({\n ...layer,\n at: layer.at / rate,\n duration: layer.duration / rate,\n tail: layer.tail / rate,\n source: tuneSource(layer.source, rate),\n ...(layer.filters ? { filters: { ...layer.filters, bank: layer.filters.bank.map((filter) => tuneFilter(filter, rate)) } } : {}),\n modulators: layer.modulators.map((modulator) => tuneModulator(modulator, rate)),\n envelope: layer.envelope.map((point) => ({ ...point, time: point.time / rate })),\n})\n\n/**\n * A plan played faster or slower, as a tape would: every frequency (tones, filters, formants, LFOs) times `rate`, every time divided by it. Noise\n * has no pitch of its own, so its colour moves with its filters. `rate` 1 gives the plan back.\n */\nexport function retunePlan(plan: SoundPlan, rate: number): SoundPlan {\n if (rate === 1 || !(rate > 0)) return plan\n return { ...plan, length: plan.length / rate, layers: plan.layers.map((layer) => tuneLayer(layer, rate)) }\n}\n\n/** Remembers the last variant of each set, so the next draw never repeats it. */\nexport type SetPicker = {\n /** The variant to play and its rate, drawn from `random` (two numbers: the variant, then the rate). */\n pick(set: SoundSet, random: () => number): { readonly id: string; readonly rate: number }\n /** Forget the last variants (a fresh scene). */\n reset(): void\n}\n\nexport function createSetPicker(): SetPicker {\n const last = new Map<string, number>()\n return {\n pick(set, random) {\n const count = set.variants.length\n const previous = last.get(set.id)\n let index: number\n if (count === 1) index = 0\n else if (set.repeat || previous === undefined) index = Math.min(count - 1, Math.floor(random() * count))\n else {\n // one of the others: draw among count − 1 and skip the previous\n index = Math.min(count - 2, Math.floor(random() * (count - 1)))\n if (index >= previous) index += 1\n }\n last.set(set.id, index)\n const [min, max] = set.rate ?? [1, 1]\n const rate = min === max ? min : min + random() * (max - min)\n return { id: set.variants[index] as string, rate }\n },\n reset: () => last.clear(),\n }\n}\n","/**\n * Decoded sample buffers by url. Files load once (concurrent asks share the same promise), decode on the engine's context and stay until `clear`.\n * The bytes come from a `SampleLoader`: `fetch` by default, or anything else (a single-file page passes the files inlined as base64).\n */\n\n/** Gets the bytes of a file. */\nexport type SampleLoader = (url: string) => Promise<ArrayBuffer>\n\nexport type SampleStatus = 'none' | 'loading' | 'ready' | 'failed'\n\nexport type SampleLoadReport = { readonly loaded: readonly string[]; readonly failed: readonly { readonly url: string; readonly error: string }[] }\n\nexport type SampleStore = {\n status(url: string): SampleStatus\n /** The decoded buffer, once ready. */\n buffer(url: string): AudioBuffer | undefined\n /** Whether every url is ready. */\n ready(urls: readonly string[]): boolean\n load(urls: readonly string[], context: BaseAudioContext): Promise<SampleLoadReport>\n /** Seconds of the decoded file, or `undefined` while not ready. */\n seconds(url: string): number | undefined\n clear(): void\n}\n\n/** `fetch` relative to `baseUrl` (default the page). */\nexport function fetchLoader(baseUrl?: string): SampleLoader {\n return async (url) => {\n const target = baseUrl ? new URL(url, baseUrl).toString() : url\n const response = await fetch(target)\n if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${target}`)\n return response.arrayBuffer()\n }\n}\n\n/** Bytes of files given inline as base64 (or `data:` urls), by url. */\nexport function inlineLoader(files: Readonly<Record<string, string>>): SampleLoader {\n return async (url) => {\n const text = files[url]\n if (text === undefined) throw new Error(`no inline file for ${url}`)\n const base64 = text.startsWith('data:') ? text.slice(text.indexOf(',') + 1) : text\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)\n return bytes.buffer\n }\n}\n\nconst decode = (context: BaseAudioContext, bytes: ArrayBuffer): Promise<AudioBuffer> =>\n new Promise((resolve, reject) => {\n // the callback form also covers old Safari, where decodeAudioData returns no promise\n const result = context.decodeAudioData(bytes, resolve, reject) as Promise<AudioBuffer> | undefined\n result?.catch?.(reject)\n })\n\nexport function createSampleStore(loader: SampleLoader = fetchLoader()): SampleStore {\n const buffers = new Map<string, AudioBuffer>()\n const pending = new Map<string, Promise<AudioBuffer>>()\n const failed = new Map<string, string>()\n let generation = 0\n\n const loadOne = (url: string, context: BaseAudioContext): Promise<AudioBuffer> => {\n const existing = buffers.get(url)\n if (existing) return Promise.resolve(existing)\n const inFlight = pending.get(url)\n if (inFlight) return inFlight\n const started = generation\n failed.delete(url)\n const promise = loader(url)\n .then((bytes) => decode(context, bytes))\n .then((buffer) => {\n if (started === generation) buffers.set(url, buffer)\n return buffer\n })\n .catch((error: unknown) => {\n if (started === generation) failed.set(url, error instanceof Error ? error.message : String(error))\n throw error\n })\n .finally(() => {\n if (pending.get(url) === promise) pending.delete(url)\n })\n pending.set(url, promise)\n return promise\n }\n\n return {\n status(url) {\n if (buffers.has(url)) return 'ready'\n if (pending.has(url)) return 'loading'\n if (failed.has(url)) return 'failed'\n return 'none'\n },\n buffer: (url) => buffers.get(url),\n ready: (urls) => urls.every((url) => buffers.has(url)),\n seconds: (url) => buffers.get(url)?.duration,\n async load(urls, context) {\n const results = await Promise.allSettled(urls.map((url) => loadOne(url, context)))\n const loaded: string[] = []\n const errors: { url: string; error: string }[] = []\n results.forEach((result, index) => {\n const url = urls[index] as string\n if (result.status === 'fulfilled') loaded.push(url)\n else errors.push({ url, error: result.reason instanceof Error ? result.reason.message : String(result.reason) })\n })\n return { loaded, failed: errors }\n },\n clear() {\n generation++\n buffers.clear()\n pending.clear()\n failed.clear()\n },\n }\n}\n","import { OPEN_CUTOFF } from '../sample'\nimport type { SamplePlan } from '../sample'\nimport { gainNode, voiceOf } from './nodes'\nimport type { RealizedVoice } from './nodes'\n\nexport type SampleTarget = {\n readonly context: BaseAudioContext\n readonly output: AudioNode\n readonly buffer: (url: string) => AudioBuffer | undefined\n readonly time: number\n}\n\n/** A sample voice can also be faded out (the choke of its sound). */\nexport type RealizedSampleVoice = RealizedVoice & { fade(at: number, seconds: number): void }\n\n/**\n * Builds a sample plan: each layer is a buffer source at the planned rate with its own gain, the layers meet in one voice gain (the choke fades it),\n * one lowpass (left out when open) and one stereo panner (when the plan has a pan), then the bus. A layer whose buffer is not loaded is skipped.\n */\nexport function realizeSample(plan: SamplePlan, target: SampleTarget): RealizedSampleVoice {\n const context = target.context\n let head: AudioNode = target.output\n if (plan.pan !== undefined && typeof context.createStereoPanner === 'function') {\n const panner = context.createStereoPanner()\n panner.pan.value = plan.pan\n panner.connect(head)\n head = panner\n }\n if (plan.cutoff < OPEN_CUTOFF) {\n const lowpass = context.createBiquadFilter()\n lowpass.type = 'lowpass'\n lowpass.frequency.value = plan.cutoff\n lowpass.Q.value = 0.7\n lowpass.connect(head)\n head = lowpass\n }\n const voice = context.createGain()\n voice.connect(head)\n head = voice\n const sources: AudioBufferSourceNode[] = []\n for (const layer of plan.layers) {\n const buffer = target.buffer(layer.url)\n if (!buffer) continue\n const source = context.createBufferSource()\n source.buffer = buffer\n source.playbackRate.value = layer.rate\n const gain = gainNode(context as AudioContext, layer.gain)\n source.connect(gain)\n gain.connect(head)\n source.start(target.time + layer.at)\n sources.push(source)\n }\n const realized = voiceOf(sources)\n return {\n ...realized,\n fade(at, seconds) {\n voice.gain.setValueAtTime(1, at)\n voice.gain.linearRampToValueAtTime(0, at + seconds)\n for (const source of sources) {\n try {\n source.stop(at + seconds)\n } catch {\n // already stopped\n }\n }\n },\n }\n}\n\n/** Seconds a sample plan lasts with its buffers (the longest layer, at its rate). */\nexport function sampleLength(plan: SamplePlan, seconds: (url: string) => number | undefined): number {\n let length = 0\n for (const layer of plan.layers) length = Math.max(length, layer.at + (seconds(layer.url) ?? 0) / layer.rate)\n return length\n}\n","import type { DeferredQueue, Vec3 } from '@adatechnology/game-contracts'\n\nimport { createSoundRegistry } from '../bank'\nimport type { SoundRegistry } from '../bank'\nimport { falloffGain, isSilent } from '../falloff'\nimport { DEFAULT_LISTENER, listenerDistance } from '../listener'\nimport type { DistanceMode, Listener } from '../listener'\nimport { DEFAULT_MIX, busGain, resolveMix } from '../mix'\nimport type { BusSetting, MixProfile } from '../mix'\nimport { planSound } from '../plan'\nimport type { PlanInput, SoundPlan } from '../plan'\nimport type { BusId, SoundBank, SoundRecipe } from '../recipe'\nimport { createRng, streamFor } from '../rng'\nimport { busPriority, createVoiceManager } from '../voices'\nimport type { VoiceGroup } from '../voices'\nimport { buildChain } from './chain'\nimport type { MixChain } from './chain'\nimport { globalContext, unlockContext } from './context'\nimport { createLoopHandle } from './engine-loop'\nimport type { AudioLoopHandle, LoopHost } from './engine-loop'\nimport { createSampleLoopHandle } from './sample-loop'\nimport { createNoiseStore, noiseBuffer, prepareNoise } from './engine-noise'\nimport type { NoiseStore } from './engine-noise'\nimport type { RealizedVoice } from './nodes'\nimport { createStartQueue } from './engine-queue'\nimport type { StartQueueOptions } from './engine-queue'\nimport { realize } from './realize'\nimport { createSetPicker, retunePlan } from '../variation'\nimport { planSample, sampleUrls } from '../sample'\nimport type { SampleEnvironment, SampleMemory, SamplePlan, SampleSound } from '../sample'\nimport { createSampleStore, fetchLoader } from './sample-store'\nimport type { SampleLoadReport, SampleLoader, SampleStatus } from './sample-store'\nimport { realizeSample, sampleLength } from './realize-sample'\nimport type { RealizedSampleVoice } from './realize-sample'\n\nexport type PlayOptions = {\n readonly position?: Vec3\n /** Meters; overrides `position` for the distance (not for the pan). */\n readonly distance?: number\n readonly volume?: number\n readonly params?: Readonly<Record<string, number>>\n /** This sound's own stream: same seed, same sound. */\n readonly seed?: number\n /** Seconds from now. */\n readonly delay?: number\n /** Built now instead of waiting in the engine's deferred start queue: for a sound that has to land on the frame the player sees it (a blow's\n * contact, a heel strike, a landing). The queue builds a voice on the next frame budget and drops it after its latency, which at a low frame\n * rate is late or silent. Default false. */\n readonly urgent?: boolean\n /** A named stream of the engine (`streamFor(seed, name)`), so one subject never shifts another's sounds. */\n readonly channel?: string\n /** The tail a sample sound plays (default the engine's, see `setEnvironment`). */\n readonly environment?: SampleEnvironment\n /** 0 (light) to 1 (heavy): the tier of takes a sample sound plays (criterion C7). */\n readonly intensity?: number\n /** 0 (clear) to 1 (behind a wall) for this play, over the engine's `occlusion` (a test bench puts a wall in between). Sample sounds only. */\n readonly occlusion?: number\n}\n\n/** A playing voice: a recipe (`kind: 'recipe'`, the plan of the synthesized sound) or files (`kind: 'sample'`). */\nexport type VoiceHandle =\n | { readonly id: number; readonly kind: 'recipe'; readonly plan: SoundPlan; stop(): void }\n | { readonly id: number; readonly kind: 'sample'; readonly plan: SamplePlan; stop(): void }\n\n/**\n * A voice that started, for measuring (criterion C1: the event against the start of the sound). Times are the context clock, in seconds:\n * `requestedAt` when `play` was called, `startAt` when the first sample of the sound leaves the engine; `outputLatency` is what the device adds\n * after that (`baseLatency + outputLatency` of the context, 0 when unknown).\n */\nexport type VoiceStartEvent = {\n readonly id: string\n readonly kind: 'recipe' | 'sample'\n /** The sample sound this recipe stood in for while its files were not loaded. */\n readonly fallbackOf?: string\n /** The bank the played id is registered in (`kit_samples`, `user_samples`, a recipe bank...). */\n readonly bank?: string\n readonly requestedAt: number\n readonly startAt: number\n readonly outputLatency: number\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** The files a sample voice plays, by layer. */\n readonly layers?: readonly { readonly role: string; readonly url: string; readonly take: number; readonly rate: number }[]\n /** The tier of takes a sample voice played (criterion C7). */\n readonly tier?: string\n}\n\nexport type SampleOptions = {\n /** Gets the bytes of a file (default `fetch`, relative to `baseUrl`). */\n readonly loader?: SampleLoader\n readonly baseUrl?: string\n /** Load a sound's files the first time it is played (default true); the fallback plays meanwhile. */\n readonly autoLoad?: boolean\n /**\n * The peak limiter every sample voice of a bus goes through before the bus (criteria C6 and C9: no sound and no burst goes over −1 dBFS): linear\n * up to `knee` (default 0.5, −6 dBFS), then bent smoothly to `ceiling` (default 0.891, −1 dBFS), with no delay. `false` leaves it out.\n */\n readonly limiter?: false | { readonly knee?: number; readonly ceiling?: number }\n}\n\n/** A subject's own random stream; `ownNoise` also gives it its own noise buffer, filled from that stream (the order `createWeaponAudio` uses). */\nexport type AudioChannel = {\n readonly random: () => number\n play(id: string, options?: PlayOptions): VoiceHandle | null\n plan(id: string, options?: PlayOptions): SoundPlan | null\n}\n\nexport type AudioStats = {\n readonly context: 'none' | AudioContextState\n readonly voices: number\n readonly peak: number\n readonly dropped: number\n readonly maxVoices: number\n readonly loops: number\n}\n\nexport type AudioEngineOptions = {\n /** Seeds the engine stream: the noise, the reverb impulse and every sound played without its own seed or channel. Default 1. */\n readonly seed?: number\n /** Default `art_scene` (Q1). */\n readonly mix?: string | MixProfile\n readonly profiles?: Readonly<Record<string, MixProfile>>\n readonly banks?: readonly SoundBank[]\n readonly maxVoices?: number\n readonly groups?: Readonly<Record<string, VoiceGroup>>\n readonly distance?: DistanceMode\n /** 0 (clear) to 1 (behind a wall) for a sound at a point; without it there is no occlusion (Q8). */\n readonly occlusion?: (point: Vec3) => number\n readonly createContext?: () => AudioContext | null\n /** Build voices in timed slices between frames instead of inside `play` (a sound starts a few ms late; a burst never costs a frame). Off by default. */\n readonly deferredStart?: StartQueueOptions\n /** Where sample sounds get their files. */\n readonly samples?: SampleOptions\n /** The tail sample sounds play when `play` names none (default `outdoor`). */\n readonly environment?: SampleEnvironment\n /** Called when a voice is built (recipe or sample): the measuring hook of the criteria. */\n readonly onVoiceStart?: (event: VoiceStartEvent) => void\n}\n\nexport type AudioEngine = {\n readonly registry: SoundRegistry\n register(bank: SoundBank): void\n /** Pure: the plan a sound would play with, from `options.seed` or the engine seed; draws nothing from the live streams. */\n plan(id: string, options?: PlayOptions): SoundPlan | null\n /** Pure: the plan a sample sound would play with (no round-robin memory), from `options.seed` or the engine seed. */\n planSample(id: string, options?: PlayOptions): SamplePlan | null\n /** Loads the files of these sample sounds (default all registered). Creates the context; resolves when every file is decoded or failed. */\n loadSamples(ids?: readonly string[]): Promise<SampleLoadReport>\n /** `ready` when every file of the sound is decoded. */\n sampleStatus(id: string): SampleStatus\n /** The tail sample sounds play from now on. */\n setEnvironment(environment: SampleEnvironment): void\n /** The node everything is mixed into before the speakers (to record or meter the whole output), or `null` before the context exists. */\n output(): AudioNode | null\n /** Another place files come from: urls `accepts` takes go to `loader`, the rest to the engine's own (a bench lends its calibration takes). */\n addSampleSource(accepts: (url: string) => boolean, loader: SampleLoader): void\n /** Follows every voice built from now on (as `onVoiceStart` does); returns the unsubscribe function. */\n watchVoices(listener: (event: VoiceStartEvent) => void): () => void\n play(id: string, options?: PlayOptions): VoiceHandle | null\n playPlan(plan: SoundPlan, options?: { readonly delay?: number }): VoiceHandle | null\n loop(id: string, options?: { readonly volume?: number }): AudioLoopHandle\n channel(options: { readonly seed?: number; readonly random?: () => number; readonly ownNoise?: boolean }): AudioChannel\n setListener(listener: Listener): void\n setBus(id: BusId, setting: BusSetting): void\n setMix(mix: string | MixProfile): void\n /** The master volume of the current chain and of any later one (0 to 1). */\n setMaster(gain: number): void\n /** Creates the context and the mixing chain if needed and resumes it; call from a click or a key. */\n unlock(): void\n /** Creates the context, the mixing chain (reverb impulse included) and the shared noise buffer now, so the first sound does not pay for them inside a frame. Returns false without a context. */\n warmUp(): boolean\n stats(): AudioStats\n /** RMS (0 to 1) of what a bus carries now, read from an analyser the first time you ask; sounds started before that do not reach it. 0 without a context. */\n level(bus: BusId): number\n /**\n * The voice start queue as a `DeferredQueue` for a shared frame budget (`budget.register` attaches it and the queue stops scheduling its own tasks), or `null`\n * without `deferredStart`. Asking for it changes nothing.\n */\n deferredQueue?(): DeferredQueue | null\n dispose(): void\n}\n\n/** The limiter's transfer curve over ±`range`: linear up to `knee`, then a tanh bend that never passes `ceiling`. */\nexport function limiterCurve(knee: number, ceiling: number, range: number, points = 2049): Float32Array<ArrayBuffer> {\n const curve = new Float32Array(points)\n const room = Math.max(1e-6, ceiling - knee)\n for (let index = 0; index < points; index++) {\n const value = ((index / (points - 1)) * 2 - 1) * range\n const size = Math.abs(value)\n const bent = size <= knee ? size : knee + room * Math.tanh((size - knee) / room)\n curve[index] = Math.sign(value) * bent\n }\n return curve\n}\n\ntype Admission = { readonly bus: BusId; readonly group?: string; readonly priority?: number }\n\nconst usesNoise = (recipe: SoundRecipe): boolean => recipe.layers.some((layer) => layer.source.kind !== 'osc')\nconst planUsesNoise = (plan: SoundPlan): boolean => plan.layers.some((layer) => layer.source.kind !== 'osc')\n\n/**\n * The sound engine: plans recipes and builds them on a lazily created AudioContext through one of the team mixing chains. Without an AudioContext\n * (Node, workers) every call except `plan` does nothing.\n */\nexport function createAudioEngine(options: AudioEngineOptions = {}): AudioEngine {\n const seed = options.seed ?? 1\n const registry = createSoundRegistry(options.banks)\n const voices = createVoiceManager({ ...(options.groups ? { groups: options.groups } : {}), ...(options.maxVoices === undefined ? {} : { maxVoices: options.maxVoices }) })\n const engineRandom = createRng(seed)\n const shared = createNoiseStore(engineRandom)\n const busSettings = new Map<BusId, BusSetting>()\n const busNodes = new Map<BusId, GainNode>()\n const meters = new Map<BusId, { readonly analyser: AnalyserNode; readonly data: Float32Array<ArrayBuffer> }>()\n const active = new Map<number, RealizedVoice>()\n const loops = new Set<{ rewire(): void; stop(): void; readonly created: boolean }>()\n const named = new Map<string, () => number>()\n let mix = resolveMix(options.mix ?? DEFAULT_MIX, options.profiles)\n let context: AudioContext | null = null\n let chain: MixChain | null = null\n let listener: Listener = DEFAULT_LISTENER\n let lastTime = 0\n let environment: SampleEnvironment = options.environment ?? 'outdoor'\n const sampleLimiters = new Map<BusId, AudioNode>()\n // recipes go straight to the bus (their traces match the team routines node for node); recorded files go through a limiter of their bus. It is a\n // waveshaper, not a compressor: a compressor of the browser looks 6 ms ahead, which C1 (≤ 20 ms from the event) cannot spare.\n const sampleOutput = (bus: BusId): AudioNode => {\n const setting = options.samples?.limiter\n if (setting === false || !context) return outputFor(bus)\n const existing = sampleLimiters.get(bus)\n if (existing) return existing\n const range = 4\n const input = context.createGain()\n input.gain.value = 1 / range\n const shaper = context.createWaveShaper()\n shaper.curve = limiterCurve(setting?.knee ?? 0.5, setting?.ceiling ?? 0.891, range)\n ensureBus(bus)\n input.connect(shaper)\n shaper.connect(outputFor(bus))\n sampleLimiters.set(bus, input)\n return input\n }\n const chokes = new Map<string, { readonly id: number; readonly voice: RealizedSampleVoice }[]>()\n // the voices of a choked sound still ringing (the limiter forgets the ones that ended)\n const choked = (id: string): { readonly id: number; readonly voice: RealizedSampleVoice }[] => {\n const list = (chokes.get(id) ?? []).filter((entry) => active.has(entry.id))\n chokes.set(id, list)\n return list\n }\n const watchers = new Set<(event: VoiceStartEvent) => void>()\n const announce = (event: VoiceStartEvent): void => {\n options.onVoiceStart?.(event)\n for (const watcher of watchers) watcher(event)\n }\n const sources: { readonly accepts: (url: string) => boolean; readonly loader: SampleLoader }[] = []\n const baseLoader = options.samples?.loader ?? fetchLoader(options.samples?.baseUrl)\n const sampleStore = createSampleStore((url) => (sources.find((source) => source.accepts(url))?.loader ?? baseLoader)(url))\n const memory: SampleMemory = new Map()\n const latencyOf = (audio: BaseAudioContext): number => {\n const live = audio as Partial<Pick<AudioContext, 'baseLatency' | 'outputLatency'>>\n return (live.baseLatency ?? 0) + (live.outputLatency ?? 0)\n }\n\n const outputFor = (bus: BusId): AudioNode => (busNodes.get(bus) ?? chain?.master) as AudioNode\n\n // a bus somebody asked the level of gets an analyser as soon as it has a node, so sounds started before the first reading are metered too\n const watched = new Set<BusId>()\n const meterOf = (bus: BusId): { readonly analyser: AnalyserNode; readonly data: Float32Array<ArrayBuffer> } | undefined => {\n const existing = meters.get(bus)\n if (existing) return existing\n const node = busNodes.get(bus)\n if (!context || !node || typeof context.createAnalyser !== 'function') return undefined\n const analyser = context.createAnalyser()\n analyser.fftSize = 1024\n node.connect(analyser)\n const made = { analyser, data: new Float32Array(analyser.fftSize) }\n meters.set(bus, made)\n return made\n }\n\n const ensureBus = (bus: BusId): void => {\n if (!context || !chain || busNodes.has(bus)) return\n const node = context.createGain()\n node.connect(chain.master)\n busNodes.set(bus, node)\n if (watched.has(bus)) meterOf(bus)\n }\n\n const ready = (): AudioContext | null => {\n if (context) return context\n const created = (options.createContext ?? globalContext)()\n if (!created) return null\n context = created\n chain = buildChain(created, mix, engineRandom)\n if (mix.noise.create === 'eager') noiseBuffer(shared, created, mix.noise.seconds)\n for (const [bus, setting] of Object.entries(mix.buses ?? {}) as [BusId, BusSetting][]) {\n busSettings.set(bus, { ...setting, ...busSettings.get(bus) })\n }\n for (const [bus, setting] of busSettings) {\n ensureBus(bus)\n ;(busNodes.get(bus) as GainNode).gain.value = busGain(setting)\n }\n lastTime = created.currentTime\n return created\n }\n\n const advance = (): void => {\n if (!context) return\n const elapsed = context.currentTime - lastTime\n lastTime = context.currentTime\n if (elapsed > 0) for (const id of voices.advance(elapsed)) active.delete(id)\n }\n\n const inputFor = (recipe: SoundRecipe, playOptions: PlayOptions, random: () => number): PlanInput => ({\n random,\n listener,\n noiseSeconds: mix.noise.seconds,\n ...(options.distance ? { distanceMode: options.distance } : {}),\n ...(playOptions.volume === undefined ? {} : { volume: playOptions.volume }),\n ...(playOptions.distance === undefined ? {} : { distance: playOptions.distance }),\n ...(playOptions.position ? { position: playOptions.position } : {}),\n ...(playOptions.params ? { params: playOptions.params } : {}),\n ...(options.occlusion && playOptions.position && recipe.falloff?.model !== 'none' ? { occlusion: options.occlusion(playOptions.position) } : {}),\n })\n\n const startQueue = options.deferredStart ? createStartQueue(options.deferredStart) : null\n\n const build = (plan: SoundPlan, store: NoiseStore, delay: number, requestedAt: number, fallbackOf?: string): RealizedVoice => {\n const audio = context as AudioContext\n const time = audio.currentTime + delay\n const realized = realize(plan, {\n context: audio,\n output: outputFor(plan.bus),\n ...(chain?.wet ? { wet: chain.wet } : {}),\n noise: () => noiseBuffer(store, audio, mix.noise.seconds),\n time,\n })\n const recipeBank = registry.bankOf(plan.id)\n announce({\n id: plan.id,\n kind: 'recipe',\n ...(fallbackOf ? { fallbackOf } : {}),\n ...(recipeBank ? { bank: recipeBank } : {}),\n requestedAt,\n startAt: time,\n outputLatency: latencyOf(audio),\n level: plan.level,\n distance: plan.distance,\n ...(plan.pan === undefined ? {} : { pan: plan.pan }),\n })\n return realized\n }\n\n // the voice a deferred sound is tracked by until it is built: `stop` cancels it or stops what was built\n const deferVoice = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay: number, fallbackOf?: string): RealizedVoice => {\n const requestedAt = context?.currentTime ?? 0\n let built: RealizedVoice | null = null\n let cancelled = false\n const pending: RealizedVoice = {\n get sources() {\n return built?.sources ?? []\n },\n stop() {\n cancelled = true\n built?.stop()\n },\n }\n ;(startQueue as ReturnType<typeof createStartQueue>).push({\n run() {\n if (!cancelled && context) built = build(plan, store, delay, requestedAt, fallbackOf)\n },\n drop() {\n if (voiceId === undefined) return\n voices.release(voiceId)\n active.delete(voiceId)\n },\n })\n return pending\n }\n\n const start = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay = 0, fallbackOf?: string, urgent = false): VoiceHandle | null => {\n const realized = startQueue && !urgent ? deferVoice(plan, store, voiceId, delay, fallbackOf) : build(plan, store, delay, context?.currentTime ?? 0, fallbackOf)\n if (voiceId === undefined) return null\n voices.setLength(voiceId, plan.length + delay)\n active.set(voiceId, realized)\n return {\n id: voiceId,\n kind: 'recipe',\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const admit = (recipe: Admission, gain: number, distance: number): number | null => {\n const decision = voices.request({ ...(recipe.group ? { group: recipe.group } : {}), priority: recipe.priority ?? busPriority(recipe.bus), gain, distance, length: 0 })\n if (!decision.accepted) return null\n for (const id of decision.evicted) {\n active.get(id)?.stop()\n active.delete(id)\n }\n return decision.id\n }\n\n // a set id (`SoundBank.sets`) plays one of its variants, never the last one, at a drawn rate; a recipe id plays itself at rate 1\n const picker = createSetPicker()\n const resolve = (id: string, random: () => number, chooser = picker): { readonly id: string; readonly rate: number } => {\n if (registry.sound(id)) return { id, rate: 1 }\n const set = registry.set(id)\n return set ? chooser.pick(set, random) : { id, rate: 1 }\n }\n\n const loadSounds = (sounds: readonly SampleSound[]): Promise<SampleLoadReport> => {\n const audio = ready()\n if (!audio) return Promise.resolve({ loaded: [], failed: sounds.flatMap(sampleUrls).map((url) => ({ url, error: 'no audio context' })) })\n return sampleStore.load([...new Set(sounds.flatMap(sampleUrls))], audio)\n }\n\n const sampleInput = (playOptions: PlayOptions, random: () => number, withMemory: boolean) => ({\n random,\n listener,\n environment: playOptions.environment ?? environment,\n ...(withMemory ? { memory } : {}),\n ...(options.distance ? { distanceMode: options.distance } : {}),\n ...(playOptions.volume === undefined ? {} : { volume: playOptions.volume }),\n ...(playOptions.intensity === undefined ? {} : { intensity: playOptions.intensity }),\n ...(playOptions.distance === undefined ? {} : { distance: playOptions.distance }),\n ...(playOptions.position ? { position: playOptions.position } : {}),\n ...(playOptions.occlusion !== undefined\n ? { occlusion: playOptions.occlusion }\n : options.occlusion && playOptions.position\n ? { occlusion: options.occlusion(playOptions.position) }\n : {}),\n })\n\n // undefined: the files are not ready and there is no fallback, so the recipe of the same id (if any) plays\n const playSample = (sample: SampleSound, playOptions: PlayOptions, random: () => number, store: NoiseStore): VoiceHandle | null | undefined => {\n if (busSettings.get(sample.bus)?.muted) return null\n if (!sampleStore.ready(sampleUrls(sample))) {\n if (options.samples?.autoLoad !== false && ready()) void loadSounds([sample]).catch(() => undefined)\n if (sample.fallback && sample.fallback !== sample.id) return playWith(sample.fallback, playOptions, random, store, sample.id)\n return registry.sound(sample.id) ? undefined : null\n }\n const plan = planSample(sample, sampleInput(playOptions, playOptions.seed === undefined ? random : createRng(playOptions.seed), true))\n if (!plan) return null\n const audio = ready()\n if (!audio) return null\n unlockContext(audio)\n advance()\n const voiceId = admit(plan, plan.level, plan.distance)\n if (voiceId === null) return null\n const requestedAt = audio.currentTime\n const time = requestedAt + (playOptions.delay ?? 0)\n const chokeList = sample.choke ? choked(sample.id) : undefined\n const realized = realizeSample(plan, { context: audio, output: sampleOutput(plan.bus), buffer: (url) => sampleStore.buffer(url), time })\n const sampleBank = registry.bankOf(plan.id)\n announce({\n id: plan.id,\n kind: 'sample',\n ...(sampleBank ? { bank: sampleBank } : {}),\n requestedAt,\n startAt: time,\n outputLatency: latencyOf(audio),\n level: plan.level,\n distance: plan.distance,\n ...(plan.pan === undefined ? {} : { pan: plan.pan }),\n layers: plan.layers.map((layer) => ({ role: layer.role, url: layer.url, take: layer.take, rate: layer.rate })),\n ...(plan.tier ? { tier: plan.tier } : {}),\n })\n voices.setLength(voiceId, sampleLength(plan, (url) => sampleStore.seconds(url)) + (playOptions.delay ?? 0))\n active.set(voiceId, realized)\n if (chokeList && sample.choke) {\n chokeList.push({ id: voiceId, voice: realized })\n while (chokeList.length > Math.max(1, sample.choke.voices)) {\n const oldest = chokeList.shift()\n if (!oldest) break\n oldest.voice.fade(time, sample.choke.fade ?? 0.03)\n voices.release(oldest.id)\n active.delete(oldest.id)\n }\n }\n return {\n id: voiceId,\n kind: 'sample',\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const playWith = (asked: string, playOptions: PlayOptions, streamRandom: () => number, store: NoiseStore, fallbackOf?: string): VoiceHandle | null => {\n const sample = fallbackOf === undefined ? registry.sample(asked) : undefined\n if (sample) {\n const played = playSample(sample, playOptions, streamRandom, store)\n if (played !== undefined) return played\n }\n const seeded = playOptions.seed === undefined ? null : createRng(playOptions.seed)\n const { id, rate } = resolve(asked, seeded ?? streamRandom)\n const random = seeded ?? streamRandom\n const recipe = registry.sound(id)\n if (!recipe || busSettings.get(recipe.bus)?.muted) return null\n const distance = playOptions.distance ?? (playOptions.position ? listenerDistance(listener, playOptions.position, options.distance) : 0)\n const level = falloffGain(recipe.falloff, playOptions.volume ?? 1, distance)\n const silent = isSilent(recipe.falloff, level)\n // a sound too quiet to play does not even start the context (the team routines return before touching it)\n if (silent && !recipe.keepSilent) return null\n const audio = ready()\n if (!audio) return null\n unlockContext(audio)\n advance()\n const voiceId = silent ? undefined : admit(recipe, level, distance)\n if (voiceId === null) return null\n if (!silent && usesNoise(recipe)) prepareNoise(store, audio, mix.noise.seconds)\n const plan = planSound(recipe, inputFor(recipe, playOptions, random))\n return plan ? start(retunePlan(plan, rate), store, voiceId, playOptions.delay, fallbackOf, playOptions.urgent) : null\n }\n\n const randomFor = (playOptions: PlayOptions): (() => number) => {\n if (playOptions.channel === undefined) return engineRandom\n const existing = named.get(playOptions.channel)\n if (existing) return existing\n const stream = streamFor(seed, playOptions.channel)\n named.set(playOptions.channel, stream)\n return stream\n }\n\n // pure: a set is drawn with a picker of its own, so planning never moves what `play` picks next\n const planWith = (asked: string, playOptions: PlayOptions, random: () => number): SoundPlan | null => {\n const { id, rate } = resolve(asked, random, createSetPicker())\n const recipe = registry.sound(id)\n const plan = recipe ? planSound(recipe, inputFor(recipe, playOptions, random)) : null\n return plan ? retunePlan(plan, rate) : null\n }\n\n const loopHost: LoopHost = {\n ready,\n output: outputFor,\n prepareNoise: () => context && prepareNoise(shared, context, mix.noise.seconds),\n noise: () => noiseBuffer(shared, context as AudioContext, mix.noise.seconds),\n register: (loop) => void loops.add(loop),\n unregister: (loop) => void loops.delete(loop),\n listener: () => listener,\n ...(options.distance ? { distance: options.distance } : {}),\n }\n\n return {\n registry,\n register: (bank) => registry.register(bank),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\n planSample(id, playOptions = {}) {\n const sample = registry.sample(id)\n return sample ? planSample(sample, sampleInput(playOptions, createRng(playOptions.seed ?? seed), false)) : null\n },\n loadSamples(ids) {\n const chosen = (ids ?? registry.sampleIds()).map((id) => registry.sample(id)).filter((sample): sample is SampleSound => sample !== undefined)\n return loadSounds(chosen)\n },\n sampleStatus(id) {\n const sample = registry.sample(id)\n if (!sample) return 'none'\n const statuses = sampleUrls(sample).map((url) => sampleStore.status(url))\n if (statuses.every((status) => status === 'ready')) return 'ready'\n if (statuses.includes('failed')) return 'failed'\n if (statuses.includes('loading')) return 'loading'\n return statuses.includes('ready') ? 'loading' : 'none'\n },\n setEnvironment(next) {\n environment = next\n },\n output: () => chain?.master ?? null,\n addSampleSource(accepts, loader) {\n sources.push({ accepts, loader })\n },\n watchVoices(listener) {\n watchers.add(listener)\n return () => void watchers.delete(listener)\n },\n play: (id, playOptions = {}) => playWith(id, playOptions, randomFor(playOptions), shared),\n playPlan(plan, playOptions = {}) {\n const audio = ready()\n if (!audio) return null\n advance()\n const recipe = { id: plan.id, bus: plan.bus, layers: [], sources: [], priority: plan.priority, ...(plan.group ? { group: plan.group } : {}) }\n const voiceId = plan.silent ? undefined : admit(recipe, plan.level, plan.distance)\n if (voiceId === null) return null\n if (planUsesNoise(plan)) prepareNoise(shared, audio, mix.noise.seconds)\n return start(plan, shared, voiceId, playOptions.delay)\n },\n loop(id, loopOptions = {}) {\n const sample = registry.sample(id)\n if (!sample?.loop) return createLoopHandle(registry.loop(id), loopHost, loopOptions.volume)\n return createSampleLoopHandle(\n sample,\n {\n ready,\n output: sampleOutput,\n buffer: (url) => sampleStore.buffer(url),\n isReady: (sound) => sampleStore.ready(sampleUrls(sound)),\n load: (sound) => (options.samples?.autoLoad === false ? Promise.resolve() : loadSounds([sound])),\n fallback: (volume) => createLoopHandle(registry.loop(sample.fallback ?? sample.id) ?? registry.loop(sample.id), loopHost, volume),\n random: engineRandom,\n register: loopHost.register,\n unregister: loopHost.unregister,\n muted: (bus) => busSettings.get(bus)?.muted === true,\n },\n loopOptions.volume,\n )\n },\n channel(channelOptions) {\n const random = channelOptions.random ?? (channelOptions.seed === undefined ? engineRandom : createRng(channelOptions.seed))\n const store = channelOptions.ownNoise ? createNoiseStore(random) : shared\n return {\n random,\n play: (id, playOptions = {}) => playWith(id, playOptions, random, store),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\n }\n },\n setListener(next) {\n listener = next\n },\n setBus(id, setting) {\n busSettings.set(id, { ...busSettings.get(id), ...setting })\n if (!context) return\n ensureBus(id)\n ;(busNodes.get(id) as GainNode).gain.value = busGain(busSettings.get(id))\n },\n setMix(next) {\n const previous = mix\n mix = resolveMix(next, options.profiles)\n if (!context || !chain) return\n const old = chain\n chain = buildChain(context, mix, engineRandom)\n if (mix.noise.seconds !== previous.noise.seconds) shared.reset()\n for (const node of busNodes.values()) {\n node.disconnect()\n node.connect(chain.master)\n }\n for (const loop of loops) loop.rewire()\n old.disconnect()\n },\n setMaster(gain) {\n mix = { ...mix, master: gain }\n if (chain) chain.master.gain.value = gain\n },\n unlock() {\n const audio = ready()\n if (audio) unlockContext(audio)\n },\n warmUp() {\n const audio = ready()\n if (!audio) return false\n noiseBuffer(shared, audio, mix.noise.seconds)\n return true\n },\n level(bus) {\n watched.add(bus)\n ensureBus(bus)\n const meter = meterOf(bus)\n if (!meter) return 0\n meter.analyser.getFloatTimeDomainData(meter.data)\n let sum = 0\n for (const sample of meter.data) sum += sample * sample\n return Math.sqrt(sum / meter.data.length)\n },\n deferredQueue: () => startQueue?.deferredQueue() ?? null,\n stats() {\n advance()\n const voiceStats = voices.stats()\n return {\n context: context ? context.state : 'none',\n voices: voiceStats.active,\n peak: voiceStats.peak,\n dropped: voiceStats.dropped,\n maxVoices: voiceStats.maxVoices,\n loops: [...loops].filter((loop) => loop.created).length,\n }\n },\n dispose() {\n // closing the context ends every voice; they only leave the limiter\n startQueue?.clear()\n for (const id of active.keys()) voices.release(id)\n for (const loop of [...loops]) loop.stop()\n active.clear()\n void context?.close()\n context = null\n chain = null\n busNodes.clear()\n meters.clear()\n shared.reset()\n sampleStore.clear()\n memory.clear()\n sampleLimiters.clear()\n chokes.clear()\n },\n }\n}\n","/**\n * Measurements of rendered sound (pure, on plain sample arrays), for the criteria C1–C9: when it starts, how loud and how bright it is, which side\n * it is on, how long it rings and how many separate hits a burst has.\n */\n\nexport type Channels = readonly Float32Array[]\n\n/** Linear amplitude to dBFS (−Infinity for 0). */\nexport const dbOf = (amplitude: number): number => (amplitude > 0 ? 20 * Math.log10(amplitude) : -Infinity)\n\nconst clampIndex = (channels: Channels, index: number): number => Math.max(0, Math.min(channels[0]?.length ?? 0, Math.round(index)))\n\n/** The loudest sample of every channel between two sample indexes (linear). */\nexport function peakOf(channels: Channels, start = 0, end = Number.POSITIVE_INFINITY): number {\n let peak = 0\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, end)\n for (let index = from; index < to; index++) {\n const value = Math.abs(channel[index] as number)\n if (value > peak) peak = value\n }\n }\n return peak\n}\n\n/** Index of the loudest sample (any channel) between two indexes. */\nexport function peakIndex(channels: Channels, start = 0, end = Number.POSITIVE_INFINITY): number {\n let peak = -1\n let at = -1\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, end)\n for (let index = from; index < to; index++) {\n const value = Math.abs(channel[index] as number)\n if (value > peak) {\n peak = value\n at = index\n }\n }\n }\n return at\n}\n\n/** First sample index at or after `start` whose amplitude (any channel) reaches `threshold`, or −1. */\nexport function onsetIndex(channels: Channels, start = 0, threshold = 0.001): number {\n const length = channels[0]?.length ?? 0\n for (let index = clampIndex(channels, start); index < length; index++) {\n for (const channel of channels) if (Math.abs(channel[index] as number) >= threshold) return index\n }\n return -1\n}\n\n/** RMS of all channels between two indexes, dBFS. */\nexport function rmsDb(channels: Channels, start: number, end: number): number {\n let sum = 0\n let count = 0\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, Math.round(end))\n for (let index = from; index < to; index++) {\n const value = channel[index] as number\n sum += value * value\n count++\n }\n }\n return count === 0 ? -Infinity : dbOf(Math.sqrt(sum / count))\n}\n\n/** Spectral centroid (Hz) of `size` samples from `start` (channels summed, Hann window, plain DFT): the brightness of the sound. */\nexport function centroidHz(channels: Channels, sampleRate: number, start: number, size = 2048): number {\n const from = clampIndex(channels, start)\n const frame = new Float64Array(size)\n for (const channel of channels) {\n for (let index = 0; index < size; index++) frame[index] = (frame[index] as number) + ((channel[from + index] as number | undefined) ?? 0)\n }\n for (let index = 0; index < size; index++) frame[index] = (frame[index] as number) * (0.5 - 0.5 * Math.cos((2 * Math.PI * index) / (size - 1)))\n let weighted = 0\n let total = 0\n const bins = size / 2\n for (let bin = 1; bin < bins; bin++) {\n let re = 0\n let im = 0\n const step = (2 * Math.PI * bin) / size\n for (let index = 0; index < size; index++) {\n const value = frame[index] as number\n re += value * Math.cos(step * index)\n im -= value * Math.sin(step * index)\n }\n const magnitude = Math.hypot(re, im)\n weighted += magnitude * ((bin * sampleRate) / size)\n total += magnitude\n }\n return total > 0 ? weighted / total : 0\n}\n\n/** Energy balance from −1 (all left) to 1 (all right) between two indexes. */\nexport function balanceOf(left: Float32Array, right: Float32Array, start: number, end: number): number {\n let l = 0\n let r = 0\n const to = Math.min(left.length, right.length, Math.round(end))\n for (let index = Math.max(0, Math.round(start)); index < to; index++) {\n l += (left[index] as number) ** 2\n r += (right[index] as number) ** 2\n }\n return l + r > 0 ? (r - l) / (r + l) : 0\n}\n\n/** Seconds from `start` to the last 10 ms window louder than `floorDb` (how long the sound rings, tail included). */\nexport function ringSeconds(channels: Channels, sampleRate: number, start: number, floorDb = -60): number {\n const window = Math.max(1, Math.round(sampleRate * 0.01))\n const length = channels[0]?.length ?? 0\n let last = clampIndex(channels, start)\n for (let index = last; index < length; index += window) {\n if (dbOf(peakOf(channels, index, index + window)) > floorDb) last = index + window\n }\n return (last - start) / sampleRate\n}\n\n/**\n * Separate hits in a burst: attacks of the 2 ms envelope, where it jumps to twice the mean of the 20 ms before it and reaches `threshold`, at least\n * 30 ms apart (so a rapid fire over a long tail still counts every shot).\n */\nexport function countHits(channels: Channels, sampleRate: number, threshold: number): number {\n const window = Math.max(1, Math.round(sampleRate * 0.002))\n const length = channels[0]?.length ?? 0\n const envelope: number[] = []\n for (let index = 0; index < length; index += window) envelope.push(peakOf(channels, index, index + window))\n const history = 10\n const refractory = Math.round(0.03 / 0.002)\n let hits = 0\n let quietUntil = -1\n for (let index = 0; index < envelope.length; index++) {\n const level = envelope[index] as number\n if (index < quietUntil || level < threshold) continue\n let sum = 0\n for (let back = Math.max(0, index - history); back < index; back++) sum += envelope[back] as number\n const before = index === 0 ? 0 : sum / Math.min(history, index)\n if (level >= 2 * before) {\n hits++\n quietUntil = index + refractory\n }\n }\n return hits\n}\n\n/** Peak of the last `seconds` of a file against its own peak, dB (≤ −40: it fades out, it does not end on a cut). */\nexport function endDropDb(channels: Channels, sampleRate: number, seconds = 0.005): number {\n const length = channels[0]?.length ?? 0\n const whole = peakOf(channels)\n if (whole === 0) return -Infinity\n return dbOf(peakOf(channels, length - Math.round(sampleRate * seconds), length) / whole)\n}\n","/**\n * The measuring harness of the sound criteria (C1–C10 of the sound checklist). Each criterion plays the sound through a real engine on an\n * `OfflineAudioContext` (the same mix, limiter and realizer the game uses, rendered faster than real time), and measures the rendered output: when it\n * starts against the event, how loud and bright it is at each distance, which side, how many takes, how it ends. Runs in a browser (or anything with\n * an `OfflineAudioContext`); C10 is the owner's ear, so it is left open with a recording to listen to (`recordOutput`).\n */\nimport type { MixProfile } from '../mix'\nimport type { SoundBank } from '../recipe'\nimport { createRng } from '../rng'\nimport { planSample, sampleUrls } from '../sample'\nimport type { SampleEnvironment, SampleSound } from '../sample'\nimport { createAudioEngine } from '../webaudio/engine'\nimport type { AudioEngine, PlayOptions, VoiceStartEvent } from '../webaudio/engine'\nimport type { SampleLoader } from '../webaudio/sample-store'\nimport { balanceOf, centroidHz, dbOf, endDropDb, onsetIndex, peakIndex, peakOf, ringSeconds, rmsDb } from './analyze'\nimport type { Channels } from './analyze'\n\nexport const CRITERIA = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'] as const\nexport type CriterionId = (typeof CRITERIA)[number]\n\n/** The targets of the checklist, as numbers the harness compares with. */\nexport const CRITERIA_TARGETS = {\n /** C1: event to the first sample, and onset to the peak (one 60 fps frame). */\n syncMs: 20,\n peakAfterOnsetMs: 1000 / 60,\n /** C3: distances measured, metres. */\n distances: [1, 10, 50, 200] as readonly number[],\n /** C5: plays, distinct takes and the pitch range (fraction). */\n plays: 10,\n minTakes: 4,\n pitch: [0.03, 0.05] as const,\n /** C6: the highest peak, dBFS. */\n peakDb: -1,\n /** C8: the end of each file against its peak, dB. */\n endDropDb: -40,\n /** C9: a burst of rapid fire. */\n burst: 20,\n burstSpacing: 0.06,\n} as const\n\nexport type CriterionResult = {\n readonly id: CriterionId\n /** `null`: not decided by the harness (C10, the owner's ear). */\n readonly pass: boolean | null\n /** What was measured, short (the bench prints it). */\n readonly value: string\n readonly target: string\n readonly data?: Readonly<Record<string, unknown>>\n}\n\n/** One action of the game and the sound it must play (C2). */\nexport type ActionCheck = { readonly action: string; readonly play: string; readonly expect: string; readonly options?: PlayOptions }\n\nexport type MeasureOptions = {\n /** The sample sound measured. */\n readonly sound: string\n readonly banks: readonly SoundBank[]\n readonly loader: SampleLoader\n /** The mixing chain the game uses (default the engine's default). */\n readonly mix?: string | MixProfile\n readonly sampleRate?: number\n /** `new OfflineAudioContext(...)` by default. */\n readonly createOfflineContext?: (channels: number, length: number, sampleRate: number) => OfflineAudioContext\n /** The live context's `baseLatency` (s), added to the rendered delay for C1. */\n readonly baseLatency?: number\n /** The device's `outputLatency` (s), reported with C1 but not counted (it is the speakers', not the game's). */\n readonly outputLatency?: number\n /** C2: the actions to check (default the sound for itself). */\n readonly actions?: readonly ActionCheck[]\n /** C6: sound ids loudest first, the order the buses must keep (tiro > explosão > impacto > passo). */\n readonly loudnessOrder?: readonly string[]\n}\n\ntype Render = { readonly channels: Channels; readonly sampleRate: number; readonly events: readonly VoiceStartEvent[]; readonly handles: number }\n\nconst EVENT_AT = 0.2\n\nconst offlineFactory = (options: MeasureOptions) =>\n options.createOfflineContext ??\n ((channels: number, length: number, sampleRate: number): OfflineAudioContext => {\n const Constructor = (globalThis as { OfflineAudioContext?: new (channels: number, length: number, sampleRate: number) => OfflineAudioContext }).OfflineAudioContext\n if (!Constructor) throw new Error('no OfflineAudioContext here: the harness runs in a browser')\n return new Constructor(channels, length, sampleRate)\n })\n\n/** Renders what `act` plays on a fresh engine (files loaded first), `seconds` long. */\nasync function render(options: MeasureOptions, seconds: number, act: (engine: AudioEngine) => number, engineExtras: { occlusion?: () => number; environment?: SampleEnvironment } = {}): Promise<Render> {\n const sampleRate = options.sampleRate ?? 48000\n const context = offlineFactory(options)(2, Math.ceil(seconds * sampleRate), sampleRate)\n const events: VoiceStartEvent[] = []\n const engine = createAudioEngine({\n banks: options.banks,\n createContext: () => context as unknown as AudioContext,\n samples: { loader: options.loader, autoLoad: false },\n onVoiceStart: (event) => events.push(event),\n ...(options.mix ? { mix: options.mix } : {}),\n ...(engineExtras.occlusion ? { occlusion: engineExtras.occlusion } : {}),\n ...(engineExtras.environment ? { environment: engineExtras.environment } : {}),\n })\n const ids = [...new Set([options.sound, ...(options.actions ?? []).map((action) => action.play), ...(options.loudnessOrder ?? [])])].filter((id) => engine.registry.sample(id))\n const report = await engine.loadSamples(ids)\n if (report.failed.length > 0) throw new Error(`files did not load: ${report.failed.map((entry) => `${entry.url} (${entry.error})`).join(', ')}`)\n const handles = act(engine)\n const buffer = await context.startRendering()\n const channels = Array.from({ length: buffer.numberOfChannels }, (_, index) => buffer.getChannelData(index))\n return { channels, sampleRate, events, handles }\n}\n\nconst ms = (seconds: number): string => `${(seconds * 1000).toFixed(1)} ms`\nconst db = (value: number): string => (Number.isFinite(value) ? `${value.toFixed(1)} dB` : '−∞')\nconst decreasing = (values: readonly number[]): boolean => values.every((value, index) => index === 0 || value < (values[index - 1] as number))\n\nasync function c1(options: MeasureOptions): Promise<CriterionResult> {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { distance: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 0.001)\n const event = result.events.find((entry) => entry.id === options.sound)\n if (onset < 0 || !event) return { id: 'C1', pass: false, value: 'sem som', target: `≤ ${CRITERIA_TARGETS.syncMs} ms` }\n const delay = onset / result.sampleRate - EVENT_AT + (event.startAt - event.requestedAt - EVENT_AT) + (options.baseLatency ?? 0)\n const peak = peakIndex(result.channels, onset, onset + Math.round(result.sampleRate * 0.25))\n const toPeak = (peak - onset) / result.sampleRate\n const pass = delay <= CRITERIA_TARGETS.syncMs / 1000 && toPeak <= CRITERIA_TARGETS.peakAfterOnsetMs / 1000\n return {\n id: 'C1',\n pass,\n value: `${ms(delay)}, pico +${ms(toPeak)}`,\n target: `≤ ${CRITERIA_TARGETS.syncMs} ms; pico no quadro do contato`,\n data: { delay, toPeak, baseLatency: options.baseLatency ?? 0, outputLatency: options.outputLatency ?? 0 },\n }\n}\n\nasync function c2(options: MeasureOptions): Promise<CriterionResult> {\n const actions = options.actions ?? [{ action: options.sound, play: options.sound, expect: options.sound }]\n const result = await render(options, 0.5, (engine) => {\n let played = 0\n for (const action of actions) if (engine.play(action.play, { distance: 1, ...action.options })) played++\n return played\n })\n const wrong = actions.filter((action, index) => {\n const event = result.events[index]\n return !event || (event.fallbackOf ?? event.id) !== action.expect || event.kind !== 'sample'\n })\n return {\n id: 'C2',\n pass: wrong.length === 0,\n value: `${actions.length - wrong.length}/${actions.length} certas`,\n target: '100% das ações batem com a tabela (arquivo, não o substituto)',\n data: { wrong: wrong.map((action) => action.action), events: result.events.map((event) => `${event.kind}:${event.id}`) },\n }\n}\n\nasync function c3(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const levels: number[] = []\n const brightness: number[] = []\n for (const distance of CRITERIA_TARGETS.distances) {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { position: [0, 0, -distance], seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n levels.push(onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3))\n brightness.push(onset < 0 ? 0 : centroidHz(result.channels, result.sampleRate, onset))\n }\n const far = planSample(sound, { random: createRng(1), distance: CRITERIA_TARGETS.distances.at(-1) as number })\n const switched = (far?.farMix ?? 0) === 1 && (far?.layers.some((layer) => layer.role === 'far') ?? false)\n const pass = decreasing(levels) && decreasing(brightness) && switched\n return {\n id: 'C3',\n pass,\n value: `${levels.map((level) => db(level)).join(' › ')}; ${brightness.map((hz) => `${Math.round(hz)} Hz`).join(' › ')}${switched ? '; longe = far' : '; sem camada far'}`,\n target: 'cai e escurece com a distância; troca para a versão de longe depois de ~50 m',\n data: { distances: CRITERIA_TARGETS.distances, levels, brightness, switched },\n }\n}\n\nasync function c4(options: MeasureOptions): Promise<CriterionResult> {\n const side = async (x: number): Promise<number> => {\n const result = await render(options, 0.8, (engine) => (engine.play(options.sound, { position: [x, 0, -2], seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const [left, right] = result.channels as [Float32Array, Float32Array]\n return balanceOf(left, right, 0, left.length)\n }\n const right = await side(10)\n const left = await side(-10)\n const bright = async (occluded: boolean): Promise<number> => {\n const result = await render(options, 0.8, (engine) => (engine.play(options.sound, { position: [0, 0, -10], seed: 1, delay: EVENT_AT }) ? 1 : 0), occluded ? { occlusion: () => 1 } : {})\n const onset = onsetIndex(result.channels, 0, 1e-5)\n return onset < 0 ? 0 : centroidHz(result.channels, result.sampleRate, onset)\n }\n const clear = await bright(false)\n const wall = await bright(true)\n const pass = right > 0.2 && left < -0.2 && wall < clear * 0.7\n return {\n id: 'C4',\n pass,\n value: `dir ${right.toFixed(2)} esq ${left.toFixed(2)}; parede ${Math.round(wall)} Hz de ${Math.round(clear)} Hz`,\n target: 'lado certo; atrás da parede fica abafado',\n data: { right, left, clear, wall },\n }\n}\n\nasync function c5(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const result = await render(options, 0.3 * CRITERIA_TARGETS.plays + 1, (engine) => {\n let played = 0\n for (let index = 0; index < CRITERIA_TARGETS.plays; index++) if (engine.play(options.sound, { distance: 1, delay: 0.1 + index * 0.3 })) played++\n return played\n })\n const close = result.events.map((event) => event.layers?.find((layer) => layer.role === 'close'))\n const takes = close.map((layer) => layer?.url ?? '')\n const repeats = takes.filter((take, index) => index > 0 && take === takes[index - 1]).length\n const distinct = new Set(takes).size\n const rates = close.map((layer) => layer?.rate ?? 1)\n const spread = (Math.max(...rates) - Math.min(...rates)) / 2\n const pitch = sound.pitch ?? 0.04\n const pass = distinct >= CRITERIA_TARGETS.minTakes && repeats === 0 && pitch >= CRITERIA_TARGETS.pitch[0] && pitch <= CRITERIA_TARGETS.pitch[1] && spread > 0.01\n return {\n id: 'C5',\n pass,\n value: `${distinct} tomadas, ${repeats} repetições seguidas, tom ±${(pitch * 100).toFixed(0)}%`,\n target: `≥ ${CRITERIA_TARGETS.minTakes} variações, nunca a mesma duas vezes, tom ±3–5%`,\n data: { takes, rates },\n }\n}\n\nasync function c6(options: MeasureOptions): Promise<CriterionResult> {\n const peakAt = async (id: string): Promise<{ peak: number; rms: number }> => {\n const result = await render(options, 1.2, (engine) => (engine.play(id, { distance: 1, seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n return { peak: dbOf(peakOf(result.channels)), rms: onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3) }\n }\n const own = await peakAt(options.sound)\n const order = options.loudnessOrder ?? []\n const loudness: number[] = []\n for (const id of order) loudness.push((await peakAt(id)).rms)\n const ordered = order.length < 2 || decreasing(loudness)\n const pass = own.peak <= CRITERIA_TARGETS.peakDb && ordered\n return {\n id: 'C6',\n pass,\n value: `pico ${db(own.peak)}, RMS ${db(own.rms)}${order.length > 1 ? `; ordem ${ordered ? 'ok' : 'errada'}` : ''}`,\n target: 'tiro > explosão > impacto > passo; pico ≤ −1 dBFS',\n data: { peak: own.peak, rms: own.rms, order, loudness },\n }\n}\n\nasync function c7(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n if (!sound.tiers || sound.tiers.length < 2) return { id: 'C7', pass: false, value: 'sem camadas leve/médio/forte', target: 'muda de camada, não só de volume' }\n const at = async (intensity: number): Promise<{ tier: string; rms: number; files: string }> => {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { distance: 1, seed: 1, intensity, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n const event = result.events[0]\n return { tier: event?.tier ?? '', rms: onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3), files: event?.layers?.find((layer) => layer.role === 'close')?.url ?? '' }\n }\n const light = await at(0.1)\n const heavy = await at(0.9)\n const pass = light.tier !== heavy.tier && light.files !== heavy.files && heavy.rms > light.rms\n return {\n id: 'C7',\n pass,\n value: `${light.tier} ${db(light.rms)} → ${heavy.tier} ${db(heavy.rms)}`,\n target: 'golpe fraco x forte troca a camada (leve/médio/forte), não só o volume',\n data: { light, heavy },\n }\n}\n\nasync function c8(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const sampleRate = options.sampleRate ?? 48000\n const decoder = offlineFactory(options)(1, sampleRate, sampleRate)\n const drops: { url: string; drop: number }[] = []\n for (const url of sampleUrls(sound)) {\n const buffer = await decoder.decodeAudioData(await options.loader(url))\n drops.push({ url, drop: endDropDb([buffer.getChannelData(0)], buffer.sampleRate) })\n }\n const worst = drops.reduce((max, entry) => Math.max(max, entry.drop), -Infinity)\n const ring = async (environment: SampleEnvironment): Promise<number> => {\n const result = await render(options, 3, (engine) => (engine.play(options.sound, { distance: 1, seed: 1, environment, delay: EVENT_AT }) ? 1 : 0))\n return ringSeconds(result.channels, result.sampleRate, Math.round(EVENT_AT * result.sampleRate))\n }\n const indoor = await ring('indoor')\n const outdoor = await ring('outdoor')\n const hasTails = Boolean(sound.tail?.indoor?.length && sound.tail?.outdoor?.length)\n const pass = worst <= CRITERIA_TARGETS.endDropDb && hasTails && outdoor > indoor\n return {\n id: 'C8',\n pass,\n value: `fim ${db(worst)}; cauda dentro ${indoor.toFixed(2)} s, fora ${outdoor.toFixed(2)} s${hasTails ? '' : ' (sem as duas caudas)'}`,\n target: 'não corta seco; cauda de interior x exterior coerente',\n data: { drops, indoor, outdoor },\n }\n}\n\nasync function c9(options: MeasureOptions): Promise<CriterionResult> {\n const { burst, burstSpacing } = CRITERIA_TARGETS\n const first = 0.1\n const result = await render(options, burst * burstSpacing + 1.5, (engine) => {\n let played = 0\n for (let index = 0; index < burst; index++) if (engine.play(options.sound, { distance: 1, delay: first + index * burstSpacing })) played++\n return played\n })\n const peak = dbOf(peakOf(result.channels))\n // C9 reads: no pile-up (the level does not build up shot after shot) and no shot that vanishes (every slot carries its shot). RMS of each shot's slot:\n const slots: number[] = []\n for (let index = 0; index < burst; index++) {\n const at = Math.round((first + index * burstSpacing) * result.sampleRate)\n slots.push(rmsDb(result.channels, at, at + Math.round(burstSpacing * result.sampleRate)))\n }\n const sorted = [...slots].sort((a, b) => a - b)\n const median = sorted[Math.floor(sorted.length / 2)] as number\n const vanished = slots.filter((level) => level < median - 6).length\n const buildUp = slots.slice(-5).reduce((sum, level) => sum + level, 0) / 5 - (slots[0] as number)\n const pass = result.handles === burst && vanished === 0 && buildUp <= 6 && peak <= CRITERIA_TARGETS.peakDb\n return {\n id: 'C9',\n pass,\n value: `${result.handles}/${burst} tocaram, ${vanished} sumiram, acúmulo ${buildUp >= 0 ? '+' : ''}${buildUp.toFixed(1)} dB, pico ${db(peak)}`,\n target: 'rajada sem amontoar (acúmulo ≤ 6 dB) nem sumir; pico ≤ −1 dBFS',\n data: { handles: result.handles, slots, vanished, buildUp, peak },\n }\n}\n\n/** Runs the criteria (all by default) and returns one result each, in order. C10 is always open: it is the owner's ear on a recording. */\nexport async function measureCriteria(options: MeasureOptions, only: readonly CriterionId[] = CRITERIA): Promise<CriterionResult[]> {\n const probe = createAudioEngine({ banks: options.banks, createContext: () => null })\n const sound = probe.registry.sample(options.sound)\n if (!sound) throw new Error(`${options.sound} is not a sample sound of these banks`)\n const results: CriterionResult[] = []\n for (const id of only) {\n if (id === 'C1') results.push(await c1(options))\n else if (id === 'C2') results.push(await c2(options))\n else if (id === 'C3') results.push(await c3(options, sound))\n else if (id === 'C4') results.push(await c4(options))\n else if (id === 'C5') results.push(await c5(options, sound))\n else if (id === 'C6') results.push(await c6(options))\n else if (id === 'C7') results.push(await c7(options, sound))\n else if (id === 'C8') results.push(await c8(options, sound))\n else if (id === 'C9') results.push(await c9(options))\n else results.push({ id: 'C10', pass: null, value: 'gravar e ouvir', target: 'aprovado pelo ouvido do dono (print + gravação na 4280)' })\n }\n return results\n}\n\n/**\n * Records what the engine outputs while `act` plays, `seconds` long (the C10 recording): a `MediaRecorder` on a stream tapped from the master. Returns\n * `null` where there is no recorder or no context.\n */\nexport async function recordOutput(engine: AudioEngine, seconds: number, act: () => void): Promise<Blob | null> {\n engine.unlock()\n const output = engine.output()\n const Recorder = (globalThis as { MediaRecorder?: typeof MediaRecorder }).MediaRecorder\n const context = output?.context as AudioContext | undefined\n if (!output || !Recorder || !context || typeof context.createMediaStreamDestination !== 'function') return null\n const tap = context.createMediaStreamDestination()\n output.connect(tap)\n const recorder = new Recorder(tap.stream)\n const chunks: Blob[] = []\n recorder.ondataavailable = (event) => chunks.push(event.data)\n const done = new Promise<void>((resolve) => {\n recorder.onstop = () => resolve()\n })\n recorder.start()\n act()\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n recorder.stop()\n await done\n output.disconnect(tap)\n return new Blob(chunks, { type: recorder.mimeType || 'audio/webm' })\n}\n","/**\n * The sounds a game needs, by category, as the sound checklist lists them (generic, real-world names: a 9 mm pistol, a wooden door): the id a file\n * takes, its priority and the synthesized sound it replaces today (`current`, the A of an A/B). A sound is \"file\" once a bank registers a sample under\n * its id; \"synth\" while only `current` exists; \"missing\" when neither does. Data only: a game adds, renames or drops entries without touching the engine.\n */\n\nexport const SFX_CATEGORIES = ['armas', 'impactos', 'explosoes-fogo', 'personagem', 'veiculos', 'itens-portas', 'ambiente'] as const\nexport type SfxCategory = (typeof SFX_CATEGORIES)[number]\n\nexport type SfxPriority = 1 | 2 | 3\n\nexport type SfxEntry = {\n readonly id: string\n readonly category: SfxCategory\n readonly priority: SfxPriority\n /** The synthesized sound playing in its place today (a recipe id of some bank), if any. */\n readonly current?: string\n}\n\nconst entries = (category: SfxCategory, list: readonly (readonly [id: string, priority: SfxPriority, current?: string])[]): SfxEntry[] =>\n list.map(([id, priority, current]) => ({ id, category, priority, ...(current ? { current } : {}) }))\n\nexport const SFX_CATALOG: readonly SfxEntry[] = [\n ...entries('armas', [\n ['pistol_22lr', 2, 'sfx_pistol'],\n ['pistol_9mm', 1, 'sfx_pistol'],\n ['pistol_45', 1, 'sfx_pistol'],\n ['revolver_38_357', 2, 'sfx_pistol'],\n ['revolver_44_50ae', 3, 'sfx_pistol'],\n ['smg_9mm_auto', 1, 'sfx_pistol'],\n ['shotgun_12', 1, 'sfx_shotgun'],\n ['rifle_5_56', 1, 'sfx_rifle'],\n ['rifle_7_62x39', 1, 'sfx_rifle'],\n ['rifle_auto_burst', 1, 'sfx_rifle'],\n ['rifle_308_3006', 2, 'sfx_rifle'],\n ['sniper_338_300wm', 2, 'sfx_rifle'],\n ['antimateriel_50bmg', 3, 'sfx_rifle'],\n ['suppressed_pistol', 2],\n ['suppressed_rifle', 2],\n ['gunshot_far_pistol', 1],\n ['gunshot_far_rifle', 1],\n ['gunshot_far_shotgun', 1],\n ['gunshot_far_heavy', 2],\n ['gunshot_tail_indoor', 1],\n ['gunshot_tail_outdoor', 1],\n ['bullet_crack_by', 2],\n ['bullet_whiz', 2],\n ['ricochet_metal', 2, 'ping'],\n ['dry_fire', 1],\n ['mag_out', 1],\n ['mag_in', 1],\n ['slide_pull_release', 1],\n ['pump_cycle', 1],\n ['casing_drop_concreto_pistol', 1],\n ['casing_drop_concreto_rifle', 1],\n ['casing_drop_concreto_shell', 1],\n ['casing_drop_madeira_pistol', 1],\n ['casing_drop_madeira_rifle', 1],\n ['casing_drop_madeira_shell', 1],\n ['casing_drop_metal_pistol', 1],\n ['casing_drop_metal_rifle', 1],\n ['casing_drop_metal_shell', 1],\n ['casing_drop_terra_pistol', 1],\n ['casing_drop_terra_rifle', 1],\n ['casing_drop_terra_shell', 1],\n ['rocket_fire', 2],\n ['smg_45_auto', 2, 'sfx_pistol'],\n ['weapon_draw', 2],\n ['suppressor_attach', 3],\n ['suppressor_detach', 3],\n ]),\n ...entries('explosoes-fogo', [\n ['explosion_grenade', 1, 'boom'],\n ['explosion_big', 1, 'boom_big'],\n ['explosion_car', 2, 'boom_big'],\n ['explosion_far', 1],\n ['debris_rain_stone', 1],\n ['molotov_break_ignite', 1, 'glass_shatter'],\n ['fire_ignite', 1, 'hiss'],\n ['fire_loop_small', 1],\n ['fire_loop_large', 1],\n ['fire_extinguish', 2, 'hiss'],\n ['gas_leak_hiss', 2],\n ['structure_collapse', 2, 'crumble'],\n ['grenade_bounce', 1],\n ['c4_plant', 2],\n ['c4_beep', 2],\n ['c4_disarm', 2],\n ]),\n ...entries('personagem', [\n ['footstep_concrete_walk', 1, 'sfx_step'],\n ['footstep_wood_walk', 1, 'sfx_step'],\n ['footstep_dirt_walk', 1, 'sfx_step'],\n ['footstep_grass_walk', 1, 'sfx_step'],\n ['footstep_gravel_walk', 1, 'sfx_step'],\n ['land_concrete', 1, 'sfx_step'],\n ['punch_swing', 1],\n ['punch_hit_body', 1, 'sfx_flesh'],\n ['kick_hit', 1, 'sfx_flesh'],\n ['knife_stab', 1],\n ['blunt_hit', 1],\n ['bite', 1, 'sfx_flesh'],\n ['body_fall', 1],\n ['player_hurt', 2],\n ['footstep_tile_walk', 1, 'sfx_step'],\n ['footstep_water_walk', 1, 'sfx_step'],\n ['footstep_grate_walk', 2, 'sfx_step'],\n ['footstep_duct_walk', 3, 'sfx_step'],\n ['ladder_climb', 2],\n ['swim', 2],\n ['zombie_groan', 1],\n ['zombie_alert', 1],\n ['zombie_attack', 1],\n ['zombie_pain', 1],\n ['zombie_claw_hit', 1, 'sfx_flesh'],\n ['zombie_claw_miss', 2],\n ]),\n ...entries('veiculos', [\n ['engine_loop_car', 1],\n ['engine_start', 1],\n ['crash_light', 1, 'crash'],\n ['crash_heavy', 1, 'crash'],\n ['car_door_open', 1, 'latch'],\n ['car_door_close', 1, 'shut_metal'],\n ['horn_car', 2, 'horn'],\n ['tire_skid_asphalt', 2],\n ]),\n ...entries('itens-portas', [\n ['item_pickup_metal', 1],\n ['can_open', 1],\n ['can_crush', 1],\n ['door_wood_open', 1, 'latch'],\n ['door_wood_close', 1, 'shut_wood'],\n ['door_creak', 1, 'creak_wood'],\n ['door_locked_rattle', 1, 'rattle'],\n ['drawer_open', 2, 'slide'],\n ['fridge_close', 2, 'shut_metal'],\n ]),\n ...entries('ambiente', [\n ['rain_loop', 2],\n ['wind_loop', 2],\n ['thunder_near', 2],\n ['thunder_far', 2],\n ['water_splash', 2],\n ['helicopter_loop', 3],\n ]),\n]\n\n/** The materials of the impact matrix, with the group whose synthesized sound plays for them today. */\nexport const SFX_MATERIALS = [\n ['steel', 'metal'],\n ['aluminium', 'metal'],\n ['wood', 'wood'],\n ['plywood', 'wood'],\n ['mdf', 'wood'],\n ['glass', 'glass'],\n ['tempered_glass', 'glass'],\n ['ceramic', 'glass'],\n ['concrete', 'masonry'],\n ['brick', 'masonry'],\n ['plaster', 'masonry'],\n ['plastic', 'soft'],\n ['fabric', 'soft'],\n ['paper', 'soft'],\n ['foliage', 'soft'],\n ['soil', 'soft'],\n ['flesh', 'soft'],\n] as const satisfies readonly (readonly [string, string])[]\nexport type SfxMaterial = (typeof SFX_MATERIALS)[number][0]\n\nexport const SFX_BLOWS = ['bullet', 'blunt', 'blade', 'break', 'drag'] as const\nexport type SfxBlow = (typeof SFX_BLOWS)[number]\n\n// the destruction renderer's synthesized sounds by material group (art scene keys), the A side of the matrix\nconst CURRENT_BY_GROUP: Readonly<Record<string, Readonly<Partial<Record<SfxBlow, string>>>>> = {\n metal: { bullet: 'clang', blunt: 'clang', blade: 'clang', break: 'clang', drag: 'drag_metal' },\n wood: { bullet: 'wood_hit', blunt: 'wood_hit', blade: 'wood_hit', break: 'crack', drag: 'drag_wood' },\n glass: { bullet: 'ping', blunt: 'ping', break: 'glass_shatter', drag: 'drag_glass' },\n masonry: { bullet: 'chip', blunt: 'chip', blade: 'chip', break: 'crumble', drag: 'drag_masonry' },\n soft: { bullet: 'thud', blunt: 'thud', blade: 'thud', break: 'thud', drag: 'drag_soft' },\n}\n\n/** The id a file of the matrix takes: `impact_<material>_<blow>` (`impact_concrete_bullet`). */\nexport const impactSoundId = (material: SfxMaterial, blow: SfxBlow): string => `impact_${material}_${blow}`\n\n/** The impact matrix as entries (the `impactos` category of the catalogue). */\nexport const SFX_IMPACTS: readonly SfxEntry[] = SFX_MATERIALS.flatMap(([material, group]) =>\n SFX_BLOWS.map((blow) => {\n const current = CURRENT_BY_GROUP[group]?.[blow]\n return { id: impactSoundId(material, blow), category: 'impactos' as const, priority: (['steel', 'wood', 'glass', 'concrete', 'brick', 'soil', 'flesh'].includes(material) && blow === 'bullet' ? 1 : 2) as SfxPriority, ...(current ? { current } : {}) }\n }),\n)\n\n/** Where an entry stands in an engine: a file registered (`file`), only the synthesized sound (`synth`), or nothing (`missing`). */\nexport type SfxState = 'file' | 'synth' | 'missing'\n\nexport function sfxState(entry: SfxEntry, has: { sample(id: string): unknown; sound(id: string): unknown }): SfxState {\n if (has.sample(entry.id)) return 'file'\n if ((entry.current && has.sound(entry.current)) || has.sound(entry.id)) return 'synth'\n return 'missing'\n}\n","/**\n * The manifest the converter (`scripts/sfx-convert.mjs`) writes next to the converted files: every sound id with its takes per layer, the file\n * facts the criteria check (rate, channels, peak, length) and where each file came from. `sampleBankFromManifest` turns it into a `SoundBank`\n * of `SampleSound`s, with the bus and the numbers of each sound given by the caller.\n */\nimport type { BusId, Falloff, SoundBank } from './recipe'\nimport type { SampleCrossover, SampleRef, SampleSound } from './sample'\n\n/** Licences the SDK accepts (the files are redistributed on npm): public domain or attribution only. */\nexport const SDK_LICENSES = ['CC0', 'CC-BY'] as const\nexport type SdkLicense = (typeof SDK_LICENSES)[number]\n\nexport type SfxFileEntry = {\n /** Path from the manifest's folder: `armas/pistol_9mm_close_01.ogg`. */\n readonly file: string\n readonly sampleRate: number\n readonly channels: number\n /** dBFS. */\n readonly peak: number\n readonly seconds: number\n readonly source: string\n readonly author: string\n readonly license: SdkLicense\n}\n\n/** The layers a file name can end in: `<id>_<layer>_<nn>` (`pistol_9mm_close_01`); a name without one is a `close` take. */\nexport const SFX_LAYERS = ['close', 'far', 'tail_in', 'tail_out'] as const\nexport type SfxLayer = (typeof SFX_LAYERS)[number]\n\nexport type SfxManifestSound = {\n readonly id: string\n readonly category: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly SfxFileEntry[]>>>\n}\n\nexport type SfxManifest = {\n readonly version: 1\n readonly format: { readonly codec: 'vorbis'; readonly sampleRate: number; readonly channels: number; readonly peakDb: number }\n readonly sounds: readonly SfxManifestSound[]\n}\n\n/** The numbers of one sound that the files do not say (bus, curve, pitch...). */\nexport type SampleDefaults = {\n readonly bus: BusId\n readonly gain?: number\n readonly pitch?: number\n readonly crossover?: SampleCrossover\n readonly tailGain?: number\n readonly falloff?: Falloff\n readonly cutoffK?: number\n readonly group?: string\n readonly priority?: number\n readonly fallback?: string\n}\n\nexport type SampleBankOptions = {\n readonly id: string\n /** Prefix of every url (where the manifest's folder is served: `/sfx/`). Default ''. */\n readonly baseUrl?: string\n /** Numbers per sound id, or one function; a sound with neither is left out (it has no bus). */\n readonly sounds?: Readonly<Record<string, SampleDefaults>>\n readonly defaults?: (sound: { readonly id: string; readonly category: string }) => SampleDefaults | undefined\n}\n\n/** The strength suffixes of a sound id (`kick_hit_heavy`): takes of the tiers of `kick_hit`, from these intensities. */\nexport const SFX_TIERS: Readonly<Record<string, number>> = { light: 0, medium: 0.34, heavy: 0.67 }\n\n/** Splits a file name (no extension) into its sound id, layer and take number. */\nexport function parseSfxName(name: string): { readonly id: string; readonly layer: SfxLayer; readonly take: number } {\n const match = /^(.*?)(?:_(close|far|tail_in|tail_out))?(?:_(\\d+))?$/.exec(name)\n const id = match?.[1] || name\n const layer = (match?.[2] as SfxLayer | undefined) ?? 'close'\n const take = match?.[3] ? Number(match[3]) : 1\n return { id, layer, take }\n}\n\n/** The base id and tier of a sound id: `kick_hit_heavy` → `kick_hit`, `heavy`. */\nexport function splitTier(id: string): { readonly base: string; readonly tier?: string } {\n const match = /^(.*)_(light|medium|heavy)$/.exec(id)\n return match ? { base: match[1] as string, tier: match[2] as string } : { base: id }\n}\n\n/** What `sampleBankFromManifest` reads of a manifest: the sounds, their layers and where each file came from (any licence string). */\nexport type SfxManifestLike = {\n readonly sounds: readonly {\n readonly id: string\n readonly category: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly { readonly file: string; readonly source: string; readonly author: string; readonly license: string }[]>>>\n }[]\n}\n\nconst refsOf = (entries: readonly { readonly file: string }[] | undefined, baseUrl: string): SampleRef[] => (entries ?? []).map((entry) => ({ url: `${baseUrl}${entry.file}` }))\n\n/** A bank of sample sounds from a manifest. */\nexport function sampleBankFromManifest(manifest: SfxManifestLike, options: SampleBankOptions): SoundBank {\n const baseUrl = options.baseUrl ?? ''\n const samples: SampleSound[] = []\n // `<id>_light`, `_medium`, `_heavy` are the tiers of `<id>`, gathered under it\n type Sound = SfxManifestLike['sounds'][number]\n const tiersOf = new Map<string, Sound[]>()\n for (const sound of manifest.sounds) {\n const { base, tier } = splitTier(sound.id)\n if (tier) tiersOf.set(base, [...(tiersOf.get(base) ?? []), sound])\n }\n const bases = new Map<string, Sound>()\n for (const sound of manifest.sounds) {\n if (!splitTier(sound.id).tier) bases.set(sound.id, sound)\n }\n for (const [base, tiers] of tiersOf) {\n if (!bases.has(base)) bases.set(base, { id: base, category: tiers[0]?.category ?? '', layers: { close: tiers[0]?.layers.close ?? [] } })\n }\n for (const sound of bases.values()) {\n const numbers = options.sounds?.[sound.id] ?? options.defaults?.(sound)\n const close = refsOf(sound.layers.close, baseUrl)\n if (!numbers || close.length === 0) continue\n const tiers = (tiersOf.get(sound.id) ?? [])\n .map((tier) => {\n const name = splitTier(tier.id).tier as string\n const tierFar = refsOf(tier.layers.far, baseUrl)\n return { name, from: SFX_TIERS[name] ?? 0, close: refsOf(tier.layers.close, baseUrl), ...(tierFar.length > 0 ? { far: tierFar } : {}) }\n })\n .sort((a, b) => a.from - b.from)\n const far = refsOf(sound.layers.far, baseUrl)\n const indoor = refsOf(sound.layers.tail_in, baseUrl)\n const outdoor = refsOf(sound.layers.tail_out, baseUrl)\n const files = [sound, ...(tiersOf.get(sound.id) ?? [])].flatMap((entry) => Object.values(entry.layers).flatMap((entries) => entries ?? []))\n samples.push({\n id: sound.id,\n bus: numbers.bus,\n close,\n ...(far.length > 0 ? { far } : {}),\n ...(tiers.length > 0 ? { tiers } : {}),\n ...(numbers.crossover ? { crossover: numbers.crossover } : {}),\n ...(indoor.length > 0 || outdoor.length > 0\n ? { tail: { ...(indoor.length > 0 ? { indoor } : {}), ...(outdoor.length > 0 ? { outdoor } : {}), ...(numbers.tailGain === undefined ? {} : { gain: numbers.tailGain }) } }\n : {}),\n ...(numbers.pitch === undefined ? {} : { pitch: numbers.pitch }),\n ...(numbers.gain === undefined ? {} : { gain: numbers.gain }),\n ...(numbers.falloff ? { falloff: numbers.falloff } : {}),\n ...(numbers.cutoffK === undefined ? {} : { cutoffK: numbers.cutoffK }),\n ...(numbers.group ? { group: numbers.group } : {}),\n ...(numbers.priority === undefined ? {} : { priority: numbers.priority }),\n ...(numbers.fallback ? { fallback: numbers.fallback } : {}),\n sources: files.map((file) => `${file.file}: ${file.source} ${file.author} ${file.license}`),\n })\n }\n return { id: options.id, samples }\n}\n","/**\n * The kit's own recorded sounds: the files in `assets/sfx/` (CC0 / CC-BY, credited in `assets/sfx/CREDITOS.md`) and the numbers each one plays\n * with. `kitSampleBank` turns the converter's manifest into a bank; `KIT_SAMPLE_ALIASES` lets a recipe id the kit already plays (`shut_wood`,\n * `rattle`...) be answered by the takes of a file id (`door_wood_shut`), so a sound that was synthesized becomes the recording with no change where\n * it is played: the recipe of the same id plays while the files load, and wherever they cannot be fetched (`file://`). `loadKitSamples` fetches the\n * manifest from where the folder is served and registers the bank on an engine.\n */\nimport { sampleBankFromManifest } from './manifest'\nimport type { SampleDefaults, SfxManifest, SfxManifestSound } from './manifest'\nimport type { BusId, SoundBank } from './recipe'\n\n/** The bus of a manifest category (the folder the file sits in). */\nexport const KIT_CATEGORY_BUS: Readonly<Record<string, BusId>> = {\n armas: 'weapons',\n impactos: 'world',\n 'explosoes-fogo': 'world',\n personagem: 'world',\n veiculos: 'world',\n 'itens-portas': 'world',\n ambiente: 'ambience',\n}\n\n/** Voice sounds go on the voices bus whatever folder they are in. */\nconst VOICE_IDS = /^(player_(hurt|death|effort|breath)|scream|zombie_)/\n\n/**\n * Recipe id → file id. The recipe keeps playing until the takes of the file id load. Hand-worked leaves (doors, drawers) of `game-destruction-three`\n * and the hand sounds of items.\n */\nexport const KIT_SAMPLE_ALIASES: Readonly<Record<string, string>> = {\n // a house door: the latch giving, the hinge, the leaf meeting the frame, a locked one shaken; a drawer on its runners\n latch: 'metal_latch',\n creak_wood: 'door_creak',\n shut_wood: 'door_wood_shut',\n rattle: 'door_locked_rattle',\n // a drawer stays on its recipe: the recorded runs (1 to 1.9 s) outlast a drawer's pull\n // an item taken in the hand (game-destruction-three grab_* keys)\n grab_hard: 'item_pickup_generic',\n grab_soft: 'item_pickup_leather',\n}\n\n/** The numbers of a sound the files do not say: the bus of its folder, a little pitch spread. */\nexport function kitSampleDefaults(sound: { readonly id: string; readonly category: string }): SampleDefaults | undefined {\n const bus = VOICE_IDS.test(sound.id) ? 'voices' : KIT_CATEGORY_BUS[sound.category]\n if (!bus) return undefined\n return { bus, pitch: sound.category === 'ambiente' || /_loop/.test(sound.id) ? 0 : 0.04 }\n}\n\nexport type KitSampleBankOptions = {\n /** Where the `assets/sfx/` folder is served (`./sfx/`). */\n readonly baseUrl?: string\n /** Recipe id → file id (default `KIT_SAMPLE_ALIASES`); `{}` adds none. */\n readonly aliases?: Readonly<Record<string, string>>\n readonly id?: string\n}\n\n/** The manifest with each alias as one more sound, holding the takes of its file id. */\nexport function withAliases(manifest: SfxManifest, aliases: Readonly<Record<string, string>>): SfxManifest {\n const byId = new Map(manifest.sounds.map((sound) => [sound.id, sound]))\n const extra: SfxManifestSound[] = []\n for (const [alias, target] of Object.entries(aliases)) {\n const sound = byId.get(target)\n if (sound && !byId.has(alias)) extra.push({ ...sound, id: alias })\n }\n return { ...manifest, sounds: [...manifest.sounds, ...extra] }\n}\n\n/** The bank of the kit's files. */\nexport function kitSampleBank(manifest: SfxManifest, options: KitSampleBankOptions = {}): SoundBank {\n return sampleBankFromManifest(withAliases(manifest, options.aliases ?? KIT_SAMPLE_ALIASES), {\n id: options.id ?? 'kit_samples',\n baseUrl: options.baseUrl ?? '',\n defaults: kitSampleDefaults,\n })\n}\n\nexport type LoadKitSamplesOptions = KitSampleBankOptions & {\n /** Gets the manifest (default `fetch` of `<baseUrl>manifest.json`). */\n readonly fetchManifest?: (url: string) => Promise<SfxManifest>\n /** Ids to load right away instead of on their first play (the sounds of the first seconds, so they are not the recipe). */\n readonly preload?: readonly string[]\n}\n\ntype Registers = { register(bank: SoundBank): void; loadSamples?(ids?: readonly string[]): Promise<unknown> }\n\n/** True when `url`, read against the page, is a `file://` one: `fetch` refuses that scheme and the browser logs an error for each try. */\nconst isFileUrl = (url: string): boolean => {\n const page = (globalThis as { location?: { href?: string } }).location?.href\n try {\n return new URL(url, page).protocol === 'file:'\n } catch {\n return false\n }\n}\n\nconst fetchJson = async (url: string): Promise<SfxManifest> => {\n // a page opened from disk keeps the recipes without asking: the refused fetch would only put an error in the console\n if (isFileUrl(url)) throw new Error(`${url}: file:// is not fetched`)\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url}: ${response.status}`)\n return (await response.json()) as SfxManifest\n}\n\n/**\n * Fetches the manifest and registers the bank on the engine. Resolves to the bank, or `null` when the manifest cannot be had (a page opened from\n * `file://`, the folder not served): the recipes keep playing, so that is not an error.\n */\nexport async function loadKitSamples(engine: Registers, options: LoadKitSamplesOptions = {}): Promise<SoundBank | null> {\n const baseUrl = options.baseUrl ?? ''\n let manifest: SfxManifest\n try {\n manifest = await (options.fetchManifest ?? fetchJson)(`${baseUrl}manifest.json`)\n } catch {\n return null\n }\n const bank = kitSampleBank(manifest, options)\n engine.register(bank)\n if (options.preload && engine.loadSamples) void engine.loadSamples(options.preload).catch(() => undefined)\n return bank\n}\n","/**\n * The owner's own sounds, kept out of the kit. Files whose licence the kit cannot redistribute (game rips, paid libraries) never enter git or npm:\n * a list of picks (`user-sounds/picks.json`: sound id, the pack and the files in it) says which file answers which sound, the script `sfx:user`\n * converts those files from the owner's folder into `.sfx-local/` (ignored by git) with a manifest, and `loadUserSamples` registers them on an\n * engine from where that folder is served.\n *\n * Each pick has a role. `primary`: the kit has no recording of that sound, so the owner's file plays. `fallback`: the kit's recording plays first;\n * the owner's file is registered under the same id only when the kit has none loaded (its manifest could not be fetched). Every pick is also\n * registered under `user:<id>`, so a panel can play the owner's take next to the kit's.\n */\nimport { sampleBankFromManifest, splitTier } from './manifest'\nimport type { SfxLayer } from './manifest'\nimport { kitSampleDefaults } from './kit-samples'\nimport type { SoundBank } from './recipe'\n\nexport const USER_SAMPLES_BANK = 'user_samples'\nexport const KIT_SAMPLES_BANK = 'kit_samples'\n/** Prefix of the id each pick is also registered under. */\nexport const USER_SOUND_PREFIX = 'user:'\n\nexport type UserSoundRole = 'primary' | 'fallback'\n\n/** One sound the owner's files answer. */\nexport type UserSoundPick = {\n readonly id: string\n readonly role: UserSoundRole\n /** The kit category (`armas`, `personagem`...): the bus and the folder of the converted files. */\n readonly category: string\n readonly label: string\n /** The pack the files come from (a folder of the owner's sounds). */\n readonly pack: string\n /** Paths inside the pack (matched by their end, so the pack may be nested differently). */\n readonly files: readonly string[]\n /** 0–10: how well the files fit the sound (rate, clipping, band). */\n readonly score: number\n readonly loop?: boolean\n}\n\nexport type UserSoundPicks = {\n readonly version: 1\n readonly author: string\n readonly license: string\n readonly picks: readonly UserSoundPick[]\n}\n\n/** One converted file, as `sfx:user` writes it. */\nexport type UserSfxFile = {\n readonly file: string\n readonly sampleRate: number\n readonly channels: number\n readonly peak: number\n readonly seconds: number\n readonly source: string\n readonly author: string\n readonly license: string\n}\n\nexport type UserSfxSound = {\n readonly id: string\n readonly category: string\n readonly role: UserSoundRole\n readonly label: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly UserSfxFile[]>>>\n}\n\n/** The manifest `sfx:user` writes in `.sfx-local/manifest.json`. */\nexport type UserSfxManifest = {\n readonly version: 1\n readonly sounds: readonly UserSfxSound[]\n}\n\n/** Where a voice came from: the kit's recording, the owner's file, or the synthesized recipe. */\nexport type SoundSource = 'sdk' | 'user' | 'synth'\n\n/** The source of a started voice, from its kind and the bank its id is registered in. */\nexport function soundSourceOf(event: { readonly kind: 'recipe' | 'sample'; readonly bank?: string }): SoundSource {\n if (event.kind === 'recipe') return 'synth'\n return event.bank === USER_SAMPLES_BANK ? 'user' : 'sdk'\n}\n\nexport type UserSampleBankOptions = {\n readonly baseUrl?: string\n /** True for an id the kit already plays from a file: a `fallback` pick is then only registered under `user:<id>`. */\n readonly kitHas?: (id: string) => boolean\n}\n\nexport type UserSampleBankResult = {\n readonly bank: SoundBank\n /** Ids the owner's files now answer (primary picks, and fallbacks the kit lacks). */\n readonly playing: readonly string[]\n /** Fallback ids the kit answers, kept under `user:<id>`. */\n readonly behindKit: readonly string[]\n}\n\n/** The bank of the owner's converted files. */\nexport function userSampleBank(manifest: UserSfxManifest, options: UserSampleBankOptions = {}): UserSampleBankResult {\n const playing: string[] = []\n const behindKit: string[] = []\n const sounds: UserSfxSound[] = []\n for (const picked of manifest.sounds) {\n // a strength tier (`mag_seat_medium`) answers its base id (`mag_seat`), the id the kit's tiers are played by\n const sound = { ...picked, id: splitTier(picked.id).base }\n sounds.push({ ...sound, id: `${USER_SOUND_PREFIX}${sound.id}` })\n if (sound.role === 'fallback' && options.kitHas?.(sound.id)) {\n behindKit.push(sound.id)\n continue\n }\n sounds.push(sound)\n playing.push(sound.id)\n }\n const bank = sampleBankFromManifest(\n { sounds },\n {\n id: USER_SAMPLES_BANK,\n baseUrl: options.baseUrl ?? '',\n defaults: (sound) => kitSampleDefaults({ id: sound.id.replace(USER_SOUND_PREFIX, ''), category: sound.category }),\n },\n )\n return { bank, playing, behindKit }\n}\n\nexport type LoadUserSamplesOptions = UserSampleBankOptions & {\n readonly fetchManifest?: (url: string) => Promise<UserSfxManifest>\n}\n\ntype Registers = { register(bank: SoundBank): void; readonly registry?: { sample(id: string): unknown } }\n\nconst fetchManifestJson = async (url: string): Promise<UserSfxManifest> => {\n const page = (globalThis as { location?: { href?: string } }).location?.href\n if (new URL(url, page ?? 'http://localhost/').protocol === 'file:') throw new Error(`${url}: file:// is not fetched`)\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url}: ${response.status}`)\n return (await response.json()) as UserSfxManifest\n}\n\n/**\n * Fetches `<baseUrl>manifest.json` (default `./sfx-local/`) and registers the owner's files. Call it after the kit's bank loaded, so a fallback\n * pick stays behind the kit's recording. Resolves to `null` when the folder is not there (a machine without the owner's sounds): nothing changes.\n */\nexport async function loadUserSamples(engine: Registers, options: LoadUserSamplesOptions = {}): Promise<UserSampleBankResult | null> {\n const baseUrl = options.baseUrl ?? './sfx-local/'\n let manifest: UserSfxManifest\n try {\n manifest = await (options.fetchManifest ?? fetchManifestJson)(`${baseUrl}manifest.json`)\n } catch {\n return null\n }\n const kitHas = options.kitHas ?? ((id: string): boolean => Boolean(engine.registry?.sample(id)))\n const result = userSampleBank(manifest, { baseUrl, kitHas })\n engine.register(result.bank)\n return result\n}\n","{\n \"sources\": [\"jogo:L62089-62107\"],\n \"note\": \"The game's sfx table P: [lowpass cutoff Hz, peak gain, seconds]. Played as a noise burst with the game's distance curve (falloff game_sfx) and a 0.05 s tail. Team names in `team`.\",\n \"classes\": [\n { \"id\": \"pistol\", \"team\": \"pistola\", \"bus\": \"weapons\", \"cutoff\": 1800, \"gain\": 0.9, \"seconds\": 0.18 },\n { \"id\": \"shotgun\", \"team\": \"escopeta\", \"bus\": \"weapons\", \"cutoff\": 900, \"gain\": 1.2, \"seconds\": 0.35 },\n { \"id\": \"rifle\", \"team\": \"fuzil\", \"bus\": \"weapons\", \"cutoff\": 1400, \"gain\": 1.1, \"seconds\": 0.28 },\n { \"id\": \"long_rifle\", \"team\": \"rifle\", \"bus\": \"weapons\", \"cutoff\": 1100, \"gain\": 1.3, \"seconds\": 0.45 },\n { \"id\": \"impact\", \"team\": \"impacto\", \"bus\": \"world\", \"cutoff\": 2500, \"gain\": 0.25, \"seconds\": 0.05 },\n { \"id\": \"flesh\", \"team\": \"carne\", \"bus\": \"world\", \"cutoff\": 600, \"gain\": 0.35, \"seconds\": 0.08 },\n { \"id\": \"step\", \"team\": \"passo\", \"bus\": \"world\", \"cutoff\": 400, \"gain\": 0.08, \"seconds\": 0.05 },\n { \"id\": \"glass\", \"team\": \"vidro\", \"bus\": \"world\", \"cutoff\": 5000, \"gain\": 0.5, \"seconds\": 0.3 },\n { \"id\": \"wood\", \"team\": \"madeira\", \"bus\": \"world\", \"cutoff\": 700, \"gain\": 0.5, \"seconds\": 0.2 },\n { \"id\": \"reload\", \"team\": \"recarga\", \"bus\": \"weapons\", \"cutoff\": 3000, \"gain\": 0.15, \"seconds\": 0.06 },\n { \"id\": \"empty\", \"team\": \"vazio\", \"bus\": \"weapons\", \"cutoff\": 4000, \"gain\": 0.12, \"seconds\": 0.03 },\n { \"id\": \"explosion\", \"team\": \"explosao\", \"bus\": \"world\", \"cutoff\": 200, \"gain\": 1.6, \"seconds\": 1.4 }\n ],\n \"fallback\": { \"id\": \"unknown\", \"team\": \"(any other name)\", \"bus\": \"world\", \"cutoff\": 1000, \"gain\": 0.5, \"seconds\": 0.1 }\n}\n","import { DISTANCE_CURVES } from '../falloff'\nimport type { BusId, SoundBank, SoundRecipe } from '../recipe'\nimport gameSfxJson from '../data/game-sfx.json'\n\n/** One row of the game's `sfx` table (jogo L62096–62100): lowpass cutoff, peak gain and seconds of a noise burst. */\nexport type NoiseClass = {\n readonly id: string\n /** The name in the team code (`pistola`, `vidro`...). */\n readonly team: string\n readonly bus: BusId\n readonly cutoff: number\n readonly gain: number\n readonly seconds: number\n}\n\ntype GameSfxTable = { readonly sources: readonly string[]; readonly classes: readonly NoiseClass[]; readonly fallback: NoiseClass }\n\nconst GAME_SFX = gameSfxJson as unknown as GameSfxTable\n\n/** The 12 game classes, in the table's order. */\nexport const GAME_SFX_CLASSES: readonly NoiseClass[] = GAME_SFX.classes\n/** What the game plays for a name it does not know: `[1000, 0.5, 0.1]`. */\nexport const GAME_SFX_FALLBACK: NoiseClass = GAME_SFX.fallback\n\n/**\n * A class as a recipe: noise from a random point, the class lowpass (muffled by distance), the peak set at once and an exponential fall to 0.001 over\n * the class seconds, stopped 0.05 s later; the game's distance curve, silent below 0.01. Built in the game's `sfx` order (`burst`).\n */\nexport function noiseClassRecipe(row: NoiseClass, id = `sfx_${row.id}`): SoundRecipe {\n return {\n id,\n bus: row.bus,\n order: 'burst',\n duration: row.seconds,\n tail: 0.05,\n layers: [\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: row.cutoff } }] },\n envelope: [\n [0, row.gain, 'set'],\n ['1d', 0.001, 'exp', 'fixed'],\n ],\n },\n ],\n falloff: DISTANCE_CURVES.game_sfx,\n sources: [...GAME_SFX.sources.map((source) => `${source} ${row.team}`)],\n }\n}\n\n/** The game's classes as a bank (`sfx_pistol`... and `sfx_unknown`). Subject banks pick their own classes from `GAME_SFX_CLASSES`. */\nexport const GAME_SFX_BANK: SoundBank = { id: 'game_sfx', sounds: [...GAME_SFX_CLASSES, GAME_SFX_FALLBACK].map((row) => noiseClassRecipe(row)) }\n","// The art scene's synthesis primitives (cena L1322-L1328) as recipe layers, shared by every subject bank that ports a `sfx.*` of the page: the\n// materials in `destruction-three`, the voices and wounds in `characters-three`. Each helper writes the layer the team routine builds, with its\n// fields in the order the routine draws its random numbers, so a recipe built from them leaves the trace of the team code.\nimport { DISTANCE_CURVES } from '../falloff'\nimport type { BusId, Envelope, Layer, ParamRef, Range, SoundRecipe } from '../recipe'\n\nconst ATTACK = 0.002\n\n/** A length in seconds: a number, a `[min, max]` range or a named number. */\nexport type SceneLength = number | readonly [number, number] | ParamRef\n\n// the layer is `attack + d` long (the art scene's gain rises over `a` and falls over `d`)\nfunction lengthOf(d: SceneLength, attack: number): Range {\n if (typeof d === 'number') return attack + d\n if (Array.isArray(d)) return [attack + d[0], attack + d[1]] as const\n return { ...(d as ParamRef), add: ((d as ParamRef).add ?? 0) + attack }\n}\n\nconst envelope = (attack: number): Envelope => [\n [0, 0.0001, 'set', 'fixed'],\n [attack, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n]\n\nexport type SceneNoise = {\n readonly type?: BiquadFilterType\n readonly f: Range\n /** The filter slides here over `d` (needs a fixed `d`). */\n readonly f2?: number\n readonly q?: number\n readonly a?: number\n readonly d: SceneLength\n readonly vol: Range\n readonly wet?: number\n readonly delay?: Range\n}\n\n/** `sNoise` (cena L1323): noise from a random point, a filter (default lowpass, Q 0.7), the gain rising over `a` and falling over `d`. */\nexport function sceneNoise(o: SceneNoise): Layer {\n const a = o.a ?? ATTACK\n const over = typeof o.d === 'number' ? o.d : 0\n return {\n filters: {\n mode: 'serial',\n bank: [{ type: o.type ?? 'lowpass', frequency: o.f2 === undefined ? { set: o.f } : { set: o.f, to: o.f2, curve: 'exp', over }, q: o.q ?? 0.7 }],\n },\n duration: lengthOf(o.d, a),\n gain: o.vol,\n ...(o.delay === undefined ? {} : { at: o.delay }),\n ...(o.wet === undefined ? {} : { wet: o.wet }),\n source: { kind: 'noise', offset: 'random', offsetScale: 1.5, loop: true },\n envelope: envelope(a),\n }\n}\n\nexport type SceneTone = { readonly wave?: OscillatorType; readonly f: Range; readonly f2?: number; readonly d: SceneLength; readonly vol: Range; readonly wet?: number; readonly delay?: Range }\n\n/** `sTone` (cena L1324): an oscillator sliding from `f` to `f2` (back to `f` when none), the gain rising over 0.002 s and falling over `d`. */\nexport function sceneTone(o: SceneTone): Layer {\n return {\n source: { kind: 'osc', wave: o.wave ?? 'sine', frequency: { from: o.f, to: o.f2 ?? 'from', curve: 'exp', over: 'duration' } },\n duration: lengthOf(o.d, ATTACK),\n gain: o.vol,\n ...(o.delay === undefined ? {} : { at: o.delay }),\n ...(o.wet === undefined ? {} : { wet: o.wet }),\n envelope: envelope(ATTACK),\n }\n}\n\nexport type SceneVoice = {\n /** Start and end frequency of the sweep (the page ramps linearly from `f0` to `f1` over the length). */\n readonly f0: Range\n readonly f1: Range\n /** Length in seconds. */\n readonly d: SceneLength\n /** Centre of the first and second formant (Q 4 and 6) and of the breath band (Q 1.1). */\n readonly fA: Range\n readonly fB: Range\n /** Level of the breath noise. */\n readonly noise: Range\n readonly vol: Range\n readonly wave?: OscillatorType\n}\n\n/**\n * `voice` (cena L1325): an oscillator swept from `f0` to `f1` with a vibrato of 4 to 10 Hz (depth 0.08 of `f0`) through two formant bands plus a band of\n * breath noise, summed and boosted 3.2 times, the gain rising over 0.1 s, held to 0.6 of the length and falling; reverb send 0.45. It is the one\n * layer the page builds with `voice(...)`, so a scream is two of them.\n */\nexport function sceneVoice(o: SceneVoice): Layer {\n return {\n duration: lengthOf(o.d, 0),\n gain: o.vol,\n wet: 0.45,\n source: {\n kind: 'formant_voice',\n wave: o.wave ?? 'sawtooth',\n frequency: { from: o.f0, to: o.f1, curve: 'linear', over: 'duration' },\n vibrato: { rate: [4, 10], depth: 0.08 },\n formants: [\n { frequency: o.fA, q: 4 },\n { frequency: o.fB, q: 6 },\n ],\n breath: { frequency: o.fB, q: 1.1, gain: o.noise },\n mix: 3.2,\n },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.1, 1, 'exp'],\n ['0.6d', 1, 'set'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n }\n}\n\n/** The layer played `count` times (a team `for` loop whose body draws numbers): each pass is its own layer, so the draws stay in the loop's order. */\nexport const sceneMany = (count: number, make: () => Layer): Layer[] => Array.from({ length: count }, make)\n\nexport type SceneRecipeOptions = {\n /** Named numbers drawn first (`PlayOptions.params` can override them). */\n readonly vars?: SoundRecipe['vars']\n readonly bus?: BusId\n readonly group?: string\n}\n\n/** A recipe in the art scene's mix: positional with the art scene's curve (`vol / (1 + d² × 0.008)`) and pan; `line` is the team code it comes from (`cena:<line>`). */\nexport function sceneRecipe(id: string, layers: readonly Layer[], line: string, options: SceneRecipeOptions = {}): SoundRecipe {\n return {\n id,\n bus: options.bus ?? 'world',\n pan: true,\n layers,\n falloff: DISTANCE_CURVES.art_scene,\n ...(options.vars ? { vars: options.vars } : {}),\n ...(options.group ? { group: options.group } : {}),\n sources: [`cena:${line}`],\n }\n}\n","{\n \"id\": \"crowd_rumble\",\n \"bus\": \"ambience\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"noise\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 160 } }] },\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\"jogo:L62116 horda: noise through a 160 Hz lowpass\", \"jogo:L70424 level min(0.16, near × 0.0016)\", \"temporary home until the crowd package (Q12)\"]\n}\n","{\n \"id\": \"engine_saw\",\n \"bus\": \"world\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"osc\", \"wave\": \"sawtooth\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 400 } }] },\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\n \"jogo:L62115 motor: sawtooth through a 400 Hz lowpass\",\n \"jogo:L70421 level 0.035 + speed × 0.003, frequency 38 + speed × 7 (the host drives `set`)\",\n \"temporary home until the vehicles package (Q12)\"\n ]\n}\n","{\n \"id\": \"horn\",\n \"bus\": \"world\",\n \"order\": \"chord\",\n \"duration\": 0.6,\n \"tail\": 0.02,\n \"layers\": [\n { \"source\": { \"kind\": \"osc\", \"wave\": \"square\", \"frequency\": { \"set\": 415 } }, \"envelope\": [[0, 0.08, \"set\"], [0.6, 0.0001, \"set\", \"fixed\"]] },\n { \"source\": { \"kind\": \"osc\", \"wave\": \"square\", \"frequency\": { \"set\": 523 } }, \"envelope\": [[0, 0.08, \"set\"], [0.6, 0.0001, \"set\", \"fixed\"]] }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"jogo:L70272-70276 buzina: squares at 415 and 523 Hz, 0.08 for 0.6 s\", \"temporary home until the vehicles package (Q12)\"]\n}\n","{\n \"id\": \"radio_static\",\n \"bus\": \"world\",\n \"order\": \"static\",\n \"duration\": 0.6,\n \"layers\": [\n {\n \"source\": { \"kind\": \"noise\", \"offset\": \"random\" },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"bandpass\", \"frequency\": { \"set\": 1800 }, \"q\": 0.8 }] },\n \"envelope\": [[0, 0.06, \"set\"], [\"1d\", 0.001, \"exp\", \"fixed\"]]\n }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"jogo:L69998-70004 chiado: noise through a 1800 Hz bandpass (Q 0.8), 0.06 falling over 0.6 s\", \"temporary home until the props or radio package (Q12)\"]\n}\n","{\n \"id\": \"rotor_blades\",\n \"bus\": \"world\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"noise\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 300 } }] },\n \"modulators\": [{ \"target\": \"gain\", \"rate\": 11, \"depth\": 0.5, \"base\": 0.5 }],\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\n \"jogo:L62116-62120 rotor: noise through a 300 Hz lowpass, blade beat as an 11 Hz LFO of 0.5 on a 0.5 gain stage\",\n \"jogo:L70426 level min(0.5, 30 / (distance + 10))\",\n \"temporary home until the vehicles package (Q12)\"\n ]\n}\n","{\n \"id\": \"siren\",\n \"bus\": \"world\",\n \"order\": \"siren\",\n \"duration\": 9,\n \"tail\": 0.2,\n \"layers\": [\n {\n \"wet\": 1.5,\n \"source\": { \"kind\": \"osc\", \"wave\": \"sine\", \"frequency\": { \"set\": 850 } },\n \"modulators\": [{ \"target\": \"frequency\", \"rate\": 0.18, \"depth\": 280 }],\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 1400 } }] },\n \"envelope\": [[0, 0.0001, \"set\", \"fixed\"], [2, 0.035, \"exp\"], [6, 0.035, \"set\"], [9, 0.0001, \"exp\", \"fixed\"]]\n }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"cena:L1369 siren: 850 Hz sine swept ±280 Hz at 0.18 Hz, 1400 Hz lowpass, 0.035 for 9 s, reverb send 1.5\", \"temporary home until the vehicles package (Q12)\"]\n}\n","// Sounds whose subject has no package yet (Q12): they move to vehicles, crowd and props in Phases 7 and 8 and stay here as re-exports.\nimport type { LoopRecipe, SoundBank, SoundRecipe } from '../recipe'\nimport crowdRumble from './crowd_rumble.json'\nimport engineSaw from './engine_saw.json'\nimport horn from './horn.json'\nimport radioStatic from './radio_static.json'\nimport rotorBlades from './rotor_blades.json'\nimport siren from './siren.json'\n\nexport const LIBRARY_SOUNDS: readonly SoundRecipe[] = [horn, radioStatic, siren] as unknown as readonly SoundRecipe[]\nexport const LIBRARY_LOOPS: readonly LoopRecipe[] = [engineSaw, rotorBlades, crowdRumble] as unknown as readonly LoopRecipe[]\nexport const LIBRARY_BANK: SoundBank = { id: 'library', sounds: LIBRARY_SOUNDS, loops: LIBRARY_LOOPS }\n","// The sounds of a vehicle's cabin and body switches (the turn signal relay, the starter, the alarm, the wipers, the belt chime, the lock chirp). Like the\n// library's horn, they live here until the vehicles package has a bank of its own (Q12). Synthesized; no recording.\nimport type { SoundBank, SoundRecipe } from '../recipe'\n\nexport const CABIN_SOUNDS: readonly SoundRecipe[] = [\n {\n id: 'blinker_tick',\n bus: 'world',\n duration: 0.03,\n layers: [\n // the relay: a click of bright noise and a short low knock\n { source: { kind: 'noise', offset: 'random' }, filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 2600 } }] }, envelope: [[0, 0.22, 'set'], [0.025, 0.0001, 'exp', 'fixed']] },\n { source: { kind: 'osc', wave: 'triangle', frequency: { set: 180 } }, envelope: [[0, 0.12, 'set'], [0.03, 0.0001, 'exp', 'fixed']] },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'starter_crank',\n bus: 'world',\n duration: 0.9,\n layers: [\n // the starter motor turning the engine over: low noise chopped at the compression strokes\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 420 } }] },\n modulators: [{ target: 'gain', wave: 'square', rate: 11, depth: 0.08, base: 0.1 }],\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.05, 0.25, 'linear'], [0.8, 0.22, 'set'], [0.9, 0.0001, 'exp', 'fixed']],\n },\n { source: { kind: 'osc', wave: 'sawtooth', frequency: { set: 95, to: 120, curve: 'linear', over: 0.9 } }, filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 300 } }] }, envelope: [[0, 0.04, 'set'], [0.9, 0.0001, 'exp', 'fixed']] },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'car_alarm',\n bus: 'world',\n order: 'siren',\n duration: 3,\n tail: 0.1,\n layers: [\n // the whoop of a car alarm: a square swept up and down three times a second\n {\n source: { kind: 'osc', wave: 'square', frequency: { set: 1100 } },\n modulators: [{ target: 'frequency', wave: 'triangle', rate: 3, depth: 420 }],\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 2600 } }] },\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.05, 0.05, 'linear'], [2.9, 0.05, 'set'], [3, 0.0001, 'exp', 'fixed']],\n },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'alarm_chirp',\n bus: 'world',\n duration: 0.1,\n layers: [{ source: { kind: 'osc', wave: 'square', frequency: { set: 2300 } }, repeat: { count: 2, spacing: 0.16 }, envelope: [[0, 0.05, 'set'], [0.09, 0.0001, 'exp', 'fixed']] }],\n falloff: { model: 'none' },\n },\n {\n id: 'wiper_swish',\n bus: 'world',\n duration: 0.45,\n layers: [\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'bandpass', frequency: { set: 700, to: 1100, curve: 'linear', over: 0.45 }, q: 1.2 }] },\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.2, 0.06, 'linear'], [0.45, 0.0001, 'exp', 'fixed']],\n },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'seatbelt_chime',\n bus: 'world',\n duration: 0.5,\n layers: [{ source: { kind: 'osc', wave: 'sine', frequency: { set: 880 } }, repeat: { count: 3, spacing: 0.7 }, envelope: [[0, 0.06, 'set'], [0.5, 0.0001, 'exp', 'fixed']] }],\n falloff: { model: 'none' },\n },\n] as unknown as readonly SoundRecipe[]\n\nexport const CABIN_BANK: SoundBank = { id: 'vehicle_cabin', sounds: CABIN_SOUNDS, loops: [] }\n","// Foley of the hand: items picked up, opened, drunk and eaten, and the doors, lids and drawers of furniture and vehicles. Synthesised stand-ins under the\n// ids of the sound list (`sons/checklist-sons.md` 5.7 and the car doors of 5.6), so a recorded take filed under the same id replaces the recipe without\n// touching the code that plays it. Every recipe draws its numbers from ranges (pitch about ±4 %, timing and level), so no two plays are the same, and\n// falls off faster than a gunshot and loses its highs with distance: a latch is a near sound.\nimport type { Falloff, Layer, SoundBank, SoundRecipe } from '../recipe'\nimport { sceneMany as many, sceneNoise as noise, sceneTone as tone } from './scene'\n\n/** Small sounds of the hand: `vol / (1 + d² × 0.02)`, lowpass cutoffs `/ (1 + d × 0.04)`, silent below 0.004 (a latch at 10 m is a third, at 50 m gone). */\nexport const FOLEY_FALLOFF: Falloff = {\n model: 'inverse_square',\n k: 0.02,\n cutoffK: 0.04,\n minGain: 0.004,\n}\n\n/** ±`pct` around `f`: the range a recipe draws a frequency from. */\nconst vary = (f: number, pct = 0.04): readonly [number, number] => [Math.round(f * (1 - pct)), Math.round(f * (1 + pct))]\n\nconst foley = (id: string, layers: readonly Layer[], note: string): SoundRecipe => ({\n id,\n bus: 'world',\n pan: true,\n layers,\n falloff: FOLEY_FALLOFF,\n sources: [`sdk: ${note}`],\n})\n\n/** The click of a latch or a catch: a short band of noise and a tick of metal. */\nconst click = (f: number, vol: number, delay: readonly [number, number] | number = 0): Layer[] => [\n noise({\n type: 'bandpass',\n f: vary(f, 0.08),\n q: 4,\n d: [0.018, 0.03],\n vol: [vol * 0.85, vol * 1.1],\n delay,\n }),\n tone({\n f: vary(f * 0.8, 0.06),\n f2: Math.round(f * 0.62),\n d: [0.015, 0.025],\n vol: vol * 0.18,\n delay,\n }),\n]\n\n/** A leaf meeting its frame: the body (a falling tone), the board or panel (a band of noise) and the latch catching right after. */\nconst meet = (body: number, panel: number, vol: number, latch: number): Layer[] => [\n tone({\n f: vary(body),\n f2: Math.round(body * 0.5),\n d: [0.12, 0.16],\n vol: [vol * 0.9, vol * 1.1],\n }),\n noise({\n type: 'bandpass',\n f: vary(panel, 0.06),\n q: 1.2,\n d: [0.08, 0.12],\n vol: [vol * 0.9, vol * 1.1],\n wet: 0.25,\n }),\n ...click(latch, vol * 0.45, [0.012, 0.028]),\n]\n\n/** The doors and lids of furniture and vehicles, by what the leaf is (the room picks one from the item, else from the leaf's material). */\nexport const LEAF_FOLEY: readonly SoundRecipe[] = [\n // a wooden house door or wardrobe door: latch, a short creak, the leaf on the frame (the hard slam adds the frame rattling)\n foley('door_wood_open', click(2400, 0.4), 'the latch of a wooden door giving'),\n foley(\n 'door_creak',\n [\n tone({ f: [190, 240], f2: 310, d: [0.4, 0.55], vol: [0.04, 0.06] }),\n noise({\n type: 'bandpass',\n f: [480, 560],\n q: 6,\n a: 0.05,\n d: [0.35, 0.5],\n vol: [0.1, 0.14],\n }),\n ],\n 'a wooden hinge turning',\n ),\n foley('door_wood_close', meet(120, 600, 0.55, 2400), 'a wooden leaf meeting its frame'),\n foley(\n 'door_wood_slam',\n [\n ...meet(110, 560, 0.85, 2300),\n ...many(3, () =>\n noise({\n type: 'bandpass',\n f: [900, 1500],\n q: 3,\n d: 0.03,\n vol: [0.08, 0.14],\n delay: [0.05, 0.18],\n }),\n ),\n ],\n 'a wooden door slammed: the frame and the hinges rattle after the hit',\n ),\n // a metal door or gate: a hollow panel that rings a little\n foley('door_metal_open_close', [...meet(160, 900, 0.55, 2000), tone({ f: vary(1250), f2: 1150, d: [0.1, 0.16], vol: 0.06, wet: 0.3 })], 'a metal door or gate meeting its frame'),\n foley(\n 'door_creak_metal',\n [\n tone({ f: [620, 760], f2: 900, d: [0.3, 0.4], vol: [0.03, 0.045] }),\n noise({\n type: 'bandpass',\n f: [1300, 1500],\n q: 8,\n a: 0.04,\n d: [0.25, 0.35],\n vol: [0.07, 0.09],\n }),\n ],\n 'a metal hinge turning',\n ),\n // the handle of a locked door shaken: the latch knocking in its keeper, five to seven times in half a second\n foley(\n 'door_locked_rattle',\n [\n ...many(6, () =>\n noise({\n type: 'bandpass',\n f: [1600, 2600],\n q: 3,\n d: [0.025, 0.04],\n vol: [0.22, 0.34],\n delay: [0, 0.45],\n }),\n ),\n ...many(3, () =>\n tone({\n f: [170, 210],\n f2: 120,\n d: 0.05,\n vol: [0.12, 0.18],\n delay: [0.02, 0.4],\n }),\n ),\n ],\n 'the handle of a locked door shaken: latch knocks and the leaf thumping in its frame',\n ),\n // a fridge: the rubber seal lets go with a soft suck, the bottles in the door clink; closing it is a soft thump and the seal pulling shut\n foley(\n 'fridge_open',\n [\n noise({\n type: 'lowpass',\n f: [320, 380],\n a: 0.03,\n d: [0.14, 0.2],\n vol: [0.32, 0.4],\n }),\n noise({\n type: 'bandpass',\n f: [800, 950],\n f2: 1400,\n q: 2,\n a: 0.02,\n d: 0.12,\n vol: [0.08, 0.12],\n }),\n ...many(2, () =>\n tone({\n f: [2600, 4200],\n d: [0.04, 0.08],\n vol: [0.015, 0.03],\n delay: [0.08, 0.22],\n }),\n ),\n ],\n 'a fridge door: the seal letting go and the bottles in the door',\n ),\n foley(\n 'fridge_close',\n [\n tone({ f: vary(85), f2: 45, d: [0.1, 0.13], vol: [0.38, 0.46] }),\n noise({\n type: 'lowpass',\n f: [520, 620],\n d: [0.08, 0.12],\n vol: [0.3, 0.36],\n }),\n noise({\n type: 'lowpass',\n f: [260, 320],\n a: 0.02,\n d: 0.1,\n vol: [0.12, 0.18],\n delay: [0.04, 0.07],\n }),\n ...many(2, () =>\n tone({\n f: [2600, 4200],\n d: [0.04, 0.07],\n vol: [0.015, 0.03],\n delay: [0.03, 0.12],\n }),\n ),\n ],\n 'a fridge door shut: a soft thump, the seal pulling and the bottles',\n ),\n // a microwave: the spring catch of the door, plastic on plastic\n foley(\n 'microwave_open',\n [\n ...click(1800, 0.34),\n tone({\n f: [3000, 3400],\n f2: 2800,\n d: 0.05,\n vol: 0.025,\n delay: [0.01, 0.02],\n }),\n ],\n 'the spring catch of a microwave door',\n ),\n foley(\n 'microwave_close',\n [\n noise({\n type: 'bandpass',\n f: [1200, 1450],\n q: 2.5,\n d: [0.04, 0.06],\n vol: [0.36, 0.44],\n }),\n tone({ f: vary(180), f2: 120, d: 0.05, vol: [0.16, 0.22] }),\n ...click(2200, 0.2, [0.008, 0.016]),\n ],\n 'a microwave door clacking shut',\n ),\n foley('microwave_beep', [tone({ wave: 'square', f: 2000, d: 0.12, vol: 0.05 })], 'the beep of a microwave'),\n // drawers and sliding leaves: the runners, then the stop\n foley(\n 'drawer_open',\n [\n noise({\n type: 'bandpass',\n f: [620, 780],\n q: 2,\n a: 0.04,\n d: [0.28, 0.36],\n vol: [0.18, 0.24],\n }),\n noise({ type: 'bandpass', f: [2000, 2400], q: 5, d: 0.28, vol: 0.04 }),\n ...click(1400, 0.16, [0.28, 0.34]),\n ],\n 'a drawer on its runners and its stop',\n ),\n foley(\n 'drawer_close',\n [\n noise({\n type: 'bandpass',\n f: [620, 780],\n q: 2,\n a: 0.03,\n d: [0.2, 0.28],\n vol: [0.18, 0.24],\n }),\n tone({\n f: vary(150),\n f2: 90,\n d: 0.08,\n vol: [0.22, 0.3],\n delay: [0.2, 0.26],\n }),\n ],\n 'a drawer pushed home',\n ),\n]\n\n/** What the hand does with an item: picking it up by what it is made of, throwing it, and the uses (opening, drinking, eating, first aid). */\nexport const ITEM_FOLEY: readonly SoundRecipe[] = [\n // the hand closing on the item: a touch of skin and cloth, then the item's own small sound\n foley(\n 'item_pickup_metal',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n tone({\n f: [1900, 2600],\n f2: 1700,\n d: [0.05, 0.08],\n vol: [0.06, 0.09],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a metal thing',\n ),\n foley(\n 'item_pickup_plastic',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'bandpass',\n f: [1500, 1900],\n q: 3,\n d: 0.03,\n vol: [0.15, 0.21],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a plastic thing',\n ),\n foley(\n 'item_pickup_glass',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.15 }),\n tone({\n f: [3200, 4200],\n d: [0.05, 0.08],\n vol: [0.038, 0.06],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a glass thing',\n ),\n foley(\n 'item_pickup_paper',\n [\n noise({\n type: 'highpass',\n f: [2600, 3400],\n a: 0.01,\n d: [0.1, 0.14],\n vol: [0.12, 0.18],\n }),\n noise({ type: 'bandpass', f: [800, 1000], q: 1, d: 0.05, vol: 0.12 }),\n ],\n 'picking up paper or cardboard',\n ),\n foley(\n 'item_pickup_fabric',\n [\n noise({\n type: 'bandpass',\n f: [900, 1300],\n q: 0.8,\n a: 0.02,\n d: [0.12, 0.16],\n vol: [0.15, 0.21],\n }),\n ],\n 'picking up cloth',\n ),\n foley(\n 'item_pickup_wood',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'bandpass',\n f: [900, 1100],\n q: 2,\n d: 0.04,\n vol: [0.15, 0.21],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a wooden thing',\n ),\n foley(\n 'item_pickup_food',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'lowpass',\n f: [500, 650],\n d: 0.05,\n vol: 0.12,\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up food',\n ),\n foley(\n 'item_throw',\n [\n noise({\n type: 'bandpass',\n f: [450, 650],\n f2: 1400,\n q: 1.5,\n a: 0.05,\n d: 0.18,\n vol: [0.1, 0.14],\n }),\n ],\n 'the arm throwing something: air',\n ),\n // a can: the tab cracks, the gas hisses out; drinking is gulps; crushing it crumples the sheet\n foley(\n 'can_open',\n [\n ...click(3200, 0.36),\n noise({\n type: 'highpass',\n f: [3600, 4400],\n a: 0.005,\n d: [0.22, 0.3],\n vol: [0.16, 0.22],\n delay: [0.012, 0.02],\n }),\n ...many(5, () => tone({ f: [4000, 7000], d: 0.02, vol: 0.01, delay: [0.05, 0.4] })),\n ],\n 'the tab of a can and the gas hissing out',\n ),\n foley(\n 'can_crush',\n [\n noise({\n type: 'bandpass',\n f: [1600, 2200],\n q: 1.2,\n d: [0.18, 0.25],\n vol: [0.3, 0.38],\n }),\n ...many(6, () =>\n tone({\n f: [1200, 3400],\n f2: 900,\n d: 0.03,\n vol: [0.03, 0.06],\n delay: [0, 0.2],\n }),\n ),\n ],\n 'a can crushed in the hand',\n ),\n foley(\n 'can_puncture_spray',\n [\n noise({\n type: 'highpass',\n f: [2400, 3000],\n a: 0.005,\n d: [0.5, 0.7],\n vol: [0.2, 0.26],\n }),\n noise({ type: 'bandpass', f: [600, 800], q: 2, d: 0.4, vol: 0.06 }),\n ],\n 'a can holed: the jet hissing out',\n ),\n foley(\n 'bottle_open',\n [\n ...many(5, () =>\n noise({\n type: 'bandpass',\n f: [2200, 3000],\n q: 4,\n d: 0.008,\n vol: [0.1, 0.16],\n delay: [0, 0.18],\n }),\n ),\n noise({\n type: 'highpass',\n f: 3800,\n a: 0.005,\n d: 0.12,\n vol: [0.06, 0.1],\n delay: [0.18, 0.22],\n }),\n ],\n 'the screw cap of a bottle turning off',\n ),\n foley(\n 'drink_gulp',\n [\n noise({\n type: 'lowpass',\n f: [280, 360],\n a: 0.02,\n d: [0.1, 0.14],\n vol: [0.24, 0.3],\n }),\n tone({ f: [140, 170], f2: 85, d: [0.08, 0.11], vol: [0.12, 0.16] }),\n ],\n 'a gulp',\n ),\n foley(\n 'eat_crunch',\n [\n ...many(4, () =>\n noise({\n type: 'bandpass',\n f: [1800, 3200],\n q: 1.5,\n d: [0.02, 0.04],\n vol: [0.12, 0.2],\n delay: [0, 0.12],\n }),\n ),\n ],\n 'a bite of something crunchy',\n ),\n foley(\n 'eat_chew',\n [\n noise({\n type: 'lowpass',\n f: [450, 600],\n a: 0.03,\n d: [0.1, 0.14],\n vol: [0.12, 0.16],\n }),\n noise({\n type: 'bandpass',\n f: [1100, 1400],\n q: 2,\n d: 0.04,\n vol: 0.04,\n delay: [0.03, 0.06],\n }),\n ],\n 'chewing',\n ),\n foley(\n 'bandage_wrap',\n [\n noise({\n type: 'bandpass',\n f: [1400, 1800],\n f2: 2400,\n q: 1,\n a: 0.04,\n d: [0.3, 0.4],\n vol: [0.12, 0.16],\n }),\n ],\n 'a bandage unrolled round a limb',\n ),\n foley(\n 'pills_shake',\n [\n ...many(8, () =>\n tone({\n f: [2400, 3600],\n d: 0.015,\n vol: [0.03, 0.05],\n delay: [0, 0.25],\n }),\n ),\n noise({ type: 'bandpass', f: [1500, 1900], q: 2, d: 0.25, vol: 0.05 }),\n ],\n 'pills shaken in their bottle',\n ),\n foley(\n 'medkit_use',\n [\n ...click(1700, 0.24),\n noise({\n type: 'bandpass',\n f: [1000, 1400],\n q: 1,\n a: 0.03,\n d: [0.25, 0.32],\n vol: [0.08, 0.12],\n delay: [0.05, 0.08],\n }),\n ],\n 'a first aid kit opened and rummaged',\n ),\n foley('flashlight_click', click(2600, 0.3), 'the switch of a flashlight'),\n]\n\n/** The foley bank: register it in the engine (`engine.register(FOLEY_BANK)`). */\nexport const FOLEY_BANK: SoundBank = {\n id: 'foley',\n sounds: [...LEAF_FOLEY, ...ITEM_FOLEY],\n}\n\n/** What a picked-up item sounds like, by its heaviest material class. */\nexport const PICKUP_CLASSES = ['metal', 'plastic', 'glass', 'paper', 'fabric', 'wood', 'food'] as const\nexport type PickupClass = (typeof PICKUP_CLASSES)[number]\n\n/** The sound set of a leaf worked by hand: the ids it plays at the latch, while it turns, and as it meets the frame (gently, and slammed). */\nexport type LeafFoley = {\n readonly open: string\n readonly turn?: string\n readonly close: string\n readonly slam?: string\n readonly locked: string\n}\n\n/** The leaf sound sets the kit ships, by name; an item names one (`TestableItem.sounds.leaves`), else the room picks `wood_door` or `metal_door` by the leaf's material. */\nexport const LEAF_FOLEY_SETS: Readonly<Record<string, LeafFoley>> = {\n wood_door: {\n open: 'door_wood_open',\n turn: 'door_creak',\n close: 'door_wood_close',\n slam: 'door_wood_slam',\n locked: 'door_locked_rattle',\n },\n metal_door: {\n open: 'door_wood_open',\n turn: 'door_creak_metal',\n close: 'door_metal_open_close',\n locked: 'door_locked_rattle',\n },\n fridge: {\n open: 'fridge_open',\n close: 'fridge_close',\n locked: 'door_locked_rattle',\n },\n microwave: {\n open: 'microwave_open',\n close: 'microwave_close',\n locked: 'door_locked_rattle',\n },\n drawer: {\n open: 'drawer_open',\n close: 'drawer_close',\n locked: 'door_locked_rattle',\n },\n}\n","// The sounds of a body: footsteps by surface and gait, landings, the swing and the hit of each blow, hurt, bite and grab. Synthesised in the meantime\n// (the kit has no recorded take of these yet): each id is a set of four takes, with the numbers of each take apart, so the same action never\n// sounds twice the same. A recorded take replaces a variant by its id (`register` a bank with the same recipe id) without touching who plays it.\n//\n// How each one is built (what the ear picks first):\n// - a footstep is the heel (a low thump, how hollow the floor is) and then the roll to the toe (the surface's own texture: the grit of concrete,\n// the crunch of gravel, the ring of a metal sheet, the splash of water); a run hits harder, brighter and shorter, heel and toe almost together;\n// - a landing is the whole body's weight on the surface: a deeper thump, the surface texture longer, the clothes after;\n// - a swing is air: a band of noise sweeping up while the limb or the tool speeds up, loudest just before the contact, so it is started early\n// (`SWING_LEAD_SECONDS` of game-contracts) and the contact sound follows it;\n// - a hit on a body is skin (a slap), mass (a thud) and, for a blade, a wet tear; on an object it is only the striking part (knuckles, sole, steel)\n// and the material's own impact plays beside it.\nimport {\n BODY_SOUND_IDS,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n LAND_SOUND_IDS,\n LANDING_IDS,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n} from '@adatechnology/game-contracts'\nimport type { BlowId, BodySoundId, GaitId, LandingId, SurfaceId } from '@adatechnology/game-contracts'\n\nimport type { Falloff, Layer, SoundBank, SoundRecipe, SoundSet } from '../recipe'\nimport { sceneNoise, sceneTone, sceneVoice } from './scene'\n\n/** Takes per id. */\nexport const BODY_FOLEY_TAKES = 4\n\n/** How each take differs from the first: frequency factor, timing factor and level factor (fixed numbers, so takes are really apart). */\nconst TAKES: readonly { readonly f: number; readonly t: number; readonly v: number }[] = [\n { f: 1, t: 1, v: 1 },\n { f: 1.08, t: 0.9, v: 0.92 },\n { f: 0.93, t: 1.12, v: 1.05 },\n { f: 1.03, t: 1.05, v: 0.88 },\n]\n\n\n/** Footsteps fade fast with distance and lose their top: a step 10 m away is a quarter of the level, 30 m a few percent, and duller. */\nexport const FOOTSTEP_FALLOFF: Falloff = { model: 'inverse_square', k: 0.03, cutoffK: 0.03, minGain: 0.004 }\n/** Blows and body sounds carry further than a step. */\nexport const BODY_FALLOFF: Falloff = { model: 'inverse_square', k: 0.012, cutoffK: 0.015, minGain: 0.004 }\n\ntype Take = (typeof TAKES)[number]\n\n/** What a surface sounds like under a foot: the heel's thump and the texture of the roll. */\ntype SurfaceVoice = {\n /** The heel: thump pitch (Hz), its length (s) and level. */\n readonly heel: { readonly f: number; readonly d: number; readonly vol: number }\n /** The roll to the toe and the scuff: a filtered noise. */\n readonly roll: { readonly type: BiquadFilterType; readonly f: number; readonly q: number; readonly d: number; readonly vol: number }\n /** Grit, crunch or drips: short bursts spread after the heel. */\n readonly grains?: { readonly count: number; readonly f: number; readonly q: number; readonly spread: number; readonly vol: number }\n /** A ring of the floor itself (a hollow board, a metal sheet). */\n readonly ring?: readonly { readonly f: number; readonly d: number; readonly vol: number }[]\n /** Water: a sweep of the splash band. */\n readonly splash?: { readonly f: number; readonly f2: number; readonly d: number; readonly vol: number }\n}\n\nconst SURFACES: Readonly<Record<SurfaceId, SurfaceVoice>> = {\n concrete: { heel: { f: 95, d: 0.05, vol: 0.55 }, roll: { type: 'bandpass', f: 2300, q: 1.1, d: 0.05, vol: 0.38 }, grains: { count: 2, f: 4200, q: 2, spread: 0.04, vol: 0.08 } },\n asphalt: { heel: { f: 90, d: 0.05, vol: 0.5 }, roll: { type: 'bandpass', f: 1700, q: 0.9, d: 0.06, vol: 0.36 }, grains: { count: 4, f: 3600, q: 2.5, spread: 0.06, vol: 0.1 } },\n wood: { heel: { f: 130, d: 0.08, vol: 0.55 }, roll: { type: 'lowpass', f: 1300, q: 0.8, d: 0.06, vol: 0.3 }, ring: [{ f: 210, d: 0.1, vol: 0.18 }, { f: 470, d: 0.06, vol: 0.06 }] },\n tile: { heel: { f: 110, d: 0.04, vol: 0.45 }, roll: { type: 'bandpass', f: 3600, q: 2, d: 0.03, vol: 0.42 }, ring: [{ f: 1900, d: 0.03, vol: 0.05 }] },\n dirt: { heel: { f: 75, d: 0.06, vol: 0.45 }, roll: { type: 'lowpass', f: 750, q: 0.7, d: 0.09, vol: 0.4 }, grains: { count: 3, f: 1800, q: 1.5, spread: 0.07, vol: 0.06 } },\n grass: { heel: { f: 70, d: 0.05, vol: 0.32 }, roll: { type: 'highpass', f: 2600, q: 0.7, d: 0.13, vol: 0.28 }, grains: { count: 4, f: 5200, q: 1.2, spread: 0.1, vol: 0.07 } },\n gravel: { heel: { f: 80, d: 0.05, vol: 0.4 }, roll: { type: 'lowpass', f: 950, q: 0.8, d: 0.1, vol: 0.3 }, grains: { count: 8, f: 2600, q: 3, spread: 0.13, vol: 0.2 } },\n sand: { heel: { f: 65, d: 0.06, vol: 0.3 }, roll: { type: 'bandpass', f: 1500, q: 0.6, d: 0.16, vol: 0.3 }, grains: { count: 5, f: 4800, q: 1.5, spread: 0.12, vol: 0.05 } },\n metal: { heel: { f: 120, d: 0.05, vol: 0.5 }, roll: { type: 'bandpass', f: 2800, q: 1.5, d: 0.03, vol: 0.25 }, ring: [{ f: 420, d: 0.25, vol: 0.16 }, { f: 1130, d: 0.18, vol: 0.09 }, { f: 2470, d: 0.1, vol: 0.04 }] },\n water: { heel: { f: 70, d: 0.04, vol: 0.25 }, roll: { type: 'bandpass', f: 3000, q: 1.2, d: 0.1, vol: 0.18 }, splash: { f: 1100, f2: 380, d: 0.22, vol: 0.55 }, grains: { count: 4, f: 2400, q: 6, spread: 0.18, vol: 0.12 } },\n glass: { heel: { f: 90, d: 0.04, vol: 0.4 }, roll: { type: 'highpass', f: 4500, q: 0.8, d: 0.06, vol: 0.2 }, grains: { count: 9, f: 6200, q: 5, spread: 0.12, vol: 0.22 }, ring: [{ f: 3900, d: 0.04, vol: 0.04 }, { f: 5300, d: 0.03, vol: 0.03 }] },\n carpet: { heel: { f: 70, d: 0.05, vol: 0.32 }, roll: { type: 'lowpass', f: 420, q: 0.7, d: 0.07, vol: 0.3 } },\n}\n\nconst GAITS: Readonly<Record<GaitId, { readonly vol: number; readonly bright: number; readonly toe: number; readonly short: number }>> = {\n walk: { vol: 1, bright: 1, toe: 0.075, short: 1 },\n run: { vol: 1.35, bright: 1.25, toe: 0.035, short: 0.75 },\n}\n\nconst grainLayers = (g: NonNullable<SurfaceVoice['grains']>, take: Take, start: number, scale: number): Layer[] =>\n Array.from({ length: g.count }, (_, i) =>\n sceneNoise({ type: 'bandpass', f: [g.f * take.f * 0.85, g.f * take.f * 1.15], q: g.q, d: [0.008, 0.02], vol: g.vol * scale * take.v, delay: start + ((i + 0.5) / g.count) * g.spread * take.t }),\n )\n\nconst ringLayers = (rings: NonNullable<SurfaceVoice['ring']>, take: Take, scale: number, at = 0): Layer[] =>\n rings.map((r) => sceneTone({ f: r.f * take.f, d: r.d * take.t, vol: r.vol * scale * take.v, delay: at }))\n\n/** The layers of one foot on a surface: heel, roll to the toe, then grains, ring or splash. `weight` scales the heel (a landing is the whole body). */\nfunction footLayers(surface: SurfaceId, take: Take, gait: (typeof GAITS)[GaitId], weight = 1): Layer[] {\n const s = SURFACES[surface]\n const toe = gait.toe * take.t\n return [\n sceneTone({ f: s.heel.f * take.f * weight ** -0.3, f2: s.heel.f * take.f * 0.6, d: s.heel.d * gait.short * take.t * weight ** 0.5, vol: s.heel.vol * gait.vol * take.v * weight ** 0.5 }),\n sceneNoise({ type: 'lowpass', f: 500 * gait.bright, d: 0.02 * take.t, vol: 0.18 * gait.vol * take.v * weight ** 0.5 }),\n sceneNoise({ type: s.roll.type, f: [s.roll.f * take.f * gait.bright * 0.92, s.roll.f * take.f * gait.bright * 1.08], q: s.roll.q, d: s.roll.d * gait.short * take.t * weight ** 0.3, vol: s.roll.vol * gait.vol * take.v, delay: toe }),\n ...(s.grains ? grainLayers(s.grains, take, toe * 0.5, gait.vol * weight ** 0.5) : []),\n ...(s.ring ? ringLayers(s.ring, take, gait.vol * weight ** 0.5) : []),\n ...(s.splash ? [sceneNoise({ type: 'bandpass', f: s.splash.f * take.f, f2: s.splash.f2 * take.f, q: 1.4, d: s.splash.d * take.t * weight ** 0.4, vol: s.splash.vol * gait.vol * take.v * weight ** 0.5 })] : []),\n ]\n}\n\n/** The layers at `level` of their gain (a scene layer's gain is a number or a range). */\nconst quieter = (level: number, layers: readonly Layer[]): Layer[] =>\n layers.map((layer) => {\n const gain = layer.gain ?? 1\n if (typeof gain === 'number') return { ...layer, gain: gain * level }\n if (Array.isArray(gain)) return { ...layer, gain: [gain[0] * level, gain[1] * level] as const }\n return layer\n })\n\nconst recipe = (id: string, layers: readonly Layer[], falloff: Falloff, bus: SoundRecipe['bus'] = 'world'): SoundRecipe => ({ id, bus, pan: true, layers, falloff, sources: ['sdk'] })\n\nconst takeId = (id: string, index: number): string => `${id}_${String(index + 1).padStart(2, '0')}`\n\n/** The four takes of an id and the set that names them. */\nfunction takes(id: string, layersOf: (take: Take, index: number) => Layer[], falloff: Falloff, rate: readonly [number, number] = [0.96, 1.04], bus?: SoundRecipe['bus']): { sounds: SoundRecipe[]; set: SoundSet } {\n const sounds = TAKES.map((take, index) => recipe(takeId(id, index), layersOf(take, index), falloff, bus))\n return { sounds, set: { id, variants: sounds.map((sound) => sound.id), rate } }\n}\n\nconst footstep = (surface: SurfaceId, gait: GaitId) => takes(footstepSoundId(surface, gait), (take) => footLayers(surface, take, GAITS[gait]), FOOTSTEP_FALLOFF)\n\nconst LANDINGS: Readonly<Record<LandingId, { readonly weight: number; readonly cloth: number }>> = { light: { weight: 1.4, cloth: 0.12 }, heavy: { weight: 2.4, cloth: 0.22 } }\n\n/** A landing's layers are the feet's at the body's weight; this brings the whole of it under a blow on a body (C6). */\nconst LANDING_LEVEL = 0.65\n\nconst landing = (surface: SurfaceId, landing: LandingId) =>\n takes(\n `land_${surface}_${landing}`,\n (take) => quieter(LANDING_LEVEL, [\n // both feet, a hair apart, then the knees taking the weight (a low body thump) and the clothes settling\n ...footLayers(surface, take, GAITS.run, LANDINGS[landing].weight),\n ...footLayers(surface, { ...take, v: take.v * 0.6 }, GAITS.run, LANDINGS[landing].weight * 0.6).map((layer) => ({ ...layer, at: (typeof layer.at === 'number' ? layer.at : 0) + 0.018 * take.t })),\n sceneTone({ f: 60 * take.f, f2: 38, d: 0.14 * LANDINGS[landing].weight * take.t, vol: 0.22 * LANDINGS[landing].weight ** 0.7 * take.v, delay: 0.02 }),\n sceneNoise({ type: 'bandpass', f: [1800, 2600], q: 0.8, d: 0.18, vol: LANDINGS[landing].cloth * take.v, delay: 0.04 }),\n ]),\n FOOTSTEP_FALLOFF,\n )\n\nconst whoosh = (blow: BlowId, from: number, to: number, d: number, vol: number, q = 1.6): ((take: Take) => Layer[]) => (take) => [\n // the air: a band sweeping up as the limb speeds up; it peaks `SWING_LEAD_SECONDS` in, the moment before the contact, then dies away\n sceneNoise({ type: 'bandpass', f: from * take.f, f2: to * take.f, q, a: SWING_LEAD_SECONDS[blow], d: d * take.t, vol: vol * take.v }),\n sceneNoise({ type: 'lowpass', f: 600 * take.f, a: SWING_LEAD_SECONDS[blow], d: d * take.t * 0.8, vol: vol * 0.35 * take.v }),\n]\n\n/** Skin, mass and (optionally) bone: what a blow on a body is made of. */\nconst fleshHit = (o: { slap: number; slapF: number; thud: number; thudF: number; thudD: number; crack?: number; wet?: number }): ((take: Take) => Layer[]) => (take) => [\n sceneNoise({ type: 'bandpass', f: o.slapF * take.f, q: 1.2, d: 0.03 * take.t, vol: o.slap * take.v }),\n sceneNoise({ type: 'highpass', f: 3500 * take.f, d: 0.012, vol: o.slap * 0.4 * take.v }),\n sceneTone({ f: o.thudF * take.f, f2: o.thudF * 0.5, d: o.thudD * take.t, vol: o.thud * take.v }),\n sceneNoise({ type: 'lowpass', f: 600 * take.f, d: o.thudD * 1.2 * take.t, vol: o.thud * 0.5 * take.v }),\n ...(o.crack ? [sceneNoise({ type: 'highpass', f: 2500, d: 0.015, vol: o.crack * take.v, delay: 0.006 }), sceneTone({ wave: 'square', f: 900 * take.f, f2: 300, d: 0.02, vol: o.crack * 0.15 * take.v, delay: 0.006 })] : []),\n ...(o.wet ? [sceneNoise({ type: 'bandpass', f: 1400 * take.f, f2: 500, q: 2.5, d: 0.12 * take.t, vol: o.wet * take.v, delay: 0.01 })] : []),\n]\n\n/** What only the striking part sounds like on a hard thing (the material's impact plays beside it). */\nconst knock = (o: { clickF: number; click: number; tones: readonly (readonly [number, number, number])[] }): ((take: Take) => Layer[]) => (take) => [\n sceneNoise({ type: 'bandpass', f: o.clickF * take.f, q: 1.5, d: 0.018, vol: o.click * take.v }),\n ...o.tones.map(([f, d, vol]) => sceneTone({ f: f * take.f, d: d * take.t, vol: vol * take.v })),\n]\n\nconst voice = (o: { f0: number; f1: number; d: number; fA: number; fB: number; noise: number; vol: number }): ((take: Take) => Layer[]) => (take) => [\n sceneVoice({ f0: o.f0 * take.f, f1: o.f1 * take.f, d: o.d * take.t, fA: o.fA * take.f, fB: o.fB * take.f, noise: o.noise, vol: o.vol * take.v }),\n]\n\nconst BODY: Readonly<Record<BodySoundId, (take: Take) => Layer[]>> = {\n jump: (take) => [\n sceneNoise({ type: 'bandpass', f: 900 * take.f, f2: 1700 * take.f, q: 1, a: 0.03, d: 0.12, vol: 0.18 * take.v }),\n sceneNoise({ type: 'bandpass', f: 2200 * take.f, q: 0.8, d: 0.04, vol: 0.12 * take.v }),\n sceneTone({ f: 85 * take.f, f2: 60, d: 0.04, vol: 0.2 * take.v }),\n ],\n cloth_rustle: (take) => [\n { ...sceneNoise({ type: 'bandpass', f: 2400 * take.f, q: 0.8, a: 0.06, d: 0.22 * take.t, vol: 0.12 * take.v }), modulators: [{ target: 'gain', wave: 'triangle', rate: [9, 14], depth: 0.5 }] },\n ],\n body_fall: (take) => [\n sceneTone({ f: 58 * take.f, f2: 35, d: 0.28 * take.t, vol: 0.9 * take.v }),\n sceneNoise({ type: 'lowpass', f: 480 * take.f, d: 0.3 * take.t, vol: 0.55 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1300 * take.f, q: 1, d: 0.05, vol: 0.3 * take.v }),\n // the limbs a moment later, and the clothes\n sceneTone({ f: 75 * take.f, f2: 45, d: 0.12, vol: 0.4 * take.v, delay: 0.13 * take.t }),\n sceneNoise({ type: 'bandpass', f: 2200, q: 0.8, d: 0.2, vol: 0.12 * take.v, delay: 0.05 }),\n ],\n fall_damage: (take) => [\n ...BODY.body_fall(take),\n sceneNoise({ type: 'highpass', f: 2800, d: 0.02, vol: 0.35 * take.v, delay: 0.01 }),\n ...voice({ f0: 170, f1: 110, d: 0.32, fA: 650, fB: 1150, noise: 0.25, vol: 0.32 })(take).map((layer) => ({ ...layer, at: 0.08 })),\n ],\n player_hurt: voice({ f0: 150, f1: 105, d: 0.26, fA: 620, fB: 1100, noise: 0.3, vol: 0.35 }),\n player_breath_run: (take) => [\n sceneNoise({ type: 'bandpass', f: 1200 * take.f, q: 1, a: 0.08, d: 0.22 * take.t, vol: 0.25 * take.v }),\n sceneNoise({ type: 'bandpass', f: 900 * take.f, q: 1, a: 0.06, d: 0.26 * take.t, vol: 0.3 * take.v, delay: 0.3 * take.t }),\n ],\n player_death: voice({ f0: 135, f1: 68, d: 1, fA: 560, fB: 980, noise: 0.35, vol: 0.4 }),\n bite: (take) => [\n sceneNoise({ type: 'highpass', f: 2600, d: 0.015, vol: 0.4 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1600 * take.f, f2: 450, q: 2.2, d: 0.16 * take.t, vol: 0.55 * take.v, delay: 0.01 }),\n sceneNoise({ type: 'bandpass', f: 3200 * take.f, f2: 1800, q: 1.2, d: 0.22 * take.t, vol: 0.25 * take.v, delay: 0.09 }),\n sceneTone({ f: 120 * take.f, f2: 70, d: 0.06, vol: 0.3 * take.v }),\n ],\n grab: (take) => [\n sceneNoise({ type: 'bandpass', f: 1900 * take.f, q: 0.9, a: 0.004, d: 0.13 * take.t, vol: 0.32 * take.v }),\n sceneTone({ f: 95 * take.f, f2: 60, d: 0.07, vol: 0.3 * take.v }),\n sceneNoise({ type: 'lowpass', f: 700, d: 0.08, vol: 0.2 * take.v }),\n ],\n punch_swing: whoosh('punch', 450, 1500, 0.16, 0.9),\n punch_hit_body: fleshHit({ slap: 0.55, slapF: 1500, thud: 0.6, thudF: 115, thudD: 0.09 }),\n punch_hit_face: fleshHit({ slap: 0.75, slapF: 2300, thud: 0.45, thudF: 150, thudD: 0.07, crack: 0.25 }),\n punch_hit_object: knock({ clickF: 1800, click: 0.3, tones: [[210, 0.04, 0.25]] }),\n kick_swing: whoosh('kick', 280, 950, 0.22, 1, 1.3),\n kick_hit: fleshHit({ slap: 0.45, slapF: 1100, thud: 0.85, thudF: 82, thudD: 0.14 }),\n kick_hit_object: knock({ clickF: 1000, click: 0.3, tones: [[92, 0.08, 0.5]] }),\n shove_two_hands: (take) => [\n sceneNoise({ type: 'bandpass', f: 950 * take.f, q: 0.9, a: 0.01, d: 0.13 * take.t, vol: 0.38 * take.v }),\n sceneTone({ f: 100 * take.f, f2: 60, d: 0.1 * take.t, vol: 0.45 * take.v }),\n sceneNoise({ type: 'bandpass', f: 2300, q: 0.8, d: 0.16, vol: 0.12 * take.v, delay: 0.03 }),\n ],\n knife_swing: whoosh('blade', 1900, 4600, 0.12, 1.1, 2.2),\n knife_stab: fleshHit({ slap: 0.2, slapF: 1200, thud: 0.4, thudF: 160, thudD: 0.06, wet: 0.5 }),\n knife_slash: (take) => [\n sceneNoise({ type: 'highpass', f: 3200 * take.f, f2: 1800, d: 0.13 * take.t, vol: 0.35 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1300 * take.f, f2: 600, q: 2.5, d: 0.12 * take.t, vol: 0.35 * take.v, delay: 0.02 }),\n ],\n knife_hit_object: knock({ clickF: 3200, click: 0.25, tones: [[2800, 0.08, 0.07], [4150, 0.06, 0.05]] }),\n blunt_swing: whoosh('blunt', 220, 760, 0.28, 1.1, 1.5),\n blunt_hit: fleshHit({ slap: 0.35, slapF: 900, thud: 1, thudF: 70, thudD: 0.18, crack: 0.3 }),\n blunt_hit_object: knock({ clickF: 1400, click: 0.35, tones: [[300, 0.12, 0.25], [760, 0.08, 0.12]] }),\n axe_swing: whoosh('chop', 190, 620, 0.3, 1.2, 1.4),\n axe_chop: fleshHit({ slap: 0.3, slapF: 1400, thud: 0.75, thudF: 140, thudD: 0.1, crack: 0.35, wet: 0.45 }),\n axe_hit_object: knock({ clickF: 2200, click: 0.4, tones: [[1500, 0.15, 0.1], [2300, 0.1, 0.06], [140, 0.1, 0.35]] }),\n}\n\nconst BODY_BUS: Partial<Record<BodySoundId, SoundRecipe['bus']>> = { player_hurt: 'voices', player_death: 'voices', player_breath_run: 'voices', fall_damage: 'voices' }\n\nconst built = [\n ...SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstep(surface, gait))),\n ...SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((l) => landing(surface, l))),\n ...BODY_SOUND_IDS.map((id) => takes(id, BODY[id], BODY_FALLOFF, id.endsWith('_swing') ? [0.94, 1.06] : [0.96, 1.04], BODY_BUS[id])),\n]\n\n/**\n * Every body sound of `game-contracts`' `BODY_FOLEY_IDS` as a set of four takes (`footstep_concrete_walk` plays `footstep_concrete_walk_01`..`_04`,\n * never the same twice in a row, at ±4% of rate). Register it in the engine the body plays on.\n */\nexport const BODY_FOLEY_BANK: SoundBank = {\n id: 'body_foley',\n sounds: built.flatMap((entry) => entry.sounds),\n sets: built.map((entry) => entry.set),\n}\n\n/** The ids the bank answers (the sets), in the contract's order. */\nexport const BODY_FOLEY_SET_IDS: readonly string[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n","import type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from '@adatechnology/game-contracts'\n\nimport type { SoundBank } from '../recipe'\nimport type { AudioEngine, VoiceHandle } from './engine'\n\n/** An `AudioSink` (what a host lends its modules) that carries the engine behind it, so a module that wants more than `play` can use the engine. */\nexport type EngineSink = AudioSink & { readonly engine: AudioEngine }\n\n/** Lends an engine as the host's `audio`: sounds by key, loops, the listener, and banks registered into the same engine. */\nexport function createAudioSink(engine: AudioEngine): EngineSink {\n const playing = new Map<number, VoiceHandle>()\n return {\n engine,\n play(request: SoundRequest): SoundHandle | null {\n const handle = engine.play(request.sound, {\n ...(request.position ? { position: request.position } : {}),\n ...(request.volume === undefined ? {} : { volume: request.volume }),\n ...(request.params ? { params: request.params } : {}),\n ...(request.seed === undefined ? {} : { seed: request.seed }),\n ...(request.delay === undefined ? {} : { delay: request.delay }),\n ...(request.urgent ? { urgent: true } : {}),\n })\n if (!handle) return null\n playing.set(handle.id, handle)\n return { id: handle.id }\n },\n stop(handle) {\n playing.get(handle.id)?.stop()\n playing.delete(handle.id)\n },\n loop(sound, options): LoopHandle {\n const loop = engine.loop(sound)\n // the loop's place comes with the first set; `params.cutoff` drives the first filter\n let position = options?.position\n return {\n set: (state) => {\n position = state.position ?? position\n const cutoff = state.params?.['cutoff']\n loop.set({\n ...(state.volume === undefined ? {} : { volume: state.volume }),\n ...(state.frequency === undefined ? {} : { frequency: state.frequency }),\n ...(position ? { position } : {}),\n ...(cutoff === undefined ? {} : { cutoff }),\n })\n },\n stop: () => loop.stop(),\n }\n },\n setListener(listener: AudioListener) {\n engine.setListener(listener)\n },\n register(bank: unknown) {\n engine.register(bank as SoundBank)\n },\n }\n}\n","export type AudioBenchText = {\n readonly group: string\n readonly name: string\n readonly probe: string\n readonly controls: Readonly<Record<'sound' | 'distance' | 'bearing' | 'volume' | 'mix' | 'seed' | 'play' | 'voice_storm' | 'loop' | 'loop_level' | 'loop_pitch' | 'source', string>>\n readonly hints: Readonly<Record<'distance' | 'bearing' | 'mix' | 'seed' | 'voice_storm' | 'loop_pitch' | 'source', string>>\n readonly options: Readonly<Record<'none' | 'bench' | 'probe', string>>\n readonly layers: Readonly<Record<'reverb' | 'compressor' | 'panning' | 'muffling', string>>\n readonly metrics: Readonly<Record<'voices' | 'peak' | 'dropped' | 'loops' | 'context' | 'plan_length' | 'plan_level' | 'plan_pan' | 'level_weapons' | 'level_voices' | 'level_world' | 'level_ambience' | 'level_weather' | 'level_ui', string>>\n readonly scenarios: Readonly<Record<'panning' | 'distance' | 'determinism' | 'limiter', string>>\n readonly mixes: Readonly<Record<string, string>>\n /** Text of a sound or loop id when the game has one; the bench falls back to the id. */\n readonly sheet: Readonly<Record<'title' | 'level' | 'distance' | 'pan' | 'length' | 'silent' | 'layer' | 'none', string>>\n}\n\nconst EN: AudioBenchText = {\n group: 'Sound',\n name: 'Sound area',\n probe: 'Sound probe',\n controls: {\n sound: 'Sound',\n distance: 'Distance',\n bearing: 'Bearing',\n volume: 'Volume',\n mix: 'Mixing chain',\n seed: 'Seed',\n play: 'Play',\n voice_storm: 'Voice storm',\n loop: 'Loop',\n loop_level: 'Loop level',\n loop_pitch: 'Loop pitch',\n source: 'Source',\n },\n hints: {\n distance: 'Metres from the listener: the level falls and the sound is muffled with it.',\n bearing: 'Degrees from straight ahead, positive to the right: shows the panning.',\n mix: 'The game chain (master only) or the art scene chain (compressor and reverb).',\n seed: 'The same seed gives the same sound.',\n voice_storm: 'Twenty of the chosen sound at once: the voice limiter drops what its group and the global cap refuse.',\n loop_pitch: 'Frequency of an oscillator loop, in hertz (0 leaves it where it is).',\n source: 'Where the sound comes from: the distance and bearing set here, or the probe standing in the area.',\n },\n options: { none: 'None', bench: 'Bench settings', probe: 'The probe' },\n layers: { reverb: 'Reverb', compressor: 'Compressor', panning: 'Panning', muffling: 'Muffling by distance' },\n metrics: {\n voices: 'Voices playing',\n peak: 'Most voices at once',\n dropped: 'Voices dropped',\n loops: 'Loops running',\n context: 'Audio context',\n plan_length: 'Chosen sound: length',\n plan_level: 'Chosen sound: level',\n plan_pan: 'Chosen sound: pan',\n level_weapons: 'Level: weapons',\n level_voices: 'Level: voices',\n level_world: 'Level: world',\n level_ambience: 'Level: ambience',\n level_weather: 'Level: weather',\n level_ui: 'Level: interface',\n },\n scenarios: {\n panning: 'A sound to the right is heard on the right, one to the left on the left, one ahead in the middle',\n distance: 'The farther a sound, the quieter, until it is not played',\n determinism: 'The same seed gives the same sound plan, another seed another one',\n limiter: 'The voice limiter holds a storm of voices to its group rule and its global cap',\n },\n mixes: { game: 'Game', art_scene: 'Art scene', kit: 'Kit (art scene + limiter)' },\n sheet: { title: 'Sound plan', level: 'level', distance: 'distance', pan: 'pan', length: 'seconds', silent: 'too far to be heard', layer: 'layer', none: 'no sound chosen' },\n}\n\nconst PT_BR: AudioBenchText = {\n group: 'Som',\n name: 'Área de som',\n probe: 'Sonda de som',\n controls: {\n sound: 'Som',\n distance: 'Distância',\n bearing: 'Direção',\n volume: 'Volume',\n mix: 'Cadeia de mixagem',\n seed: 'Semente',\n play: 'Tocar',\n voice_storm: 'Tempestade de vozes',\n loop: 'Laço',\n loop_level: 'Nível do laço',\n loop_pitch: 'Altura do laço',\n source: 'Origem',\n },\n hints: {\n distance: 'Metros até o ouvinte: o nível cai e o som abafa junto.',\n bearing: 'Graus a partir da frente, positivo para a direita: mostra o pan.',\n mix: 'A cadeia do jogo (só o master) ou a da Cena de Arte (compressor e reverb).',\n seed: 'A mesma semente dá o mesmo som.',\n voice_storm: 'Vinte do som escolhido de uma vez: o limite de vozes derruba o que a regra do grupo e o teto global recusam.',\n loop_pitch: 'Frequência de um laço de oscilador, em hertz (0 deixa onde está).',\n source: 'De onde vem o som: a distância e a direção daqui, ou a sonda que está na área.',\n },\n options: { none: 'Nenhum', bench: 'Ajustes da bancada', probe: 'A sonda' },\n layers: { reverb: 'Reverb', compressor: 'Compressor', panning: 'Pan', muffling: 'Abafamento pela distância' },\n metrics: {\n voices: 'Vozes tocando',\n peak: 'Mais vozes de uma vez',\n dropped: 'Vozes derrubadas',\n loops: 'Laços ligados',\n context: 'Contexto de áudio',\n plan_length: 'Som escolhido: duração',\n plan_level: 'Som escolhido: nível',\n plan_pan: 'Som escolhido: pan',\n level_weapons: 'Nível: armas',\n level_voices: 'Nível: vozes',\n level_world: 'Nível: mundo',\n level_ambience: 'Nível: ambiente',\n level_weather: 'Nível: clima',\n level_ui: 'Nível: interface',\n },\n scenarios: {\n panning: 'Um som à direita sai à direita, à esquerda sai à esquerda, à frente sai no meio',\n distance: 'Quanto mais longe, mais baixo, até não tocar',\n determinism: 'A mesma semente dá o mesmo plano de som, outra semente dá outro',\n limiter: 'O limite de vozes segura uma tempestade de vozes na regra do grupo e no teto global',\n },\n mixes: { game: 'Jogo', art_scene: 'Cena de Arte', kit: 'Kit (Cena de Arte + limitador)' },\n sheet: { title: 'Plano do som', level: 'nível', distance: 'distância', pan: 'pan', length: 'segundos', silent: 'longe demais para ouvir', layer: 'camada', none: 'nenhum som escolhido' },\n}\n\nexport const audioBenchTextOf = (locale: string): AudioBenchText => (locale === 'en' ? EN : PT_BR)\n","import type { AreaPlacement, BenchChange, ChoiceOption, ModuleControl, ModuleHost, ModuleLayer, ModuleMetric, ModuleScenario, TestableItem, TestableModule, Vec3 } from '@adatechnology/game-contracts'\n\nimport { GAME_SFX_BANK } from '../recipes/noise-class'\nimport { LIBRARY_BANK } from '../library'\nimport { DISTANCE_CURVES } from '../falloff'\nimport { DEFAULT_MIX, MIX_PROFILES } from '../mix'\nimport type { MixProfile } from '../mix'\nimport { BUS_IDS } from '../recipe'\nimport type { BusId, Layer, SoundBank } from '../recipe'\nimport type { SoundPlan } from '../plan'\nimport { createVoiceManager } from '../voices'\nimport { createAudioEngine } from '../webaudio/engine'\nimport type { AudioEngine, VoiceHandle } from '../webaudio/engine'\nimport type { EngineSink } from '../webaudio/sink'\nimport type { AudioLoopHandle } from '../webaudio/engine-loop'\nimport { audioBenchTextOf } from './locale'\nimport type { AudioBenchText } from './locale'\n\n/**\n * Two probe sounds of the bench itself (a ping and a hiss), so panning, distance and the seed can be heard on something that has no subject. They are\n * made by the kit, not delivered by any team (`sdk` in the sources).\n */\nexport const BENCH_BANK: SoundBank = {\n id: 'audio_bench',\n sounds: [\n {\n id: 'bench_ping',\n bus: 'ui',\n pan: true,\n duration: 0.25,\n layers: [\n {\n gain: 0.5,\n wet: 0.3,\n source: { kind: 'osc', wave: 'sine', frequency: { from: 880 } },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.002, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n } satisfies Layer,\n ],\n falloff: DISTANCE_CURVES.art_scene,\n sources: ['sdk: bench probe, a 880 Hz ping through the art scene output stage'],\n },\n {\n id: 'bench_hiss',\n bus: 'ui',\n pan: true,\n duration: [0.3, 0.9],\n layers: [\n {\n gain: 0.4,\n source: { kind: 'noise', offset: 'random', offsetScale: 1.5, loop: true },\n filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 3000 }, q: 0.7 }] },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.002, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n } satisfies Layer,\n ],\n falloff: DISTANCE_CURVES.art_scene,\n sources: ['sdk: bench probe, a highpass hiss of random length'],\n },\n ],\n}\n\nexport type AudioTestModuleOptions = {\n /** The engine to test (default: the one the host lends in `host.audio`, else a new one of the module's own). */\n engine?: AudioEngine\n /** Banks registered in the engine besides the bench's probes (default the game's noise classes and the library). */\n banks?: readonly SoundBank[]\n locale?: string\n /** Text of a sound or loop id (`sound.glass`) in the game's words; without it the bench shows the bank and the id. */\n translate?: (key: string, locale: string) => string | undefined\n seed?: number\n /** First sound chosen (default `bench_ping`). */\n sound?: string\n /**\n * Draws the thing the probe stands for, where the sound comes from with the `probe` source (for example a portable radio of `game-items-three`). The module\n * draws nothing of its own: without it the area has no probe and the sounds come from the bench settings.\n */\n probe?: (THREE: unknown) => unknown\n}\n\n/** What the scenarios use of the context the test room passes. */\nexport interface AudioScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type AudioTestModule = TestableModule<AudioScenarioLike> & {\n /** The engine in use: the host's when it lent one, the module's own otherwise. */\n readonly engine: AudioEngine\n /** The resolved plan of the chosen sound as text (the S3 view: every number decided). */\n sheet(): string\n /** Plays the chosen sound as the bench is set. */\n play(): VoiceHandle | null\n}\n\nconst DISTANCES = [0, 10, 40, 60, 120, 160] as const\nconst STORM = 20\nconst PROBE_ID = 'audio_probe'\nconst PROBE_AT: Vec3 = [0, 0, -10]\nconst NONE = 'none'\nconst DEFAULT_SOUND = 'bench_ping'\n\ntype Camera = { readonly position: { readonly x: number; readonly y: number; readonly z: number }; getWorldDirection(target: unknown): { readonly x: number; readonly z: number } }\ntype ThreeLike = { Vector3: new () => unknown }\ntype ProbeObject = { userData?: Record<string, unknown>; getWorldPosition(target: unknown): { readonly x: number; readonly y: number; readonly z: number }; traverse(visit: (object: ProbeObject) => void): void }\n\nconst variantOf = (profile: MixProfile, reverb: boolean, compressor: boolean): MixProfile => {\n const { reverb: wet, compressor: chain, ...rest } = profile\n return { ...rest, id: `${profile.id}${reverb ? '' : '+dry'}${compressor ? '' : '+open'}`, ...(wet && reverb ? { reverb: wet } : {}), ...(chain && compressor ? { compressor: chain } : {}) }\n}\n\n/**\n * The sound area of a test room, written against the generic contracts only: it plays any sound of an engine at a distance and bearing from the listener\n * (or from a probe standing in the area), runs loops, throws a storm of voices at the limiter, switches the mixing chain and its parts, reads the\n * level of each bus and prints the resolved plan. The engine is the host's (`host.audio`) when lent, else the module's own.\n */\nexport function createAudioTestModule(options: AudioTestModuleOptions = {}): AudioTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text: AudioBenchText = audioBenchTextOf(locale)\n const banks = [BENCH_BANK, ...(options.banks ?? [GAME_SFX_BANK, LIBRARY_BANK])]\n let engine: AudioEngine = options.engine ?? createAudioEngine({ seed: options.seed ?? 1, banks })\n for (const bank of banks) engine.register(bank)\n let host: ModuleHost | null = null\n let loop: AudioLoopHandle | undefined\n const state = {\n sound: options.sound ?? DEFAULT_SOUND,\n distance: 10,\n bearing: 0,\n volume: 1,\n mix: DEFAULT_MIX,\n seed: options.seed ?? 1,\n source: 'bench',\n loop: NONE,\n loopLevel: 0.1,\n loopPitch: 0,\n reverb: true,\n compressor: true,\n panning: true,\n muffling: true,\n }\n\n const nameOf = (id: string): string => {\n const translated = options.translate?.(`sound.${id}`, locale)\n if (translated) return translated\n const bank = engine.registry.bankOf(id)\n return bank ? `${bank} / ${id}` : id\n }\n const soundOptions = (): ChoiceOption[] => engine.registry.soundIds().map((id) => ({ id, name: nameOf(id) }))\n const loopOptions = (): ChoiceOption[] => [{ id: NONE, name: text.options.none }, ...engine.registry.loopIds().map((id) => ({ id, name: nameOf(id) }))]\n\n // the listener is the host camera; without a host (a test) it stands at the origin looking along -z\n const listener = (): { position: Vec3; yaw: number } => {\n const camera = host?.camera as Camera | undefined\n const three = host?.THREE as ThreeLike | undefined\n if (typeof camera?.getWorldDirection !== 'function' || typeof three?.Vector3 !== 'function' || !camera.position) return { position: [0, 0, 0], yaw: 0 }\n const direction = camera.getWorldDirection(new three.Vector3())\n return { position: [camera.position.x, camera.position.y, camera.position.z], yaw: Math.atan2(-direction.x, -direction.z) }\n }\n\n const probePosition = (): Vec3 | undefined => {\n const scene = host?.scene as ProbeObject | undefined\n const three = host?.THREE as ThreeLike | undefined\n if (typeof scene?.traverse !== 'function' || typeof three?.Vector3 !== 'function') return undefined\n let found: Vec3 | undefined\n scene.traverse((object) => {\n if (found || object.userData?.[PROBE_ID] !== true) return\n const at = object.getWorldPosition(new three.Vector3())\n found = [at.x, at.y, at.z]\n })\n return found\n }\n\n // `bearing` is degrees to the right of straight ahead\n const sourceAt = (ears: { position: Vec3; yaw: number }): Vec3 => {\n const probe = state.source === 'probe' ? probePosition() : undefined\n if (probe) return probe\n const bearing = (state.bearing * Math.PI) / 180\n const forward = [-Math.sin(ears.yaw), -Math.cos(ears.yaw)] as const\n const right = [Math.cos(ears.yaw), -Math.sin(ears.yaw)] as const\n return [ears.position[0] + state.distance * (forward[0] * Math.cos(bearing) + right[0] * Math.sin(bearing)), ears.position[1], ears.position[2] + state.distance * (forward[1] * Math.cos(bearing) + right[1] * Math.sin(bearing))]\n }\n\n const playOptions = (): { position?: Vec3; distance?: number; volume: number; seed: number } => {\n const ears = listener()\n engine.setListener(ears)\n const at = sourceAt(ears)\n const distance = Math.hypot(at[0] - ears.position[0], at[2] - ears.position[2])\n return { ...(state.panning ? { position: at } : { distance }), volume: state.volume, seed: state.seed }\n }\n\n // no muffling: the recipe's cutoff divisor is switched off for the one call\n const withMuffling = <T>(id: string, run: () => T): T => {\n const falloff = engine.registry.sound(id)?.falloff\n if (state.muffling || !falloff || falloff.model !== 'inverse_square' || falloff.cutoffK === undefined) return run()\n engine.registry.patch(id, { falloff: { cutoffK: 0 } })\n try {\n return run()\n } finally {\n engine.registry.patch(id, { falloff: { cutoffK: falloff.cutoffK } })\n }\n }\n\n const play = (): VoiceHandle | null => {\n engine.unlock()\n const chosen = state.sound\n return withMuffling(chosen, () => engine.play(chosen, playOptions()))\n }\n\n const plan = (): SoundPlan | null => {\n const chosen = state.sound\n return withMuffling(chosen, () => engine.plan(chosen, playOptions()))\n }\n\n const sheet = (): string => {\n const planned = plan()\n if (!planned) return `${text.sheet.title}: ${engine.registry.sound(state.sound) ? text.sheet.silent : text.sheet.none}`\n const head = `${text.sheet.title}: ${planned.id} (${planned.bus}) ${text.sheet.level} ${planned.level.toFixed(4)} ${text.sheet.distance} ${planned.distance.toFixed(1)} m` + `${planned.pan === undefined ? '' : ` ${text.sheet.pan} ${planned.pan.toFixed(3)}`} ${planned.length.toFixed(3)} ${text.sheet.length}`\n const layers = planned.layers.map((layer, index) => {\n const source = layer.source.kind === 'noise' ? `noise@${layer.source.offset.toFixed(4)}` : layer.source.kind === 'osc' ? `${layer.source.wave}@${layer.source.frequency.value ?? layer.source.frequency.from}` : layer.source.kind\n const filters = (layer.filters?.bank ?? []).map((filter) => `${filter.type}@${(filter.frequency.value ?? filter.frequency.from ?? 0).toFixed(1)}`).join(' ')\n const envelope = layer.envelope.map((point) => `${point.time.toFixed(3)}:${point.value.toPrecision(3)}`).join(' ')\n return ` ${text.sheet.layer} ${index + 1}: ${source} at ${layer.at.toFixed(3)} for ${layer.duration.toFixed(3)} ${filters} [${envelope}]`\n })\n return [head, ...layers].join('\\n')\n }\n\n const applyMix = (): void => {\n const profile = engine && MIX_PROFILES[state.mix]\n if (profile) engine.setMix(variantOf(profile, state.reverb, state.compressor))\n }\n\n const setLoop = (): void => {\n loop?.stop()\n loop = undefined\n if (state.loop === NONE) return\n engine.unlock()\n loop = engine.loop(state.loop)\n loop.set({ volume: state.loopLevel, ...(state.loopPitch > 0 ? { frequency: state.loopPitch } : {}) })\n }\n\n const storm = (): void => {\n engine.unlock()\n const base = playOptions()\n const chosen = state.sound\n for (let index = 0; index < STORM; index++) {\n const spread = base.position ? { position: [base.position[0] + (index - STORM / 2), base.position[1], base.position[2]] as Vec3 } : {}\n withMuffling(chosen, () => engine.play(chosen, { ...base, ...spread, seed: state.seed + index }))\n }\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'layer') {\n if (change.id === 'reverb' || change.id === 'compressor') {\n state[change.id] = change.on\n applyMix()\n } else if (change.id === 'panning' || change.id === 'muffling') state[change.id] = change.on\n return\n }\n if (change.kind === 'action') {\n if (change.id === 'play') play()\n else if (change.id === 'voice_storm') storm()\n return\n }\n const { id, value } = change\n if (id === 'sound' && typeof value === 'string') state.sound = value\n else if (id === 'distance' && typeof value === 'string') state.distance = Number(value)\n else if (id === 'bearing' && typeof value === 'number') state.bearing = value\n else if (id === 'volume' && typeof value === 'number') state.volume = value\n else if (id === 'seed' && typeof value === 'number') state.seed = value\n else if (id === 'source' && typeof value === 'string') state.source = value\n else if (id === 'mix' && typeof value === 'string') {\n state.mix = value\n applyMix()\n } else if (id === 'loop' && typeof value === 'string') {\n state.loop = value\n setLoop()\n } else if (id === 'loop_level' && typeof value === 'number') {\n state.loopLevel = value\n loop?.set({ volume: value })\n } else if (id === 'loop_pitch' && typeof value === 'number') {\n state.loopPitch = value\n if (value > 0) loop?.set({ frequency: value })\n }\n }\n\n const items = (): TestableItem[] => {\n const probe = options.probe\n if (!probe) return []\n return [\n {\n id: PROBE_ID,\n name: text.probe,\n movable: false,\n build: (THREE) => {\n const root = probe(THREE) as { userData?: Record<string, unknown> }\n root.userData = root.userData ?? {}\n root.userData[PROBE_ID] = true\n return root\n },\n },\n ]\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'choice', id: 'sound', name: text.controls.sound, options: soundOptions(), default: state.sound },\n { kind: 'choice', id: 'source', name: text.controls.source, hint: text.hints.source, options: [{ id: 'bench', name: text.options.bench }, { id: 'probe', name: text.options.probe }], default: state.source },\n { kind: 'choice', id: 'distance', name: text.controls.distance, hint: text.hints.distance, options: DISTANCES.map((meters) => ({ id: String(meters), name: `${meters} m` })), default: String(state.distance) },\n { kind: 'number', id: 'bearing', name: text.controls.bearing, hint: text.hints.bearing, unit: '°', min: -180, max: 180, step: 15, default: state.bearing },\n { kind: 'number', id: 'volume', name: text.controls.volume, min: 0, max: 1, step: 0.05, default: state.volume },\n { kind: 'choice', id: 'mix', name: text.controls.mix, hint: text.hints.mix, options: Object.keys(MIX_PROFILES).map((id) => ({ id, name: text.mixes[id] ?? id })), default: state.mix },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: state.seed },\n { kind: 'action', id: 'play', name: text.controls.play },\n { kind: 'action', id: 'voice_storm', name: text.controls.voice_storm, hint: text.hints.voice_storm },\n { kind: 'choice', id: 'loop', name: text.controls.loop, options: loopOptions(), default: state.loop },\n { kind: 'number', id: 'loop_level', name: text.controls.loop_level, min: 0, max: 0.6, step: 0.01, default: state.loopLevel },\n { kind: 'number', id: 'loop_pitch', name: text.controls.loop_pitch, hint: text.hints.loop_pitch, unit: 'Hz', min: 0, max: 400, step: 5, default: state.loopPitch },\n ]\n\n const layers = (): ModuleLayer[] => (['reverb', 'compressor', 'panning', 'muffling'] as const).map((id) => ({ id, name: text.layers[id] }))\n\n const metrics = (): ModuleMetric[] => [\n { id: 'voices', name: text.metrics.voices, digits: 0, read: () => engine.stats().voices },\n { id: 'peak', name: text.metrics.peak, digits: 0, max: engine.stats().maxVoices > 0 && Number.isFinite(engine.stats().maxVoices) ? engine.stats().maxVoices : undefined, read: () => engine.stats().peak },\n { id: 'dropped', name: text.metrics.dropped, digits: 0, read: () => engine.stats().dropped },\n { id: 'loops', name: text.metrics.loops, digits: 0, read: () => engine.stats().loops },\n { id: 'context', name: text.metrics.context, read: () => engine.stats().context },\n { id: 'plan_length', name: text.metrics.plan_length, unit: 's', digits: 2, read: () => plan()?.length ?? 0 },\n { id: 'plan_level', name: text.metrics.plan_level, digits: 3, read: () => plan()?.level ?? 0 },\n { id: 'plan_pan', name: text.metrics.plan_pan, digits: 2, read: () => plan()?.pan ?? 0 },\n ...BUS_IDS.map((bus) => ({ id: `level_${bus}`, name: text.metrics[`level_${bus}` as keyof AudioBenchText['metrics']], digits: 3, read: () => engine.level(bus as BusId) })),\n ]\n\n const scenarios = (): Array<ModuleScenario<AudioScenarioLike>> => [\n {\n id: 'panning',\n name: text.scenarios.panning,\n run: ({ expect }) => {\n engine.setListener({ position: [0, 0, 0], yaw: 0 })\n const pan = (at: Vec3): number => engine.plan('bench_ping', { position: at })?.pan ?? Number.NaN\n expect(pan([10, 0, 0]) > 0.3, 'a sound to the right pans right', { pan: pan([10, 0, 0]) })\n expect(pan([-10, 0, 0]) < -0.3, 'a sound to the left pans left', { pan: pan([-10, 0, 0]) })\n expect(Math.abs(pan([0, 0, -10])) < 0.05, 'a sound ahead stays in the middle', { pan: pan([0, 0, -10]) })\n engine.setListener({ position: [0, 0, 0], yaw: Math.PI / 2 })\n expect(pan([0, 0, -10]) > 0.3, 'turning the listener left puts what was ahead on the right', { pan: pan([0, 0, -10]) })\n engine.setListener(listener())\n },\n },\n {\n id: 'distance',\n name: text.scenarios.distance,\n run: ({ expect }) => {\n const levels = [0, 10, 40, 100].map((meters) => engine.plan('bench_ping', { distance: meters })?.level ?? Number.NaN)\n expect(levels.every((level, index) => index === 0 || level < (levels[index - 1] as number)), 'the level falls with the distance', { levels })\n const far = engine.registry.sound('sfx_pistol') ? engine.plan('sfx_pistol', { distance: 400 }) : null\n expect(far === null, 'a game noise class is not played too far to be heard')\n },\n },\n {\n id: 'determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const a = engine.plan('bench_hiss', { seed: 5 })\n const b = engine.plan('bench_hiss', { seed: 5 })\n const c = engine.plan('bench_hiss', { seed: 6 })\n expect(JSON.stringify(a) === JSON.stringify(b), 'the same seed gives the same plan')\n expect(JSON.stringify(a) !== JSON.stringify(c), 'another seed gives another plan')\n },\n },\n {\n id: 'limiter',\n name: text.scenarios.limiter,\n run: ({ expect }) => {\n const voices = createVoiceManager({ maxVoices: 8 })\n const request = (group?: string) => voices.request({ ...(group ? { group } : {}), priority: 3, gain: 0.5, distance: 5, length: 1 })\n const grouped = Array.from({ length: STORM }, () => request('undead_voice')).filter((decision) => decision.accepted).length\n expect(grouped === 1, 'the group cooldown lets one voice of a storm through', { accepted: grouped })\n const plain = Array.from({ length: STORM }, () => request()).filter((decision) => decision.accepted).length\n expect(plain <= 8, 'the global cap holds the rest', { accepted: plain })\n },\n },\n ]\n\n const area = (): { placements: AreaPlacement[]; view: { eye: Vec3; target: Vec3 } } => ({\n placements: options.probe ? [{ item: PROBE_ID, position: PROBE_AT, asleep: true }] : [],\n view: { eye: [0, 1.7, 3], target: [0, 1.4, -10] },\n })\n\n const module: AudioTestModule = {\n id: 'audio_area',\n name: text.name,\n ground: { surface: 'concrete_slab' },\n group: text.group,\n get engine() {\n return engine\n },\n items: () => items(),\n area: () => area(),\n controls: () => controls(),\n layers: () => layers(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n sheet,\n play,\n attach(lent) {\n host = lent\n const shared = (lent.audio as EngineSink | undefined)?.engine\n if (shared && shared !== engine) {\n for (const bank of banks) shared.register(bank)\n engine = shared\n }\n // buses get their nodes now, so the level meters see every sound\n for (const bus of BUS_IDS) {\n engine.setBus(bus, {})\n engine.level(bus)\n }\n lent.bench?.patch('sound', { options: soundOptions() })\n lent.bench?.patch('loop', { options: loopOptions() })\n const off = lent.bench?.onChange(onChange)\n const offFrame = lent.onFrame(() => {\n if (!shared) engine.setListener(listener())\n })\n return () => {\n off?.()\n offFrame()\n loop?.stop()\n loop = undefined\n host = null\n }\n },\n }\n return module\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAS;AACX,eAAO;AAAA,MACT;AAAA,MACA,OAAO,MAAM,MAAM;AAAA,MACnB,MAAM,MAAM,KAAK;AAAA,MACjB,UAAU,MAAM,SAAS;AAAA,MACzB,QAAQ,MAAM,OAAO;AAAA,MACrB,SAAS,MAAM,QAAQ;AAAA,MACvB,WAAW,MAAM,UAAU;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,OAAO,MAAM;AACX,eAAO;AACP,cAAM,SAAU,KAAK,OAAkC;AACvD,YAAI,UAAU,WAAW,QAAQ;AAC/B,qBAAW,QAAQ,MAAO,QAAO,SAAS,IAAI;AAC9C,mBAAS;AAAA,QACX;AAEA,mBAAW,OAAO,SAAS;AACzB,iBAAO,OAAO,KAAK,CAAC,CAAC;AACrB,iBAAO,MAAM,GAAG;AAAA,QAClB;AACA,aAAK,OAAO,MAAM,SAAS,EAAE,SAAS,aAAa,EAAE,CAAC;AACtD,aAAK,OAAO,MAAM,QAAQ,EAAE,SAAS,YAAY,EAAE,CAAC;AACpD,cAAM,MAAM,KAAK,OAAO,SAAS,QAAQ;AACzC,cAAM,WAAW,KAAK,QAAQ,MAAM;AAClC,cAAI,CAAC,OAAQ,QAAO,YAAY,SAAS,CAAC;AAAA,QAC5C,CAAC;AACD,eAAO,MAAM;AACX,gBAAM;AACN,mBAAS;AACT,gBAAM,KAAK;AACX,iBAAO;AACP,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;","names":["limiterCurve","level","voice","voice","envelope","fixed","recipe","envelope","url","recipe","recipe","recipe","ramp","takes","end","landing","envelope","end","outputStage","envelope","envelope","url","voice","limiterCurve","recipe","url","built","listener","end","envelope","left","right","takes","url","entries","url","url","TAKES","landing","layers","envelope"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/rng.ts","../src/recipe.ts","../src/falloff.ts","../src/listener.ts","../src/data/voice-groups.json","../src/voices.ts","../src/plan.ts","../src/sample.ts","../src/measure/calibration.ts","../src/bank.ts","../src/data/mix-profiles.json","../src/mix.ts","../src/webaudio/noise.ts","../src/webaudio/chain.ts","../src/webaudio/context.ts","../src/loops.ts","../src/webaudio/nodes.ts","../src/webaudio/realize-loop.ts","../src/webaudio/engine-loop.ts","../src/webaudio/sample-loop.ts","../src/webaudio/engine-noise.ts","../../game-contracts/src/blast-shove.ts","../../game-contracts/src/blast-impulse.ts","../../game-contracts/src/blast-knock.ts","../../game-contracts/src/impact-cost.ts","../../game-contracts/src/impact.ts","../../game-contracts/src/body.ts","../../game-contracts/src/spec.ts","../../game-contracts/src/weapons.ts","../../game-contracts/src/ignition.ts","../../game-contracts/src/seal.ts","../../game-contracts/src/twist.ts","../../game-contracts/src/animation.ts","../../game-contracts/src/tool-animation.ts","../../game-contracts/src/frame.ts","../../game-contracts/src/warn.ts","../../game-contracts/src/registry.ts","../../game-contracts/src/bench.ts","../../game-contracts/src/environment.ts","../../game-contracts/src/categories.ts","../../game-contracts/src/origin.ts","../../game-contracts/src/footprint.ts","../../game-contracts/src/foley.ts","../../game-contracts/src/index.ts","../src/webaudio/engine-queue.ts","../src/webaudio/realize-game.ts","../src/webaudio/realize-layered.ts","../src/webaudio/realize-weapon.ts","../src/webaudio/realize.ts","../src/variation.ts","../src/webaudio/sample-store.ts","../src/webaudio/realize-sample.ts","../src/webaudio/engine.ts","../src/measure/analyze.ts","../src/measure/criteria.ts","../src/catalog.ts","../src/manifest.ts","../src/kit-samples.ts","../src/user-samples.ts","../src/data/game-sfx.json","../src/recipes/noise-class.ts","../src/recipes/scene.ts","../src/library/crowd_rumble.json","../src/library/engine_saw.json","../src/library/horn.json","../src/library/radio_static.json","../src/library/rotor_blades.json","../src/library/siren.json","../src/library/index.ts","../src/library/cabin.ts","../src/recipes/foley.ts","../src/recipes/body-foley.ts","../src/webaudio/sink.ts","../src/bench/locale.ts","../src/bench/module.ts"],"sourcesContent":["/**\n * @adatechnology/game-audio: sound as data. A recipe (layers of noise, oscillators, filters, LFOs and an envelope) is planned into a `SoundPlan`\n * with every number decided by a seeded stream, and the plan is what the WebAudio layer builds. Distance curves, pan, a voice limiter, loops and\n * the two team mixing chains (the game and the art scene) are here; the sounds themselves live in each subject's bank.\n */\nexport { createRng, drawBetween, streamFor, streamSeed } from './rng'\nexport { BUILD_ORDERS, BUS_IDS } from './recipe'\nexport type {\n Automation,\n BuildOrder,\n BusId,\n Curve,\n Envelope,\n EnvelopePoint,\n Falloff,\n FilterBank,\n FilterSpec,\n FormantVoiceSource,\n Layer,\n LayerSource,\n LoopOrder,\n LoopRecipe,\n Modulator,\n NoiseSource,\n OscSource,\n ParamRef,\n Range,\n SoundBank,\n SoundRecipe,\n SoundSet,\n Time,\n} from './recipe'\nexport { planSound } from './plan'\nexport {\n DEFAULT_CROSSOVER,\n DEFAULT_SAMPLE_CUTOFF_K,\n DEFAULT_SAMPLE_FALLOFF,\n DEFAULT_SAMPLE_PITCH,\n DEFAULT_TAIL_GAIN,\n LAYER_FLOOR,\n OPEN_CUTOFF,\n SAMPLE_ENVIRONMENTS,\n crossGains,\n farMixAt,\n pickTake,\n planSample,\n sampleCutoff,\n sampleUrls,\n tierFor,\n} from './sample'\nexport type { PlannedSampleLayer, SampleCrossover, SampleEnvironment, SampleLayerRole, SampleMemory, SamplePlan, SamplePlanInput, SampleRef, SampleSound, SampleTail, SampleTier } from './sample'\nexport { CALIBRATION_ID, CALIBRATION_LOOP_ID, CALIBRATION_LOOP_SOUND, CALIBRATION_SOUND, calibrationLoader, encodeWav, isCalibrationUrl } from './measure/calibration'\nexport { CRITERIA, CRITERIA_TARGETS, measureCriteria, recordOutput } from './measure/criteria'\nexport type { ActionCheck, CriterionId, CriterionResult, MeasureOptions } from './measure/criteria'\nexport { balanceOf, centroidHz, countHits, dbOf, endDropDb, onsetIndex, peakIndex, peakOf, ringSeconds, rmsDb } from './measure/analyze'\nexport { SFX_BLOWS, SFX_CATALOG, SFX_CATEGORIES, SFX_IMPACTS, SFX_MATERIALS, impactSoundId, sfxState } from './catalog'\nexport type { SfxBlow, SfxCategory, SfxEntry, SfxMaterial, SfxPriority, SfxState } from './catalog'\nexport { SDK_LICENSES, SFX_LAYERS, SFX_TIERS, parseSfxName, sampleBankFromManifest, splitTier } from './manifest'\nexport type { SampleBankOptions, SampleDefaults, SdkLicense, SfxFileEntry, SfxLayer, SfxManifest, SfxManifestLike, SfxManifestSound } from './manifest'\nexport { KIT_SAMPLES_BANK, USER_SAMPLES_BANK, USER_SOUND_PREFIX, loadUserSamples, soundSourceOf, userSampleBank } from './user-samples'\nexport type {\n LoadUserSamplesOptions,\n SoundSource,\n UserSampleBankOptions,\n UserSampleBankResult,\n UserSfxFile,\n UserSfxManifest,\n UserSfxSound,\n UserSoundPick,\n UserSoundPicks,\n UserSoundRole,\n} from './user-samples'\nexport { KIT_CATEGORY_BUS, KIT_SAMPLE_ALIASES, kitSampleBank, kitSampleDefaults, loadKitSamples, withAliases } from './kit-samples'\nexport type { KitSampleBankOptions, LoadKitSamplesOptions } from './kit-samples'\nexport type { PlanInput, PlannedAutomation, PlannedEnvelopePoint, PlannedFilter, PlannedLayer, PlannedModulator, PlannedSource, SoundPlan } from './plan'\nexport { DISTANCE_CURVES, cutoffDivisor, falloffGain, isSilent } from './falloff'\nexport type { DistanceCurveName } from './falloff'\nexport { DEFAULT_LISTENER, PAN_LIMIT, PAN_MIN_DISTANCE, listenerDistance, panFor } from './listener'\nexport type { DistanceMode, Listener } from './listener'\nexport { BUS_PRIORITY, DEFAULT_MAX_VOICES, VOICE_GROUPS, busPriority, createVoiceManager } from './voices'\nexport type { VoiceDecision, VoiceGroup, VoiceManager, VoiceManagerOptions, VoiceRefusal, VoiceRequest, VoiceStats } from './voices'\nexport { LOOP_SMOOTHING, LOOP_START_ABOVE, createLoopState } from './loops'\nexport type { LoopAction, LoopState } from './loops'\nexport { DEFAULT_MIX, MIX_PROFILES, busGain, resolveMix } from './mix'\nexport type { BusSetting, MixProfile } from './mix'\nexport { createSoundRegistry } from './bank'\nexport type { DeepPartial, SoundRegistry } from './bank'\nexport { GAME_SFX_BANK, GAME_SFX_CLASSES, GAME_SFX_FALLBACK, noiseClassRecipe } from './recipes/noise-class'\nexport type { NoiseClass } from './recipes/noise-class'\nexport { sceneMany, sceneNoise, sceneRecipe, sceneTone, sceneVoice } from './recipes/scene'\nexport type { SceneLength, SceneNoise, SceneRecipeOptions, SceneTone, SceneVoice } from './recipes/scene'\nexport { LIBRARY_BANK, LIBRARY_LOOPS, LIBRARY_SOUNDS } from './library'\nexport { CABIN_BANK, CABIN_SOUNDS } from './library/cabin'\nexport { FOLEY_BANK, FOLEY_FALLOFF, ITEM_FOLEY, LEAF_FOLEY, LEAF_FOLEY_SETS, PICKUP_CLASSES } from './recipes/foley'\nexport type { LeafFoley, PickupClass } from './recipes/foley'\nexport { BODY_FALLOFF, BODY_FOLEY_BANK, BODY_FOLEY_SET_IDS, BODY_FOLEY_TAKES, FOOTSTEP_FALLOFF } from './recipes/body-foley'\nexport { createSetPicker, retunePlan } from './variation'\nexport type { SetPicker } from './variation'\nexport { createAudioEngine, limiterCurve } from './webaudio/engine'\nexport type { AudioChannel, AudioEngine, AudioEngineOptions, AudioStats, PlayOptions, SampleOptions, VoiceHandle, VoiceStartEvent } from './webaudio/engine'\nexport { createSampleStore, fetchLoader, inlineLoader } from './webaudio/sample-store'\nexport type { SampleLoadReport, SampleLoader, SampleStatus, SampleStore } from './webaudio/sample-store'\nexport { realizeSample, sampleLength } from './webaudio/realize-sample'\nexport type { RealizedSampleVoice, SampleTarget } from './webaudio/realize-sample'\nexport type { AudioLoopHandle, LoopSet } from './webaudio/engine-loop'\nexport { CROSSFADE_STEPS, DEFAULT_LOOP_CROSSFADE, equalPowerIn, loopCrossfade } from './webaudio/sample-loop'\nexport type { SampleLoopHost } from './webaudio/sample-loop'\nexport type { StartQueueOptions } from './webaudio/engine-queue'\nexport { realize } from './webaudio/realize'\nexport type { RealizedVoice, RealizeTarget } from './webaudio/nodes'\nexport { buildChain } from './webaudio/chain'\nexport type { MixChain } from './webaudio/chain'\nexport { bufferOf, fillImpulse, fillNoise } from './webaudio/noise'\nexport { globalContext, unlockContext } from './webaudio/context'\nexport { createAudioSink } from './webaudio/sink'\nexport type { EngineSink } from './webaudio/sink'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport { BENCH_BANK, createAudioTestModule } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport type { AudioScenarioLike, AudioTestModule, AudioTestModuleOptions } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport { audioBenchTextOf } from './testing'\n/** @deprecated import from '@adatechnology/game-audio/testing' */\nexport type { AudioBenchText } from './testing'\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; floats in [0, 1). The same generator the golden tool seeds `Math.random` with, so a team routine and its recipe draw the same numbers. */\nexport function createRng(seed: number): () => number {\n let state = seed >>> 0\n return () => {\n state = (state + 0x6d2b79f5) >>> 0\n let mixed = Math.imul(state ^ (state >>> 15), state | 1)\n mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61)\n return ((mixed ^ (mixed >>> 14)) >>> 0) / 4294967296\n }\n}\n\n/** The seed of the stream called `name` (or numbered `name`): one seed gives each channel its own sequence, so one subject's sounds never shift another's. */\nexport function streamSeed(seed: number, name: string | number): number {\n const label = String(name)\n let hash = FNV_OFFSET\n for (let index = 0; index < label.length; index++) hash = Math.imul(hash ^ label.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function streamFor(seed: number, name: string | number): () => number {\n return createRng(streamSeed(seed, name))\n}\n\n/** `min + random × (max − min)`: the form every team routine uses (`95 + Math.random() * 40`). */\nexport function drawBetween(random: () => number, min: number, max: number): number {\n return min + random() * (max - min)\n}\n","/**\n * Sound recipes are data. A recipe says which nodes a sound has and which numbers drive them; ranges are drawn when the sound is planned, in\n * the order the fields are written (see `planSound`), so a recipe ported from a team routine draws its random numbers in the routine's order.\n */\n\nexport const BUS_IDS = ['weapons', 'voices', 'world', 'ambience', 'weather', 'ui'] as const\nexport type BusId = (typeof BUS_IDS)[number]\n\n/** A named number: from `PlayOptions.params` or the recipe's `vars`, times `scale`, plus `add`. */\nexport type ParamRef = { readonly param: string; readonly scale?: number; readonly add?: number }\n\n/** A number, a `[min, max]` drawn uniformly (`min + random × (max − min)`), or a named number. */\nexport type Range = number | readonly [min: number, max: number] | ParamRef\n\n/** Seconds from the layer start: a range, the layer `'duration'`, or `'0.6d'` (0.6 × the layer duration). */\nexport type Time = Range | 'duration' | `${number}d`\n\nexport type Curve = 'linear' | 'exp'\n\n/**\n * How an AudioParam moves:\n * - `{ set }` assigns `.value`;\n * - `{ set, to, curve, over }` assigns `.value`, then ramps to `to` at `over`;\n * - `{ from }` calls `setValueAtTime(from)` at the start; with `to`, `curve` and `over` it then ramps to `to` (`'from'` is the value drawn for `from`: the art scene ramps a tone back to its own start when it gives no end).\n */\nexport type Automation =\n | { readonly set: Range; readonly to?: Range | 'from'; readonly curve?: Curve; readonly over?: Time }\n | { readonly from: Range; readonly to?: Range | 'from'; readonly curve?: Curve; readonly over?: Time }\n\n/**\n * One gain point: time (seconds, or `'0.6d'`), value and how it is reached (`set` = `setValueAtTime`, or a ramp). The value is multiplied by the\n * layer level (volume, distance and layer gain) except when the fourth item is `'fixed'` (the floor a ramp falls to, such as 0.001).\n */\nexport type EnvelopePoint =\n | readonly [time: number | `${number}d`, value: number, curve: 'set' | Curve]\n | readonly [time: number | `${number}d`, value: number, curve: 'set' | Curve, fixed: 'fixed']\nexport type Envelope = readonly EnvelopePoint[]\n\nexport type FilterSpec = {\n readonly type: BiquadFilterType\n readonly frequency: Automation\n readonly q?: Range\n /** The BiquadFilter gain (shelf and peaking types). */\n readonly gain?: Range\n /** A gain node after the filter, for a parallel bank where each band has its own level (the game's scream formants). */\n readonly level?: Range\n}\n\nexport type FilterBank = { readonly mode: 'serial' | 'parallel'; readonly bank: readonly FilterSpec[] }\n\n/** An LFO. `depth` is absolute, or a factor of the source start frequency. With `base`, gain modulation goes through its own gain stage (the game rotor). */\nexport type Modulator = {\n readonly target: 'gain' | 'frequency'\n /** Left out, the oscillator keeps its default (sine) and no type is set. */\n readonly wave?: OscillatorType\n readonly rate: Range\n readonly depth: Range | { readonly scaleOf: 'frequency'; readonly factor: number }\n readonly base?: number\n}\n\n/**\n * Noise from the engine's seeded buffer. `offset` is where playback starts in it: `'random'` (random × `offsetScale`, default 1), `'fit'`\n * (random × (buffer length − duration)) or seconds. `loop` sets the source to loop (the art scene sets it on every noise source).\n */\nexport type NoiseSource = {\n readonly kind: 'noise'\n readonly offset?: 'random' | 'fit' | number\n readonly offsetScale?: number\n readonly loop?: boolean\n}\n\nexport type OscSource = { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency: Automation }\n\n/** The art scene's `voice`: an oscillator with vibrato through formant bands, plus a band of breath noise, summed and boosted. */\nexport type FormantVoiceSource = {\n readonly kind: 'formant_voice'\n readonly wave: OscillatorType\n readonly frequency: Automation\n /** Vibrato rate, and depth as a factor of the start frequency. */\n readonly vibrato: { readonly rate: Range; readonly depth: number }\n readonly formants: readonly { readonly frequency: Range; readonly q: number }[]\n readonly breath: { readonly frequency: Range; readonly q: number; readonly gain: Range }\n readonly mix: number\n}\n\nexport type LayerSource = NoiseSource | OscSource | FormantVoiceSource\n\nexport type Layer = {\n /** Start, seconds after the sound starts. */\n readonly at?: Range\n /** Overrides the recipe duration for this layer. */\n readonly duration?: Range\n /** Seconds the source keeps running after the duration (the `+ 0.05` of the team routines). Default: the recipe's, else 0.05. */\n readonly tail?: number\n /** The layer played `count` times, `spacing` seconds apart (the game's animal calls). */\n readonly repeat?: { readonly count: number; readonly spacing: number }\n /** Layer level before distance. Default 1. */\n readonly gain?: Range\n /** Send to the reverb, 0..1 or more (the art scene uses up to 1.2). */\n readonly wet?: number\n readonly source: LayerSource\n readonly filters?: FilterBank\n readonly modulators?: readonly Modulator[]\n readonly envelope: Envelope\n}\n\n/**\n * Distance falloff of a sound's level:\n * - `inverse_square`: `volume / (1 + d² × k)`; `cutoffK` also divides every lowpass cutoff by `1 + d × cutoffK` (the game's muffling);\n * - `linear`: `max(0, 1 − d / range)`, silent at or below `minGain`;\n * - `none`: no distance.\n * `scale` multiplies the level (the game's boom is 1.4 at the source), and below `minGain` the sound is not played.\n */\nexport type Falloff =\n | { readonly model: 'inverse_square'; readonly k: number; readonly minGain?: number; readonly cutoffK?: number; readonly scale?: number }\n | { readonly model: 'linear'; readonly range: number; readonly minGain?: number; readonly scale?: number }\n | { readonly model: 'none' }\n\n/**\n * The order the realizer creates and wires the nodes in. Each one is the order of the team routine it reproduces, so the trace of the SDK\n * matches the trace of the team code node for node:\n * - `layered` (default): the art scene's `sNoise`, `sTone` and `voice`; every layer has its own output stage (distance gain, pan, reverb send);\n * - `burst`: the game's `sfx` (jogo L62089);\n * - `scream`: the game's `grito` (L62128);\n * - `groan`: the game's `voz` (L62143);\n * - `boom`: the game's `boom` (L68278);\n * - `static`: the game's `chiado` (L69998);\n * - `chord`: the game's `buzina` (L70272);\n * - `calls`: the game's `bichoSom` (L66625);\n * - `siren`: the art scene's `siren` (L1369);\n * - `weapon`: the weapon audio of the kit (`weapons-three`): per layer a filtered noise burst or an oscillator, then its own gain, chained to the bus.\n * Every order but `layered` puts the level into the envelope and connects straight to the bus.\n */\nexport const BUILD_ORDERS = ['layered', 'burst', 'scream', 'groan', 'boom', 'static', 'chord', 'calls', 'siren', 'weapon'] as const\nexport type BuildOrder = (typeof BUILD_ORDERS)[number]\n\nexport type SoundRecipe = {\n readonly id: string\n readonly bus: BusId\n readonly order?: BuildOrder\n /** Named numbers drawn first, in the order written; layers read them with `{ param }`. */\n readonly vars?: Readonly<Record<string, Range>>\n readonly duration?: Range\n readonly tail?: number\n readonly layers: readonly Layer[]\n readonly falloff?: Falloff\n /** Stereo pan from the listener (the art scene's `panFor`). Only the `layered` order has an output stage to pan. */\n readonly pan?: boolean\n /** Voice group for the limiter (`undead_voice`...). */\n readonly group?: string\n /** Limiter priority; default from the bus (weapons > voices > world > ambience). */\n readonly priority?: number\n /**\n * The team routine creates nodes before it checks the level (the game's `bichoSom` creates its gain and filter first): a silent sound is kept as\n * a plan with `silent: true` so the realizer repeats those nodes. Off by default.\n */\n readonly keepSilent?: boolean\n /** Where the numbers come from: `\"jogo:L62128\"`, `\"cena:L1342\"`, or `\"sdk\"` for values the kit chose. */\n readonly sources: readonly string[]\n}\n\n/**\n * The order the loop realizer creates the nodes in:\n * - `game_loop`: the game's `loopSet` (L62109): gain and filter first, nodes created the first time the volume passes `startAbove`, gain from 0;\n * - `chain_loop`: the art scene's loops in `initAudio` (L1314–1316): source, filters, gain at its starting volume, created when the loop opens.\n */\nexport type LoopOrder = 'game_loop' | 'chain_loop'\n\nexport type LoopRecipe = {\n readonly id: string\n readonly bus: BusId\n readonly order?: LoopOrder\n /** An oscillator loop may leave the frequency out: it starts at the default and `set({ frequency })` glides it (the game's motor). */\n readonly source: (NoiseSource & { readonly loop: true }) | { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency?: Automation; readonly loop: true }\n readonly filters?: FilterBank\n readonly modulators?: readonly Modulator[]\n /** `setTargetAtTime` time constants (jogo L62125–62126: 0.15 for the volume, 0.08 for the frequency). */\n readonly smoothing?: { readonly volume: number; readonly frequency: number }\n /** Nodes are created the first time the volume reaches this (jogo L62112: 0.002). */\n readonly startAbove?: number\n /** Volume the gain starts at when the loop opens (`chain_loop`). */\n readonly volume?: number\n /**\n * Distance falloff of the loop, applied each time `set` gives a `position` (an engine, a fire, a skid heard from where it is). Left out, the loop is\n * heard at the listener, as the team loops are. `cutoffK` also lowers the first filter's cutoff with the distance, as it does for one-shots.\n */\n readonly falloff?: Falloff\n /** Stereo pan from the listener, from the `position` of each `set` (a panner after the gain). Off by default. */\n readonly pan?: boolean\n readonly sources: readonly string[]\n}\n\n/**\n * One id that plays one of several recipes (the takes of a footstep, of a punch): `play(id)` draws a variant, never the one it played last time (unless\n * `repeat`), and plays it at a rate drawn from `rate` (1.04 is 4% higher and 4% shorter; see `retunePlan`), so ten footsteps never sound like one.\n */\nexport type SoundSet = {\n readonly id: string\n /** Recipe ids, at least one. */\n readonly variants: readonly string[]\n /** `[min, max]` of the playback rate (pitch and speed together). Default `[1, 1]`. */\n readonly rate?: readonly [min: number, max: number]\n /** Allow the same variant twice in a row (default false). */\n readonly repeat?: boolean\n}\n\nexport type SoundBank = {\n readonly id: string\n readonly sounds?: readonly SoundRecipe[]\n readonly loops?: readonly LoopRecipe[]\n readonly sets?: readonly SoundSet[]\n /** Sounds played from recorded files (see `sample.ts`). A sample and a recipe may share an id: the sample plays once its files are loaded. */\n readonly samples?: readonly SampleSound[]\n}\n\n// ----- sounds from recorded files (planned by `planSample` in sample.ts; the types live here so the bank has them without an import cycle)\n\n/** One take: a file and its own trim (linear gain, default 1). */\nexport type SampleRef = { readonly url: string; readonly gain?: number }\n\n/** Where a sound happens: a closed room rings short and dense, the open field long and thin. */\nexport type SampleEnvironment = 'indoor' | 'outdoor'\n\n/** Where the near take hands over to the far one: all near up to `from` metres, all far from `to`, an equal-power crossfade between. */\nexport type SampleCrossover = { readonly from: number; readonly to: number }\n\nexport type SampleTail = {\n readonly indoor?: readonly SampleRef[]\n readonly outdoor?: readonly SampleRef[]\n /** Level of the tail against the dry take (default 0.6). */\n readonly gain?: number\n /** Seconds after the start (default 0: the tail file carries its own pre-delay). */\n readonly at?: number\n}\n\n/**\n * A set of takes for a strength of the action (criterion C7: a light blow, a heavy one, a car at 10 or 60 km/h): from `from` (0..1) up, these takes\n * replace `close` and `far`. The tier played is the last one whose `from` is at or below `PlayOptions.intensity`.\n */\nexport type SampleTier = {\n readonly name: string\n readonly from: number\n readonly close: readonly SampleRef[]\n readonly far?: readonly SampleRef[]\n}\n\nexport type SampleSound = {\n readonly id: string\n readonly bus: BusId\n /** The takes heard near; at least one (the criteria ask four for a sound heard all the time). */\n readonly close: readonly SampleRef[]\n /** The takes heard far; without them the near take plays at every distance (muffled by the lowpass). */\n readonly far?: readonly SampleRef[]\n /** Takes by strength (light, medium, heavy), in rising `from`; without `intensity` the near takes above play. */\n readonly tiers?: readonly SampleTier[]\n /** Default `{ from: 30, to: 80 }`. */\n readonly crossover?: SampleCrossover\n readonly tail?: SampleTail\n /** ± fraction of the playback rate drawn per play (default 0.04: ±4 %, inside the 3–5 % of the criteria). 0 plays every take at its pitch. */\n readonly pitch?: number\n /** Level of the sound (default 1). */\n readonly gain?: number\n /** Default `{ model: 'inverse_square', k: 0.002, minGain: 0.002 }`: a recorded take already sounds near or far, so the curve is gentler than a recipe's. */\n readonly falloff?: Falloff\n /** The lowpass cutoff is `20000 / (1 + d × cutoffK)` Hz (default 0.01: 10 kHz at 100 m). 0 turns the distance lowpass off. */\n readonly cutoffK?: number\n /** Stereo pan from the listener (default true). */\n readonly pan?: boolean\n readonly group?: string\n readonly priority?: number\n /**\n * At most `voices` plays of this sound ring at once: a new one fades the oldest out in `fade` seconds (default 0.03) at its own start. Rapid fire\n * then stays shot by shot instead of a wall of overlapping takes (criterion C9). Without it every play rings to its end.\n */\n readonly choke?: { readonly voices: number; readonly fade?: number }\n /**\n * A continuous sound (fire, rain, an engine idling) that `engine.loop(id)` plays: the near takes chained without a seam, each crossed into the next\n * in `crossfade` seconds (default 0.25, equal power), never the same take twice in a row. While the files load, the recipe loop of `fallback`\n * (or of the same id) plays. `play(id)` still plays one take as a one-shot.\n */\n readonly loop?: boolean | { readonly crossfade?: number }\n /** A recipe id the engine plays while the files are not loaded yet (or failed): the synthesized sound stays as the fallback. */\n readonly fallback?: string\n /** Where each file came from: `\"freesound:123456 autor CC0\"`, or `\"sdk\"` for files the kit made. */\n readonly sources: readonly string[]\n}\n","import type { Falloff } from './recipe'\n\n/** The distance curves of the team routines, by name. Each recipe carries its own; these are the values to copy. */\nexport const DISTANCE_CURVES = {\n /** The game's `sfx`: `vol / (1 + d² × 0.004)`, cutoff `/ (1 + d × 0.01)`, silent below 0.01 (jogo L62091–62092, L62101). */\n game_sfx: { model: 'inverse_square', k: 0.004, cutoffK: 0.01, minGain: 0.01 },\n /** The game's `grito`: `1 / (1 + d² × 0.006)`, silent below 0.02 (jogo L62129–62130). */\n game_scream: { model: 'inverse_square', k: 0.006, minGain: 0.02 },\n /** The game's `voz`: `1 / (1 + d² × 0.01)`, silent below 0.02 (jogo L62146–62147). */\n game_voice: { model: 'inverse_square', k: 0.01, minGain: 0.02 },\n /** The game's `boom`: `1.4 / (1 + d² × 0.002)`, never silent (jogo L68280). */\n game_boom: { model: 'inverse_square', k: 0.002, scale: 1.4 },\n /** The art scene's `outAt`: `vol / (1 + d² × 0.008)` (cena L1320). */\n art_scene: { model: 'inverse_square', k: 0.008 },\n /** The game's animal calls: `max(0, 1 − d / 70) × 0.25`, silent at or below 0.005 (jogo L66627–66628). */\n animals: { model: 'linear', range: 70, scale: 0.25, minGain: 0.005 },\n} as const satisfies Readonly<Record<string, Falloff>>\n\nexport type DistanceCurveName = keyof typeof DISTANCE_CURVES\n\n/** The level at `distance` for a sound at `volume`, before the recipe's envelope. */\nexport function falloffGain(falloff: Falloff | undefined, volume: number, distance: number): number {\n if (!falloff || falloff.model === 'none') return volume\n if (falloff.model === 'linear') {\n const level = Math.max(0, 1 - distance / falloff.range) * volume\n return falloff.scale === undefined ? level : level * falloff.scale\n }\n const level = volume / (1 + distance * distance * falloff.k)\n return falloff.scale === undefined ? level : falloff.scale * level\n}\n\n/** Whether a level is too quiet to play: below `minGain` (the game's `att < 0.01`), or at or below it for `linear` (the animal calls' `v <= 0.005`). */\nexport function isSilent(falloff: Falloff | undefined, gain: number): boolean {\n if (!falloff || falloff.model === 'none' || falloff.minGain === undefined) return false\n return falloff.model === 'linear' ? gain <= falloff.minGain : gain < falloff.minGain\n}\n\n/** What every lowpass cutoff is divided by at `distance` (1 when the curve has no muffling). */\nexport function cutoffDivisor(falloff: Falloff | undefined, distance: number): number {\n if (!falloff || falloff.model !== 'inverse_square' || falloff.cutoffK === undefined) return 1\n return 1 + distance * falloff.cutoffK\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\n/** Where the ears are. `yaw` turns around y like a three.js camera: the right ear points at `(cos yaw, 0, −sin yaw)`. */\nexport type Listener = { readonly position: Vec3; readonly yaw: number }\n\nexport type DistanceMode = 'xz' | '3d'\n\nexport const DEFAULT_LISTENER: Listener = { position: [0, 0, 0], yaw: 0 }\n\n/** The art scene clamps the pan to ±0.85 and never divides by less than 2 m (cena L1319). */\nexport const PAN_LIMIT = 0.85\nexport const PAN_MIN_DISTANCE = 2\n\n/** Distance from the listener: on the ground (`xz`, the teams' choice) or in 3D. */\nexport function listenerDistance(listener: Listener, position: Vec3, mode: DistanceMode = 'xz'): number {\n const dx = position[0] - listener.position[0]\n const dz = position[2] - listener.position[2]\n if (mode === 'xz') return Math.hypot(dx, dz)\n return Math.hypot(dx, position[1] - listener.position[1], dz)\n}\n\n/** The art scene's `panFor`: the side the sound is on, −0.85 (left) to 0.85 (right). No HRTF, for cost. */\nexport function panFor(listener: Listener, position: Vec3): number {\n const rightX = Math.cos(listener.yaw)\n const rightZ = -Math.sin(listener.yaw)\n const dx = position[0] - listener.position[0]\n const dz = position[2] - listener.position[2]\n const distance = Math.hypot(dx, dz) || 1\n const pan = (dx * rightX + dz * rightZ) / Math.max(distance, PAN_MIN_DISTANCE)\n return pan < -PAN_LIMIT ? -PAN_LIMIT : pan > PAN_LIMIT ? PAN_LIMIT : pan\n}\n","{\n \"undead_voice\": {\n \"maxConcurrent\": 5,\n \"cooldown\": 0.25,\n \"maxDistance\": 40,\n \"sources\": [\n \"cena:L1342 `AU.groans > 4` refuses, so five play at once\",\n \"jogo:L66986 one groan every 0.25 s (`groanBudget`), only nearer than 40 m\",\n \"jogo:L70472 the budget counts down by the frame time\"\n ]\n },\n \"fire_ignite\": {\n \"maxConcurrent\": 2,\n \"cooldown\": 0.15,\n \"sources\": [\n \"sdk: many parts catching at once (a blast sets a shelf alight) are one or two ignitions, not forty\"\n ]\n },\n \"fire_crackle\": {\n \"maxConcurrent\": 4,\n \"sources\": [\n \"sdk: the crackles of every fire share four voices\"\n ]\n }\n}\n","import voiceGroupsJson from './data/voice-groups.json'\nimport type { BusId } from './recipe'\n\n/**\n * Rules for a group of voices (`undead_voice`...). A request passes when every rule passes:\n * - `maxConcurrent`: at most this many of the group play at once (`steal` replaces the group's oldest instead of refusing);\n * - `cooldown`: seconds after an accepted voice before the next one (the game's `groanBudget`, jogo L66986 and L70472);\n * - `maxDistance`: only voices nearer than this (the game's `d < 40`).\n */\nexport type VoiceGroup = {\n readonly maxConcurrent?: number\n readonly cooldown?: number\n readonly maxDistance?: number\n readonly steal?: boolean\n readonly sources?: readonly string[]\n}\n\n/** `undead_voice`: the art scene's five at once with the game's 0.25 s cooldown and 40 m. */\nexport const VOICE_GROUPS: Readonly<Record<string, VoiceGroup>> = voiceGroupsJson\n\n/** Q7: weapons > voices > world > ambience; the interface above all, weather with the ambience. */\nexport const BUS_PRIORITY: Readonly<Record<BusId, number>> = { ui: 5, weapons: 4, voices: 3, world: 2, weather: 1, ambience: 1 }\nexport const DEFAULT_MAX_VOICES = 32\n\nexport function busPriority(bus: BusId): number {\n return BUS_PRIORITY[bus]\n}\n\nexport type VoiceRequest = {\n readonly group?: string\n readonly priority: number\n /** Planned level; the global cap drops the lowest `priority × gain`. */\n readonly gain: number\n readonly distance?: number\n /** Seconds the voice lasts. */\n readonly length: number\n}\n\nexport type VoiceRefusal = 'cooldown' | 'distance' | 'group_full' | 'global_full'\n\nexport type VoiceDecision =\n | { readonly accepted: true; readonly id: number; readonly evicted: readonly number[] }\n | { readonly accepted: false; readonly reason: VoiceRefusal }\n\nexport type VoiceStats = { readonly active: number; readonly peak: number; readonly dropped: number; readonly maxVoices: number }\n\nexport type VoiceManager = {\n request(request: VoiceRequest): VoiceDecision\n /** Ends a voice early (stopped by the host). */\n release(id: number): void\n /** Sets how long an accepted voice lasts (the engine admits a voice before its random length is drawn). */\n setLength(id: number, seconds: number): void\n /** Moves time on: cooldowns count down and finished voices leave. Returns the ids that ended. */\n advance(dt: number): number[]\n setGroup(id: string, group: VoiceGroup | undefined): void\n stats(): VoiceStats\n}\n\nexport type VoiceManagerOptions = {\n /** Default `VOICE_GROUPS`. */\n readonly groups?: Readonly<Record<string, VoiceGroup>>\n readonly maxVoices?: number\n}\n\ntype ActiveVoice = { readonly id: number; readonly group?: string; readonly score: number; remaining: number }\n\n/** The voice limiter: per-group rules, a global cap and priority dropping. Pure and time-driven (`advance`), so goldens script it frame by frame. */\nexport function createVoiceManager(options: VoiceManagerOptions = {}): VoiceManager {\n const groups = new Map(Object.entries(options.groups ?? VOICE_GROUPS))\n const maxVoices = options.maxVoices ?? DEFAULT_MAX_VOICES\n const budgets = new Map<string, number>()\n let voices: ActiveVoice[] = []\n let nextId = 1\n let peak = 0\n let dropped = 0\n\n const refuse = (reason: VoiceRefusal): VoiceDecision => {\n dropped += 1\n return { accepted: false, reason }\n }\n\n const groupCheck = (request: VoiceRequest, evicted: number[]): VoiceRefusal | undefined => {\n const group = request.group === undefined ? undefined : groups.get(request.group)\n if (!group) return undefined\n if (group.maxDistance !== undefined && !((request.distance ?? 0) < group.maxDistance)) return 'distance'\n if (group.cooldown !== undefined && (budgets.get(request.group as string) ?? 0) > 0) return 'cooldown'\n const members = voices.filter((voice) => voice.group === request.group)\n if (group.maxConcurrent === undefined || members.length < group.maxConcurrent) return undefined\n if (!group.steal) return 'group_full'\n evicted.push((members[0] as ActiveVoice).id)\n return undefined\n }\n\n return {\n request(request) {\n const evicted: number[] = []\n const refusal = groupCheck(request, evicted)\n if (refusal) return refuse(refusal)\n const score = request.priority * request.gain\n const remaining = voices.filter((voice) => !evicted.includes(voice.id))\n if (remaining.length >= maxVoices) {\n const lowest = remaining.reduce((low, voice) => (voice.score < low.score ? voice : low))\n if (score <= lowest.score) return refuse('global_full')\n evicted.push(lowest.id)\n dropped += 1\n }\n const group = request.group === undefined ? undefined : groups.get(request.group)\n if (group?.cooldown !== undefined) budgets.set(request.group as string, group.cooldown)\n const id = nextId++\n voices = [...voices.filter((voice) => !evicted.includes(voice.id)), { id, ...(request.group === undefined ? {} : { group: request.group }), score, remaining: request.length }]\n peak = Math.max(peak, voices.length)\n return { accepted: true, id, evicted }\n },\n release(id) {\n voices = voices.filter((voice) => voice.id !== id)\n },\n setLength(id, seconds) {\n const voice = voices.find((entry) => entry.id === id)\n if (voice) voice.remaining = seconds\n },\n advance(dt) {\n for (const [group, budget] of budgets) budgets.set(group, budget - dt)\n const ended: number[] = []\n for (const voice of voices) {\n voice.remaining -= dt\n if (voice.remaining <= 0) ended.push(voice.id)\n }\n if (ended.length > 0) voices = voices.filter((voice) => voice.remaining > 0)\n return ended\n },\n setGroup(id, group) {\n if (group) groups.set(id, group)\n else groups.delete(id)\n },\n stats: () => ({ active: voices.length, peak, dropped, maxVoices }),\n }\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { cutoffDivisor, falloffGain, isSilent } from './falloff'\nimport { DEFAULT_LISTENER, listenerDistance, panFor } from './listener'\nimport type { DistanceMode, Listener } from './listener'\nimport type { Automation, BuildOrder, BusId, Curve, Envelope, FilterSpec, Layer, LayerSource, Modulator, Range, SoundRecipe, Time } from './recipe'\nimport { createRng } from './rng'\nimport { busPriority } from './voices'\n\n/** How an AudioParam moves, with every number resolved and every time in seconds from the layer start. */\nexport type PlannedAutomation = {\n /** Assigned to `.value`. */\n readonly value?: number\n /** `setValueAtTime(from)` at the layer start. */\n readonly from?: number\n /** Ramp target, reached `at` seconds after the layer start. */\n readonly to?: number\n readonly curve?: Curve\n readonly at?: number\n}\n\nexport type PlannedFilter = {\n readonly type: BiquadFilterType\n readonly frequency: PlannedAutomation\n readonly q?: number\n readonly gain?: number\n readonly level?: number\n}\n\nexport type PlannedModulator = {\n readonly target: 'gain' | 'frequency'\n readonly wave?: OscillatorType\n readonly rate: number\n readonly depth: number\n readonly base?: number\n}\n\nexport type PlannedSource =\n | { readonly kind: 'noise'; readonly offset: number; readonly loop: boolean }\n | { readonly kind: 'osc'; readonly wave: OscillatorType; readonly frequency: PlannedAutomation }\n | {\n readonly kind: 'formant_voice'\n readonly wave: OscillatorType\n readonly frequency: PlannedAutomation\n readonly vibrato: { readonly rate: number; readonly depth: number }\n readonly formants: readonly { readonly frequency: number; readonly q: number }[]\n readonly breath: { readonly frequency: number; readonly q: number; readonly gain: number; readonly offset: number }\n readonly mix: number\n }\n\nexport type PlannedEnvelopePoint = { readonly time: number; readonly value: number; readonly curve: 'set' | Curve }\n\nexport type PlannedLayer = {\n readonly at: number\n readonly duration: number\n readonly tail: number\n /** Layer gain × the sound's level: in the envelope for every order but `layered`, in the output stage for `layered`. */\n readonly level: number\n readonly wet?: number\n readonly source: PlannedSource\n readonly filters?: { readonly mode: 'serial' | 'parallel'; readonly bank: readonly PlannedFilter[] }\n readonly modulators: readonly PlannedModulator[]\n readonly envelope: readonly PlannedEnvelopePoint[]\n}\n\n/** A sound with every number decided: what the realizer builds, what goldens compare and what the bench sheet prints. */\nexport type SoundPlan = {\n readonly id: string\n readonly bus: BusId\n readonly order: BuildOrder\n readonly group?: string\n readonly priority: number\n /** The level from volume and distance, before layer gains. */\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** Too quiet to hear, kept only for a recipe with `keepSilent`. */\n readonly silent: boolean\n /** Seconds until the last source stops. */\n readonly length: number\n readonly layers: readonly PlannedLayer[]\n}\n\nexport type PlanInput = {\n /** Where the numbers are drawn from. Default: a fresh stream with seed 1. */\n readonly random?: () => number\n readonly volume?: number\n /** Distance in meters; overrides `position`. */\n readonly distance?: number\n readonly position?: Vec3\n readonly listener?: Listener\n readonly distanceMode?: DistanceMode\n readonly params?: Readonly<Record<string, number>>\n /** 0..1 from the host's occlusion callback: gain × (1 − 0.5 × o), lowpass cutoffs × (1 − 0.6 × o). */\n readonly occlusion?: number\n /** Length of the noise buffer, for `offset: 'fit'`. Default 1.5. */\n readonly noiseSeconds?: number\n}\n\nconst DEFAULT_TAIL = 0.05\nconst DEFAULT_NOISE_SECONDS = 1.5\nconst OCCLUSION_GAIN = 0.5\nconst OCCLUSION_CUTOFF = 0.6\n\ntype Scope = { readonly random: () => number; readonly params: Record<string, number> }\n\nfunction isParamRef(range: Range): range is Extract<Range, { readonly param: string }> {\n return typeof range === 'object' && !Array.isArray(range)\n}\n\nfunction draw(range: Range, scope: Scope): number {\n if (typeof range === 'number') return range\n if (isParamRef(range)) {\n const value = scope.params[range.param]\n if (value === undefined) throw new Error(`game-audio: the recipe reads the param \"${range.param}\", which was not given`)\n return value * (range.scale ?? 1) + (range.add ?? 0)\n }\n const [min, max] = range as readonly [number, number]\n return min + scope.random() * (max - min)\n}\n\n// a time is drawn now when it is a range; 'duration' and '0.6d' wait for the layer duration\ntype PendingTime = number | 'duration' | `${number}d`\n\nfunction drawTime(time: Time, scope: Scope): PendingTime {\n if (time === 'duration' || (typeof time === 'string' && time.endsWith('d'))) return time as PendingTime\n return draw(time as Range, scope)\n}\n\nfunction timeOf(time: PendingTime, duration: number): number {\n if (typeof time === 'number') return time\n if (time === 'duration') return duration\n return Number(time.slice(0, -1)) * duration\n}\n\ntype PendingAutomation = { value?: number; from?: number; to?: number; curve?: Curve; over?: PendingTime }\n\nfunction drawAutomation(automation: Automation, scope: Scope): PendingAutomation {\n const pending: PendingAutomation = {}\n for (const key of Object.keys(automation)) {\n if (key === 'set' && 'set' in automation) pending.value = draw(automation.set, scope)\n else if (key === 'from' && 'from' in automation) pending.from = draw(automation.from, scope)\n else if (key === 'to' && automation.to !== undefined) pending.to = automation.to === 'from' ? (pending.from ?? pending.value ?? 0) : draw(automation.to, scope)\n else if (key === 'curve') pending.curve = automation.curve\n else if (key === 'over' && automation.over !== undefined) pending.over = drawTime(automation.over, scope)\n }\n return pending\n}\n\nfunction finishAutomation(pending: PendingAutomation, duration: number): PlannedAutomation {\n if (pending.from !== undefined && pending.to === undefined) return { from: pending.from }\n if (pending.from !== undefined) return { from: pending.from, to: pending.to, curve: pending.curve ?? 'linear', at: timeOf(pending.over ?? 'duration', duration) }\n if (pending.to === undefined || pending.over === undefined) return { value: pending.value }\n return { value: pending.value, to: pending.to, curve: pending.curve ?? 'linear', at: timeOf(pending.over, duration) }\n}\n\nconst startFrequency = (automation: PendingAutomation): number => automation.from ?? automation.value ?? 0\n\ntype PendingFilter = { spec: FilterSpec; frequency: PendingAutomation; q?: number; gain?: number; level?: number }\n\nfunction drawFilter(spec: FilterSpec, scope: Scope): PendingFilter {\n const pending: PendingFilter = { spec, frequency: {} }\n for (const key of Object.keys(spec)) {\n if (key === 'frequency') pending.frequency = drawAutomation(spec.frequency, scope)\n else if (key === 'q' && spec.q !== undefined) pending.q = draw(spec.q, scope)\n else if (key === 'gain' && spec.gain !== undefined) pending.gain = draw(spec.gain, scope)\n else if (key === 'level' && spec.level !== undefined) pending.level = draw(spec.level, scope)\n }\n return pending\n}\n\ntype PendingModulator = { modulator: Modulator; rate: number; depth?: number }\n\nfunction drawModulator(modulator: Modulator, scope: Scope): PendingModulator {\n const pending: PendingModulator = { modulator, rate: 0 }\n for (const key of Object.keys(modulator)) {\n if (key === 'rate') pending.rate = draw(modulator.rate, scope)\n else if (key === 'depth' && !(typeof modulator.depth === 'object' && 'scaleOf' in modulator.depth)) pending.depth = draw(modulator.depth as Range, scope)\n }\n return pending\n}\n\ntype PendingVoice = { frequency: PendingAutomation; vibratoRate: number; formants: { frequency: number; q: number }[]; breath: { frequency: number; q: number; gain: number } }\n\nfunction drawVoice(source: Extract<LayerSource, { kind: 'formant_voice' }>, scope: Scope): PendingVoice {\n const pending: PendingVoice = { frequency: {}, vibratoRate: 0, formants: [], breath: { frequency: 0, q: source.breath.q, gain: 0 } }\n for (const key of Object.keys(source)) {\n if (key === 'frequency') pending.frequency = drawAutomation(source.frequency, scope)\n else if (key === 'vibrato') pending.vibratoRate = draw(source.vibrato.rate, scope)\n else if (key === 'formants') pending.formants = source.formants.map((formant) => ({ frequency: draw(formant.frequency, scope), q: formant.q }))\n else if (key === 'breath') pending.breath = { frequency: draw(source.breath.frequency, scope), q: source.breath.q, gain: draw(source.breath.gain, scope) }\n }\n return pending\n}\n\ntype LayerDefaults = { readonly duration?: number; readonly tail?: number; readonly noiseSeconds: number }\n\ntype PendingLayer = {\n at: number\n duration?: number\n gain: number\n automation?: PendingAutomation\n voice?: PendingVoice\n filters: PendingFilter[]\n modulators: PendingModulator[]\n}\n\nfunction drawLayer(layer: Layer, scope: Scope): PendingLayer {\n const pending: PendingLayer = { at: 0, gain: 1, filters: [], modulators: [] }\n for (const key of Object.keys(layer)) {\n if (key === 'at' && layer.at !== undefined) pending.at = draw(layer.at, scope)\n else if (key === 'duration' && layer.duration !== undefined) pending.duration = draw(layer.duration, scope)\n else if (key === 'gain' && layer.gain !== undefined) pending.gain = draw(layer.gain, scope)\n else if (key === 'source' && layer.source.kind === 'osc') pending.automation = drawAutomation(layer.source.frequency, scope)\n else if (key === 'source' && layer.source.kind === 'formant_voice') pending.voice = drawVoice(layer.source, scope)\n else if (key === 'filters' && layer.filters) pending.filters = layer.filters.bank.map((spec) => drawFilter(spec, scope))\n else if (key === 'modulators' && layer.modulators) pending.modulators = layer.modulators.map((modulator) => drawModulator(modulator, scope))\n }\n return pending\n}\n\n// the team code draws the noise start point when the source starts, after every other number of the layer\nfunction drawOffset(source: LayerSource, duration: number, scope: Scope, noiseSeconds: number): number {\n if (source.kind === 'formant_voice') return scope.random()\n if (source.kind !== 'noise' || source.offset === undefined) return 0\n if (typeof source.offset === 'number') return source.offset\n if (source.offset === 'fit') return scope.random() * Math.max(0, noiseSeconds - duration)\n return scope.random() * (source.offsetScale ?? 1)\n}\n\nfunction finishSource(layer: Layer, pending: PendingLayer, duration: number, offset: number): PlannedSource {\n const source = layer.source\n if (source.kind === 'noise') return { kind: 'noise', offset, loop: source.loop === true }\n if (source.kind === 'osc') return { kind: 'osc', wave: source.wave, frequency: finishAutomation(pending.automation ?? {}, duration) }\n const voice = pending.voice as PendingVoice\n return {\n kind: 'formant_voice',\n wave: source.wave,\n frequency: finishAutomation(voice.frequency, duration),\n vibrato: { rate: voice.vibratoRate, depth: startFrequency(voice.frequency) * source.vibrato.depth },\n formants: voice.formants,\n breath: { ...voice.breath, offset },\n mix: source.mix,\n }\n}\n\nfunction finishModulator(pending: PendingModulator, sourceFrequency: number): PlannedModulator {\n const { modulator } = pending\n const depth = typeof modulator.depth === 'object' && 'scaleOf' in modulator.depth ? sourceFrequency * modulator.depth.factor : (pending.depth ?? 0)\n return { target: modulator.target, ...(modulator.wave ? { wave: modulator.wave } : {}), rate: pending.rate, depth, ...(modulator.base === undefined ? {} : { base: modulator.base }) }\n}\n\nfunction finishEnvelope(envelope: Envelope, duration: number, level: number): PlannedEnvelopePoint[] {\n return envelope.map(([time, value, curve, fixed]) => ({ time: timeOf(time, duration), value: fixed === 'fixed' ? value : value * level, curve }))\n}\n\nfunction planLayer(layer: Layer, scope: Scope, defaults: LayerDefaults, levelInEnvelope: boolean, soundLevel: number): PlannedLayer[] {\n const pending = drawLayer(layer, scope)\n const duration = pending.duration ?? defaults.duration\n if (duration === undefined) throw new Error('game-audio: a layer needs a duration (its own or the recipe’s)')\n const offset = drawOffset(layer.source, duration, scope, defaults.noiseSeconds)\n const level = pending.gain * soundLevel\n const sourceFrequency = layer.source.kind === 'noise' ? 0 : startFrequency(pending.automation ?? pending.voice?.frequency ?? {})\n const planned: PlannedLayer = {\n at: pending.at,\n duration,\n tail: layer.tail ?? defaults.tail ?? DEFAULT_TAIL,\n level,\n ...(layer.wet === undefined ? {} : { wet: layer.wet }),\n source: finishSource(layer, pending, duration, offset),\n ...(layer.filters\n ? {\n filters: {\n mode: layer.filters.mode,\n bank: pending.filters.map(({ spec, frequency, q, gain, level: filterLevel }) => ({\n type: spec.type,\n frequency: finishAutomation(frequency, duration),\n ...(q === undefined ? {} : { q }),\n ...(gain === undefined ? {} : { gain }),\n ...(filterLevel === undefined ? {} : { level: filterLevel }),\n })),\n },\n }\n : {}),\n modulators: pending.modulators.map((modulator) => finishModulator(modulator, sourceFrequency)),\n envelope: finishEnvelope(layer.envelope, duration, levelInEnvelope ? level : 1),\n }\n if (!layer.repeat) return [planned]\n return Array.from({ length: layer.repeat.count }, (_, index) => ({ ...planned, at: planned.at + index * (layer.repeat?.spacing ?? 0) }))\n}\n\nfunction scaleAutomation(automation: PlannedAutomation, divisor: number): PlannedAutomation {\n const scale = (value: number | undefined): number | undefined => (value === undefined ? undefined : value / divisor)\n const scaled: Record<string, unknown> = { ...automation }\n for (const key of ['value', 'from', 'to'] as const) if (automation[key] !== undefined) scaled[key] = scale(automation[key])\n return scaled as PlannedAutomation\n}\n\n// distance muffling and occlusion lower every lowpass cutoff of the sound\nfunction muffle(layer: PlannedLayer, divisor: number): PlannedLayer {\n if (divisor === 1 || !layer.filters) return layer\n const bank = layer.filters.bank.map((filter) => (filter.type === 'lowpass' ? { ...filter, frequency: scaleAutomation(filter.frequency, divisor) } : filter))\n return { ...layer, filters: { ...layer.filters, bank } }\n}\n\nconst layerEnd = (layer: PlannedLayer): number => layer.at + layer.duration + layer.tail\n\n/**\n * Turns a recipe into a plan: pure, Node-safe, the same plan for the same `random`. Numbers are drawn in this order: `vars` (in the order written),\n * `duration`, then each layer in the order its fields are written, the noise start point last in its layer. A sound below its falloff's `minGain`\n * gives `null` (or a silent plan with `keepSilent`) before any number is drawn.\n */\nexport function planSound(recipe: SoundRecipe, input: PlanInput = {}): SoundPlan | null {\n const listener = input.listener ?? DEFAULT_LISTENER\n const distance = input.distance ?? (input.position ? listenerDistance(listener, input.position, input.distanceMode) : 0)\n const occlusion = Math.min(1, Math.max(0, input.occlusion ?? 0))\n const order = recipe.order ?? 'layered'\n const falloffLevel = falloffGain(recipe.falloff, input.volume ?? 1, distance)\n const level = occlusion > 0 ? falloffLevel * (1 - OCCLUSION_GAIN * occlusion) : falloffLevel\n const silent = isSilent(recipe.falloff, falloffLevel)\n const base = {\n id: recipe.id,\n bus: recipe.bus,\n order,\n ...(recipe.group === undefined ? {} : { group: recipe.group }),\n priority: recipe.priority ?? busPriority(recipe.bus),\n level,\n distance,\n ...(recipe.pan ? { pan: input.position ? panFor(listener, input.position) : 0 } : {}),\n }\n if (silent) return recipe.keepSilent ? { ...base, silent: true, length: 0, layers: [] } : null\n\n const scope: Scope = { random: input.random ?? createRng(1), params: { ...input.params } }\n for (const [name, range] of Object.entries(recipe.vars ?? {})) if (scope.params[name] === undefined) scope.params[name] = draw(range, scope)\n const defaults: LayerDefaults = {\n ...(recipe.duration === undefined ? {} : { duration: draw(recipe.duration, scope) }),\n ...(recipe.tail === undefined ? {} : { tail: recipe.tail }),\n noiseSeconds: input.noiseSeconds ?? DEFAULT_NOISE_SECONDS,\n }\n const divisor = cutoffDivisor(recipe.falloff, distance) / (1 - OCCLUSION_CUTOFF * occlusion)\n const layers = recipe.layers.flatMap((layer) => planLayer(layer, scope, defaults, order !== 'layered', level)).map((layer) => muffle(layer, divisor))\n return { ...base, silent: false, length: Math.max(0, ...layers.map(layerEnd)), layers }\n}\n","/**\n * Sounds made of recorded files (`.ogg`), as data. A `SampleSound` lists the takes of each layer: `close` (the sound as heard near, the only one\n * required), `far` (the same event heard from far away: a muffled bang with its echo) and the tail of the place it happens in (`indoor` / `outdoor`).\n * `planSample` decides, from a seeded stream, which take plays (round-robin: never the same take twice in a row), the pitch (± a fraction), how the\n * near and far layers cross over with the distance, the level, the pan and the distance lowpass. It is pure, so it runs in Node and in tests; the\n * WebAudio layer (`realizeSample`) plays the plan from decoded buffers.\n */\nimport type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { falloffGain, isSilent } from './falloff'\nimport { DEFAULT_LISTENER, listenerDistance, panFor } from './listener'\nimport type { DistanceMode, Listener } from './listener'\nimport type { BusId, Falloff, SampleCrossover, SampleEnvironment, SampleRef, SampleSound, SampleTier } from './recipe'\nimport { busPriority } from './voices'\n\nexport type { SampleCrossover, SampleEnvironment, SampleRef, SampleSound, SampleTail, SampleTier } from './recipe'\n\nexport const SAMPLE_ENVIRONMENTS = ['indoor', 'outdoor'] as const satisfies readonly SampleEnvironment[]\n\n/** The role of a layer in a plan. */\nexport type SampleLayerRole = 'close' | 'far' | 'tail'\n\nexport const DEFAULT_SAMPLE_FALLOFF: Falloff = { model: 'inverse_square', k: 0.002, minGain: 0.002 }\nexport const DEFAULT_CROSSOVER: SampleCrossover = { from: 30, to: 80 }\nexport const DEFAULT_SAMPLE_PITCH = 0.04\nexport const DEFAULT_TAIL_GAIN = 0.6\nexport const DEFAULT_SAMPLE_CUTOFF_K = 0.01\n/** The open lowpass: at or above it the realizer leaves the filter out. */\nexport const OPEN_CUTOFF = 20000\n/** A layer quieter than this is left out of the plan. */\nexport const LAYER_FLOOR = 0.001\n\n/** One file to play: which take, at what level (already times the sound level), rate and start. */\nexport type PlannedSampleLayer = {\n readonly role: SampleLayerRole\n readonly url: string\n /** Index of the take in its list. */\n readonly take: number\n readonly gain: number\n readonly rate: number\n readonly at: number\n}\n\nexport type SamplePlan = {\n readonly kind: 'sample'\n readonly id: string\n readonly bus: BusId\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** Lowpass cutoff in Hz (`OPEN_CUTOFF` = no filter). */\n readonly cutoff: number\n /** Playback rate of every layer (the pitch drawn for this play). */\n readonly rate: number\n readonly environment: SampleEnvironment\n /** The tier played (`undefined` without tiers or intensity). */\n readonly tier?: string\n /** 0 = all near, 1 = all far. */\n readonly farMix: number\n readonly layers: readonly PlannedSampleLayer[]\n readonly priority: number\n readonly group?: string\n}\n\n/** The last take each sound layer played (`<id>/<role>` → index), so the next play never repeats it. Keep one per engine or channel. */\nexport type SampleMemory = Map<string, number>\n\nexport type SamplePlanInput = {\n readonly random: () => number\n readonly listener?: Listener\n readonly distanceMode?: DistanceMode\n readonly position?: Vec3\n /** Metres; overrides `position` for the distance (not for the pan). */\n readonly distance?: number\n readonly volume?: number\n /** Default `outdoor`. */\n readonly environment?: SampleEnvironment\n /** 0 (clear) to 1 (behind a wall): lowers the level and closes the lowpass. */\n readonly occlusion?: number\n /** Round-robin memory; without it each plan is drawn on its own (and may repeat). */\n readonly memory?: SampleMemory\n /** Limiter priority when the sound has none. */\n readonly priority?: number\n /** 0 (light) to 1 (heavy): picks the tier (see `SampleTier`). */\n readonly intensity?: number\n}\n\n/**\n * Round-robin without repeat: a take drawn among all but the last one played. With one take it is always 0; without `last` any take may come.\n * One random number per call.\n */\nexport function pickTake(count: number, last: number | undefined, random: () => number): number {\n if (count <= 1) return 0\n if (last === undefined || last < 0 || last >= count) return Math.min(count - 1, Math.floor(random() * count))\n const drawn = Math.min(count - 2, Math.floor(random() * (count - 1)))\n return drawn >= last ? drawn + 1 : drawn\n}\n\n/** 0 at or below `from`, 1 at or beyond `to`, linear between. */\nexport function farMixAt(crossover: SampleCrossover, distance: number): number {\n if (crossover.to <= crossover.from) return distance >= crossover.to ? 1 : 0\n const t = (distance - crossover.from) / (crossover.to - crossover.from)\n return t <= 0 ? 0 : t >= 1 ? 1 : t\n}\n\n/** Equal-power gains of the near and far layers for a far mix (so the crossover has no dip in loudness). */\nexport function crossGains(farMix: number): { readonly close: number; readonly far: number } {\n return { close: Math.cos((farMix * Math.PI) / 2), far: Math.sin((farMix * Math.PI) / 2) }\n}\n\n/** The distance lowpass, closed further behind a wall (an occluded sound loses its highs first). */\nexport function sampleCutoff(cutoffK: number, distance: number, occlusion = 0): number {\n const byDistance = cutoffK > 0 ? OPEN_CUTOFF / (1 + distance * cutoffK) : OPEN_CUTOFF\n const occluded = occlusion > 0 ? byDistance / (1 + occlusion * 9) : byDistance\n return Math.max(80, Math.min(OPEN_CUTOFF, occluded))\n}\n\n/** Every file a sound may play (to load before its first play). */\nexport function sampleUrls(sound: SampleSound): string[] {\n const tiers = (sound.tiers ?? []).flatMap((tier) => [...tier.close, ...(tier.far ?? [])])\n const all = [...sound.close, ...(sound.far ?? []), ...tiers, ...(sound.tail?.indoor ?? []), ...(sound.tail?.outdoor ?? [])].map((ref) => ref.url)\n return [...new Set(all)]\n}\n\n/** The tier for an intensity: the last whose `from` is at or below it. */\nexport function tierFor(sound: SampleSound, intensity: number | undefined): SampleTier | undefined {\n if (intensity === undefined || !sound.tiers) return undefined\n let chosen: SampleTier | undefined\n for (const tier of sound.tiers) if (tier.from <= intensity) chosen = tier\n return chosen ?? sound.tiers[0]\n}\n\n/**\n * The plan of one play, or `null` when the sound is too far to be heard. Random numbers, in order: the pitch, the near take, the far take, the\n * tail take (each drawn only when that layer has more than zero takes and is heard).\n */\nexport function planSample(sound: SampleSound, input: SamplePlanInput): SamplePlan | null {\n if (sound.close.length === 0) throw new Error(`sample sound ${sound.id} has no close take`)\n const listener = input.listener ?? DEFAULT_LISTENER\n const distance = input.distance ?? (input.position ? listenerDistance(listener, input.position, input.distanceMode) : 0)\n const falloff = sound.falloff ?? DEFAULT_SAMPLE_FALLOFF\n const occlusion = Math.max(0, Math.min(1, input.occlusion ?? 0))\n const level = falloffGain(falloff, (input.volume ?? 1) * (sound.gain ?? 1), distance) * (1 - 0.45 * occlusion)\n if (isSilent(falloff, level) || level <= 0) return null\n\n const pitch = sound.pitch ?? DEFAULT_SAMPLE_PITCH\n const rate = pitch > 0 ? 1 + (input.random() * 2 - 1) * pitch : 1\n const environment = input.environment ?? 'outdoor'\n const tier = tierFor(sound, input.intensity)\n const close = tier?.close.length ? tier.close : sound.close\n const far = tier?.far?.length ? tier.far : (sound.far ?? [])\n const farMix = far.length > 0 ? farMixAt(sound.crossover ?? DEFAULT_CROSSOVER, distance) : 0\n const gains = crossGains(farMix)\n const layers: PlannedSampleLayer[] = []\n const take = (role: SampleLayerRole, refs: readonly SampleRef[], gain: number, at: number): void => {\n if (refs.length === 0 || gain < LAYER_FLOOR) return\n const key = `${sound.id}/${tier && role !== 'tail' ? `${tier.name}/` : ''}${role}`\n const index = pickTake(refs.length, input.memory?.get(key), input.random)\n input.memory?.set(key, index)\n const ref = refs[index] as SampleRef\n layers.push({ role, url: ref.url, take: index, gain: gain * (ref.gain ?? 1) * level, rate, at })\n }\n take('close', close, gains.close, 0)\n take('far', far, gains.far, 0)\n const tails = sound.tail?.[environment] ?? []\n take('tail', tails, sound.tail?.gain ?? DEFAULT_TAIL_GAIN, sound.tail?.at ?? 0)\n\n const pan = (sound.pan ?? true) && input.position ? panFor(listener, input.position) : undefined\n return {\n kind: 'sample',\n id: sound.id,\n bus: sound.bus,\n level,\n distance,\n ...(pan === undefined ? {} : { pan }),\n cutoff: sampleCutoff(sound.cutoffK ?? DEFAULT_SAMPLE_CUTOFF_K, distance, occlusion),\n rate,\n environment,\n ...(tier ? { tier: tier.name } : {}),\n farMix,\n layers,\n priority: sound.priority ?? input.priority ?? busPriority(sound.bus),\n ...(sound.group ? { group: sound.group } : {}),\n }\n}\n","/**\n * The calibration sound of the measuring harness: a sample sound made by the kit in code (no file, no licence), with every layer the criteria ask\n * for, so the harness can prove the whole file path (bytes → decode → plan → WebAudio) before any real file exists. Each take is a WAV built here:\n * an attack on the first sample (a click and a short noise burst over a low thump that decays), four near takes with their own pitch and noise, a far\n * take (darker, slower attack of the echo), light and heavy tiers and the two tails (a short dense room, a long thin field).\n */\nimport { createRng } from '../rng'\nimport type { SampleSound } from '../sample'\nimport type { SampleLoader } from '../webaudio/sample-store'\n\nexport const CALIBRATION_ID = 'calibration_shot'\nexport const CALIBRATION_RATE = 48000\n\n/** 16-bit PCM mono WAV bytes of the samples (clamped to ±1). */\nexport function encodeWav(samples: Float32Array, sampleRate = CALIBRATION_RATE): ArrayBuffer {\n const bytes = new ArrayBuffer(44 + samples.length * 2)\n const view = new DataView(bytes)\n const text = (at: number, value: string): void => {\n for (let index = 0; index < value.length; index++) view.setUint8(at + index, value.charCodeAt(index))\n }\n text(0, 'RIFF')\n view.setUint32(4, 36 + samples.length * 2, true)\n text(8, 'WAVE')\n text(12, 'fmt ')\n view.setUint32(16, 16, true)\n view.setUint16(20, 1, true)\n view.setUint16(22, 1, true)\n view.setUint32(24, sampleRate, true)\n view.setUint32(28, sampleRate * 2, true)\n view.setUint16(32, 2, true)\n view.setUint16(34, 16, true)\n text(36, 'data')\n view.setUint32(40, samples.length * 2, true)\n for (let index = 0; index < samples.length; index++) {\n const value = Math.max(-1, Math.min(1, samples[index] as number))\n view.setInt16(44 + index * 2, value < 0 ? value * 0x8000 : value * 0x7fff, true)\n }\n return bytes\n}\n\ntype Shot = { readonly seconds: number; readonly thump: number; readonly noise: number; readonly decay: number; readonly brightness: number; readonly gain: number; readonly seed: number; readonly attack?: number }\n\n/** One take: a thump (sine glide) and a noise burst, both decaying, smoothed by a one-pole lowpass (`brightness` 0..1), faded out at the end. */\nexport function shotSamples(shot: Shot, sampleRate = CALIBRATION_RATE): Float32Array {\n const random = createRng(shot.seed)\n const length = Math.round(shot.seconds * sampleRate)\n const samples = new Float32Array(length)\n let low = 0\n let phase = 0\n const attack = Math.max(1, Math.round((shot.attack ?? 0) * sampleRate))\n for (let index = 0; index < length; index++) {\n const time = index / sampleRate\n const envelope = Math.exp(-time / shot.decay) * Math.min(1, (index + 1) / attack)\n phase += (2 * Math.PI * shot.thump * (1 + 0.6 * Math.exp(-time * 30))) / sampleRate\n const noise = random() * 2 - 1\n low += shot.brightness * (noise - low)\n const fade = Math.min(1, (length - index) / (0.01 * sampleRate))\n samples[index] = shot.gain * envelope * fade * (0.55 * Math.sin(phase) + shot.noise * low)\n }\n return samples\n}\n\nconst TAKES: Readonly<Record<string, Shot>> = {\n 'close_1.wav': { seconds: 0.4, thump: 150, noise: 1, decay: 0.06, brightness: 0.9, gain: 0.85, seed: 1 },\n 'close_2.wav': { seconds: 0.4, thump: 160, noise: 1, decay: 0.065, brightness: 0.85, gain: 0.85, seed: 2 },\n 'close_3.wav': { seconds: 0.4, thump: 142, noise: 1, decay: 0.055, brightness: 0.95, gain: 0.85, seed: 3 },\n 'close_4.wav': { seconds: 0.4, thump: 170, noise: 1, decay: 0.07, brightness: 0.8, gain: 0.85, seed: 4 },\n 'far_1.wav': { seconds: 0.9, thump: 90, noise: 0.8, decay: 0.2, brightness: 0.08, gain: 0.7, seed: 5, attack: 0.004 },\n 'far_2.wav': { seconds: 0.9, thump: 95, noise: 0.8, decay: 0.22, brightness: 0.07, gain: 0.7, seed: 6, attack: 0.004 },\n 'light_1.wav': { seconds: 0.25, thump: 220, noise: 0.6, decay: 0.03, brightness: 0.6, gain: 0.35, seed: 7 },\n 'light_2.wav': { seconds: 0.25, thump: 230, noise: 0.6, decay: 0.03, brightness: 0.55, gain: 0.35, seed: 8 },\n 'heavy_1.wav': { seconds: 0.6, thump: 110, noise: 1.2, decay: 0.11, brightness: 0.95, gain: 0.95, seed: 9 },\n 'heavy_2.wav': { seconds: 0.6, thump: 105, noise: 1.2, decay: 0.12, brightness: 0.9, gain: 0.95, seed: 10 },\n 'tail_in.wav': { seconds: 0.5, thump: 0, noise: 1, decay: 0.08, brightness: 0.4, gain: 0.25, seed: 11, attack: 0.01 },\n 'tail_out.wav': { seconds: 2, thump: 0, noise: 1, decay: 0.45, brightness: 0.25, gain: 0.2, seed: 12, attack: 0.02 },\n 'loop_1.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.5, gain: 0.5, seed: 13, attack: 0.01 },\n 'loop_2.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.45, gain: 0.5, seed: 14, attack: 0.01 },\n 'loop_3.wav': { seconds: 0.6, thump: 0, noise: 1, decay: 100, brightness: 0.55, gain: 0.5, seed: 15, attack: 0.01 },\n}\n\nconst PREFIX = 'calibration/'\nconst url = (name: string): string => `${PREFIX}${name}`\n\n/** The calibration sound (weapons bus, every layer, fallback to the game's pistol noise class). */\nexport const CALIBRATION_SOUND: SampleSound = {\n id: CALIBRATION_ID,\n bus: 'weapons',\n close: ['close_1.wav', 'close_2.wav', 'close_3.wav', 'close_4.wav'].map((name) => ({ url: url(name) })),\n far: ['far_1.wav', 'far_2.wav'].map((name) => ({ url: url(name) })),\n tiers: [\n { name: 'light', from: 0, close: ['light_1.wav', 'light_2.wav'].map((name) => ({ url: url(name) })) },\n { name: 'medium', from: 0.34, close: ['close_1.wav', 'close_2.wav', 'close_3.wav', 'close_4.wav'].map((name) => ({ url: url(name) })) },\n { name: 'heavy', from: 0.67, close: ['heavy_1.wav', 'heavy_2.wav'].map((name) => ({ url: url(name) })) },\n ],\n tail: { indoor: [{ url: url('tail_in.wav') }], outdoor: [{ url: url('tail_out.wav') }] },\n pitch: 0.04,\n choke: { voices: 2 },\n fallback: 'sfx_pistol',\n sources: ['sdk: calibration takes synthesized by the harness (measure/calibration.ts), no file, no licence'],\n}\n\nexport const CALIBRATION_LOOP_ID = 'calibration_loop'\n\n/** A steady hiss in three 0.6 s takes, crossed in 0.15 s: the loop the harness checks for seams (no dip, no gap where two takes meet). */\nexport const CALIBRATION_LOOP_SOUND: SampleSound = {\n id: CALIBRATION_LOOP_ID,\n bus: 'ambience',\n close: ['loop_1.wav', 'loop_2.wav', 'loop_3.wav'].map((name) => ({ url: url(name) })),\n loop: { crossfade: 0.15 },\n sources: ['sdk: calibration takes synthesized by the harness (measure/calibration.ts), no file, no licence'],\n}\n\n/** Whether a url is one of the calibration takes. */\nexport const isCalibrationUrl = (url: string): boolean => url.startsWith(PREFIX)\n\n/** Bytes of the calibration takes (made on demand, the same for the same name). Falls through to `next` for any other url. */\nexport function calibrationLoader(next?: SampleLoader): SampleLoader {\n const made = new Map<string, ArrayBuffer>()\n return async (requested) => {\n if (!requested.startsWith(PREFIX)) {\n if (next) return next(requested)\n throw new Error(`not a calibration file: ${requested}`)\n }\n const name = requested.slice(PREFIX.length)\n const shot = TAKES[name]\n if (!shot) throw new Error(`no calibration take ${name}`)\n let bytes = made.get(name)\n if (!bytes) {\n bytes = encodeWav(shotSamples(shot))\n made.set(name, bytes)\n }\n // decodeAudioData detaches what it gets: every load gets its own copy\n return bytes.slice(0)\n }\n}\n","import type { LoopRecipe, SoundBank, SoundRecipe, SoundSet } from './recipe'\nimport type { SampleSound } from './sample'\n\nexport type DeepPartial<TValue> = TValue extends readonly unknown[] ? TValue : TValue extends object ? { readonly [Key in keyof TValue]?: DeepPartial<TValue[Key]> } : TValue\n\n/** Every sound and loop the engine knows, by id. Banks register in order; a later bank replaces an earlier recipe with the same id. */\nexport type SoundRegistry = {\n register(bank: SoundBank): void\n /** Merged into the recipe by id (objects merge, arrays such as `layers` are replaced); an unknown id is ignored. */\n patch(id: string, patch: DeepPartial<SoundRecipe> | DeepPartial<LoopRecipe> | DeepPartial<SampleSound>): void\n remove(id: string): void\n sound(id: string): SoundRecipe | undefined\n loop(id: string): LoopRecipe | undefined\n /** The set an id names (`SoundBank.sets`), if any; a recipe with the same id wins in `play`. */\n set(id: string): SoundSet | undefined\n sample(id: string): SampleSound | undefined\n soundIds(): string[]\n setIds(): string[]\n loopIds(): string[]\n sampleIds(): string[]\n /** Which bank each id came from. */\n bankOf(id: string): string | undefined\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n// keys keep their place, so a patched range is still drawn where it was\nfunction mergeRecords(base: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) continue\n const current = merged[key]\n merged[key] = isPlainObject(current) && isPlainObject(value) ? mergeRecords(current, value) : value\n }\n return merged\n}\n\nexport function createSoundRegistry(banks: readonly SoundBank[] = []): SoundRegistry {\n const sounds = new Map<string, SoundRecipe>()\n const loops = new Map<string, LoopRecipe>()\n const sets = new Map<string, SoundSet>()\n const samples = new Map<string, SampleSound>()\n const owners = new Map<string, string>()\n const registry: SoundRegistry = {\n register(bank) {\n for (const sound of bank.sounds ?? []) {\n sounds.set(sound.id, sound)\n owners.set(sound.id, bank.id)\n }\n for (const loop of bank.loops ?? []) {\n loops.set(loop.id, loop)\n owners.set(loop.id, bank.id)\n }\n for (const set of bank.sets ?? []) {\n if (set.variants.length === 0) throw new Error(`sound set ${set.id} has no variant`)\n sets.set(set.id, set)\n owners.set(set.id, bank.id)\n }\n for (const sample of bank.samples ?? []) {\n samples.set(sample.id, sample)\n owners.set(sample.id, bank.id)\n }\n },\n patch(id, patch) {\n const sound = sounds.get(id)\n if (sound) sounds.set(id, mergeRecords(sound, patch as Record<string, unknown>) as SoundRecipe)\n const loop = loops.get(id)\n if (loop) loops.set(id, mergeRecords(loop, patch as Record<string, unknown>) as LoopRecipe)\n const sample = samples.get(id)\n if (sample) samples.set(id, mergeRecords(sample, patch as Record<string, unknown>) as SampleSound)\n },\n remove(id) {\n sounds.delete(id)\n loops.delete(id)\n sets.delete(id)\n samples.delete(id)\n owners.delete(id)\n },\n sound: (id) => sounds.get(id),\n loop: (id) => loops.get(id),\n set: (id) => sets.get(id),\n sample: (id) => samples.get(id),\n soundIds: () => [...sounds.keys()],\n setIds: () => [...sets.keys()],\n loopIds: () => [...loops.keys()],\n sampleIds: () => [...samples.keys()],\n bankOf: (id) => owners.get(id),\n }\n for (const bank of banks) registry.register(bank)\n return registry\n}\n","[\n {\n \"id\": \"game\",\n \"master\": 0.5,\n \"noise\": {\n \"seconds\": 1.5,\n \"create\": \"lazy\"\n },\n \"sources\": [\n \"jogo:L62077-62081 master 0.5 to the output\",\n \"jogo:L62082-62088 noise 1.5 s made by the first sound that needs it\"\n ]\n },\n {\n \"id\": \"art_scene\",\n \"master\": 0.85,\n \"compressor\": {\n \"threshold\": -12,\n \"ratio\": 5\n },\n \"reverb\": {\n \"seconds\": 2.2,\n \"decay\": 3.4,\n \"wet\": 0.4\n },\n \"noise\": {\n \"seconds\": 2,\n \"create\": \"eager\"\n },\n \"sources\": [\n \"cena:L1308 compressor -12 dB, ratio 5\",\n \"cena:L1309 master 0.85\",\n \"cena:L1310 convolver, impulse 2.2 s of (1 - i/len)^3.4\",\n \"cena:L1311 wet 0.4\",\n \"cena:L1312 noise 2 s made with the chain\"\n ]\n },\n {\n \"id\": \"kit\",\n \"master\": 0.85,\n \"compressor\": {\n \"threshold\": -12,\n \"ratio\": 5\n },\n \"reverb\": {\n \"seconds\": 2.2,\n \"decay\": 3.4,\n \"wet\": 0.4\n },\n \"noise\": {\n \"seconds\": 2,\n \"create\": \"eager\"\n },\n \"sources\": [\n \"sdk: the art scene chain (cena L1308-L1312) with a limiter after the compressor: the page has none, and a blast with its debris and a fire catching reached +7 dBFS\"\n ],\n \"limiter\": {\n \"ceiling\": -1,\n \"knee\": -6\n }\n }\n]\n","import mixProfilesJson from './data/mix-profiles.json'\nimport type { BusId } from './recipe'\n\nexport type BusSetting = { readonly gain?: number; readonly muted?: boolean }\n\n/**\n * A mixing chain. `master` → (compressor) → (limiter) → output; with `reverb`, a wet bus → convolver (an impulse from the engine's seed) → master. `noise` is\n * the shared noise buffer: its length, and whether it is made with the chain (`eager`, the art scene) or by the first sound that needs it (`lazy`,\n * the game). Buses sit under the master and have no node until one is changed.\n */\nexport type MixProfile = {\n readonly id: string\n readonly master: number\n readonly compressor?: { readonly threshold: number; readonly ratio: number; readonly knee?: number; readonly attack?: number; readonly release?: number }\n readonly reverb?: { readonly seconds: number; readonly decay: number; readonly wet: number }\n /**\n * A last stage after the compressor that keeps every peak under `ceiling` dBFS: below `knee` dBFS the sound passes untouched, above it the peak\n * bends smoothly toward the ceiling (a soft clipper, no lookahead and no delay), so a blast with its debris and a fire catching all at once never\n * clips the output. `range` is the loudest input it shapes, as a factor of full scale (default 4, +12 dB); louder is held at the ceiling.\n */\n readonly limiter?: { readonly ceiling: number; readonly knee: number; readonly range?: number }\n readonly noise: { readonly seconds: number; readonly create: 'lazy' | 'eager' }\n readonly buses?: Readonly<Partial<Record<BusId, BusSetting>>>\n readonly sources: readonly string[]\n}\n\n/** The two team chains: `game` (master 0.5, jogo L62080) and `art_scene` (compressor and reverb, cena L1305–1313). */\nexport const MIX_PROFILES: Readonly<Record<string, MixProfile>> = Object.fromEntries(\n (mixProfilesJson as unknown as readonly MixProfile[]).map((profile) => [profile.id, profile]),\n)\n/** Q1: the kit plays through the art scene chain (compressor and reverb) with a limiter at the end (`kit`); `mix: 'art_scene'` is the page as it was, `mix: 'game'` the game's. */\nexport const DEFAULT_MIX = 'kit'\n\n/** A profile by id from `profiles`, or the profile itself. */\nexport function resolveMix(mix: string | MixProfile, profiles: Readonly<Record<string, MixProfile>> = MIX_PROFILES): MixProfile {\n if (typeof mix !== 'string') return mix\n const profile = profiles[mix]\n if (!profile) throw new Error(`game-audio: unknown mix profile \"${mix}\" (known: ${Object.keys(profiles).join(', ')})`)\n return profile\n}\n\n/** The gain a bus plays at: 0 when muted, its gain (default 1) otherwise. */\nexport function busGain(setting: BusSetting | undefined): number {\n if (!setting) return 1\n return setting.muted ? 0 : (setting.gain ?? 1)\n}\n","/** `length` samples of white noise, `random × 2 − 1`, drawn in order (jogo L62086, cena L1312). */\nexport function fillNoise(random: () => number, length: number): Float32Array {\n const samples = new Float32Array(length)\n for (let index = 0; index < length; index++) samples[index] = random() * 2 - 1\n return samples\n}\n\n/**\n * A reverb impulse: per channel, noise times `(1 − i / length)^decay` (cena L1310). `length` is `sampleRate × seconds` as the art scene computes it,\n * which is not always whole (48000 × 2.2 = 105600.00000000001): the loop runs while `i < length`, so one more number is drawn than the buffer holds,\n * exactly like the team code. The power is `exp(decay × log(base))`, which every engine computes the same.\n */\nexport function fillImpulse(random: () => number, options: { readonly channels: number; readonly length: number; readonly decay: number }): Float32Array[] {\n const size = Math.floor(options.length)\n return Array.from({ length: options.channels }, () => {\n const samples = new Float32Array(size)\n for (let index = 0; index < options.length; index++) {\n const value = (random() * 2 - 1) * Math.exp(options.decay * Math.log(1 - index / options.length))\n if (index < size) samples[index] = value\n }\n return samples\n })\n}\n\n/** An AudioBuffer holding the samples (one channel per array). */\nexport function bufferOf(context: AudioContext, channels: readonly Float32Array[], requestedLength: number): AudioBuffer {\n const buffer = context.createBuffer(channels.length, requestedLength, context.sampleRate)\n channels.forEach((samples, channel) => buffer.getChannelData(channel).set(samples))\n return buffer\n}\n","import type { MixProfile } from '../mix'\nimport { bufferOf, fillImpulse } from './noise'\n\nexport type MixChain = { readonly master: GainNode; readonly wet?: GainNode; disconnect(): void }\n\nconst LIMITER_POINTS = 4097\n\n/**\n * The limiter's curve over inputs `-range..range` (full scale 1): untouched up to the knee, then `knee + (ceiling − knee) × tanh((|x| − knee) / (ceiling − knee))`,\n * which leaves the knee with the same slope and never passes the ceiling.\n */\nexport function limiterCurve(ceilingDb: number, kneeDb: number, range: number, points = LIMITER_POINTS): Float32Array<ArrayBuffer> {\n const ceiling = 10 ** (ceilingDb / 20)\n const knee = Math.min(10 ** (kneeDb / 20), ceiling)\n const curve = new Float32Array(new ArrayBuffer(points * 4))\n for (let i = 0; i < points; i++) {\n const x = ((i / (points - 1)) * 2 - 1) * range\n const a = Math.abs(x)\n const y = a <= knee || ceiling === knee ? Math.min(a, ceiling) : knee + (ceiling - knee) * Math.tanh((a - knee) / (ceiling - knee))\n curve[i] = Math.sign(x) * y\n }\n return curve\n}\n\n/**\n * The mixing chain in the team order (cena L1308–1311; jogo L62080): compressor to the output, master into it (or straight to the output), then the\n * convolver with an impulse drawn from `random` and the wet bus into it, back into the master.\n */\nexport function buildChain(context: AudioContext, profile: MixProfile, random: () => number): MixChain {\n // the limiter is the last stage: a gain that brings `range` × full scale into the shaper's -1..1, and a curve that gives the level back, bent above the knee\n let limiter: { readonly input: GainNode; readonly shaper: WaveShaperNode } | undefined\n if (profile.limiter) {\n const range = profile.limiter.range ?? 4\n const input = context.createGain()\n input.gain.value = 1 / range\n const shaper = context.createWaveShaper()\n shaper.curve = limiterCurve(profile.limiter.ceiling, profile.limiter.knee, range)\n input.connect(shaper)\n shaper.connect(context.destination)\n limiter = { input, shaper }\n }\n const output: AudioNode = limiter?.input ?? context.destination\n let compressor: DynamicsCompressorNode | undefined\n if (profile.compressor) {\n compressor = context.createDynamicsCompressor()\n compressor.threshold.value = profile.compressor.threshold\n compressor.ratio.value = profile.compressor.ratio\n if (profile.compressor.knee !== undefined) compressor.knee.value = profile.compressor.knee\n if (profile.compressor.attack !== undefined) compressor.attack.value = profile.compressor.attack\n if (profile.compressor.release !== undefined) compressor.release.value = profile.compressor.release\n compressor.connect(output)\n }\n const master = context.createGain()\n master.gain.value = profile.master\n master.connect(compressor ?? output)\n if (!profile.reverb) {\n return {\n master,\n disconnect: () => {\n master.disconnect()\n compressor?.disconnect()\n limiter?.input.disconnect()\n limiter?.shaper.disconnect()\n },\n }\n }\n const convolver = context.createConvolver()\n const length = context.sampleRate * profile.reverb.seconds\n convolver.buffer = bufferOf(context, fillImpulse(random, { channels: 2, length, decay: profile.reverb.decay }), length)\n const wet = context.createGain()\n wet.gain.value = profile.reverb.wet\n wet.connect(convolver)\n convolver.connect(master)\n return {\n master,\n wet,\n disconnect: () => {\n wet.disconnect()\n convolver.disconnect()\n master.disconnect()\n compressor?.disconnect()\n limiter?.input.disconnect()\n limiter?.shaper.disconnect()\n },\n }\n}\n","type AudioContextConstructor = new () => AudioContext\n\n/** A new context from the page (`AudioContext` or the old `webkitAudioContext`), or `null` in Node and workers. */\nexport function globalContext(): AudioContext | null {\n const scope = globalThis as { AudioContext?: AudioContextConstructor; webkitAudioContext?: AudioContextConstructor }\n const Constructor = scope.AudioContext ?? scope.webkitAudioContext\n return Constructor ? new Constructor() : null\n}\n\n/** Browsers start a context suspended until a click or key; call from one. */\nexport function unlockContext(context: AudioContext): void {\n // an OfflineAudioContext (no `close`) is started by `startRendering`, never resumed\n if (context.state === 'suspended' && typeof context.close === 'function') void context.resume()\n}\n","import type { LoopRecipe } from './recipe'\n\n/** jogo L62112: a loop's nodes exist only once its volume reaches 0.002. */\nexport const LOOP_START_ABOVE = 0.002\n/** jogo L62125–62126: `setTargetAtTime` time constants. */\nexport const LOOP_SMOOTHING = { volume: 0.15, frequency: 0.08 } as const\n\n/** What the realizer does for one `set`: create the nodes first (once), then glide the volume and, for an oscillator, the frequency. */\nexport type LoopAction = { readonly create: boolean; readonly volume: number; readonly frequency?: number }\n\nexport type LoopState = {\n /** `null` while the loop has no nodes and the volume is still below the start threshold. */\n set(state: { readonly volume?: number; readonly frequency?: number }): LoopAction | null\n /** Whether the nodes exist. */\n readonly created: boolean\n /** The nodes were torn down (`stop`): the next audible `set` creates them again. */\n reset(): void\n}\n\n/**\n * The game's `loopSet` as state: nodes on the first volume at or above `startAbove`, then every `set` glides. The volume set last is kept, so a\n * `set` of only the frequency keeps the level. `chain_loop` recipes open with their nodes already made (`open` is true).\n */\nexport function createLoopState(recipe: LoopRecipe, open = false): LoopState {\n const startAbove = recipe.startAbove ?? LOOP_START_ABOVE\n let created = open\n let volume = recipe.volume ?? 0\n return {\n set(state) {\n volume = state.volume ?? volume\n const create = !created\n if (create && !(volume >= startAbove)) return null\n created = true\n const frequency = recipe.source.kind === 'osc' && state.frequency ? state.frequency : undefined\n return { create, volume, ...(frequency === undefined ? {} : { frequency }) }\n },\n get created() {\n return created\n },\n reset() {\n created = false\n },\n }\n}\n","import type { PlannedAutomation, PlannedEnvelopePoint, PlannedFilter } from '../plan'\n\n/** Where a plan is built: the context, the bus it plays into, the reverb send (if the mix has one), the shared noise and the start time. */\nexport type RealizeTarget = {\n readonly context: AudioContext\n readonly output: AudioNode\n readonly wet?: AudioNode\n /** The noise buffer; made on the first call when the mix makes it on demand. */\n readonly noise: () => AudioBuffer\n readonly time: number\n}\n\n/** What `realize` built: every scheduled source (so the voice can be cut short) and `stop`. */\nexport type RealizedVoice = { readonly sources: readonly AudioScheduledSourceNode[]; stop(): void }\n\n/** `.value = value`, or `setValueAtTime(from)` at `time`. */\nexport function assign(param: AudioParam, automation: PlannedAutomation, time: number): void {\n if (automation.value !== undefined) param.value = automation.value\n if (automation.from !== undefined) param.setValueAtTime(automation.from, time)\n}\n\nexport function ramp(param: AudioParam, curve: 'set' | 'linear' | 'exp', value: number, at: number): void {\n if (curve === 'set') param.setValueAtTime(value, at)\n else if (curve === 'exp') param.exponentialRampToValueAtTime(value, at)\n else param.linearRampToValueAtTime(value, at)\n}\n\n/** The ramp of an automation, if it has one. */\nexport function rampTo(param: AudioParam, automation: PlannedAutomation, time: number): void {\n if (automation.to !== undefined && automation.at !== undefined) ramp(param, automation.curve ?? 'linear', automation.to, time + automation.at)\n}\n\nexport function applyEnvelope(param: AudioParam, points: readonly PlannedEnvelopePoint[], time: number): void {\n for (const point of points) ramp(param, point.curve, point.value, time + point.time)\n}\n\n/** A noise source on the shared buffer (`loop` set only when asked, as the art scene's `nsrc` does). */\nexport function noiseSource(target: RealizeTarget, loop: boolean): AudioBufferSourceNode {\n const source = target.context.createBufferSource()\n source.buffer = target.noise()\n if (loop) source.loop = true\n return source\n}\n\n/** The art scene's `bq`: type, frequency, then Q and gain when given. The frequency ramp is left to the caller. */\nexport function filterNode(context: AudioContext, filter: PlannedFilter, time: number): BiquadFilterNode {\n const node = context.createBiquadFilter()\n node.type = filter.type\n assign(node.frequency, filter.frequency, time)\n if (filter.q !== undefined) node.Q.value = filter.q\n if (filter.gain !== undefined) node.gain.value = filter.gain\n return node\n}\n\nexport function gainNode(context: AudioContext, value: number): GainNode {\n const node = context.createGain()\n node.gain.value = value\n return node\n}\n\nexport function voiceOf(sources: readonly AudioScheduledSourceNode[]): RealizedVoice {\n return {\n sources,\n stop() {\n for (const source of sources) {\n try {\n source.stop()\n } catch {\n // already stopped\n }\n }\n },\n }\n}\n","// Loop nodes in the two team orders: the game's `loopSet` (jogo L62109–62127) and the art scene's loops in `initAudio` (cena L1314–1316).\nimport type { Automation, LoopRecipe, Range } from '../recipe'\nimport { filterNode, gainNode, noiseSource } from './nodes'\nimport type { RealizeTarget } from './nodes'\n\nexport type RealizedLoop = {\n readonly gain: GainNode\n /** The node wired to the bus: the panner when the recipe pans, else the gain. */\n readonly out: AudioNode\n readonly panner?: StereoPannerNode\n readonly source: AudioScheduledSourceNode\n readonly frequency?: AudioParam\n /** The first filter's cutoff, for `set({ cutoff })`. */\n readonly cutoff?: AudioParam\n stop(): void\n}\n\n// a panning loop goes gain → panner → bus; the others keep the team wiring (gain → bus)\nfunction outputStage(recipe: LoopRecipe, target: RealizeTarget, gain: GainNode): { out: AudioNode; panner?: StereoPannerNode } {\n if (!recipe.pan) {\n gain.connect(target.output)\n return { out: gain }\n }\n const panner = target.context.createStereoPanner()\n gain.connect(panner)\n panner.connect(target.output)\n return { out: panner, panner }\n}\n\n// loops take fixed numbers: a range or a param in a loop recipe reads as 0\nconst fixed = (range: Range | undefined): number => (typeof range === 'number' ? range : 0)\nconst fixedFrequency = (automation: Automation): number => fixed('set' in automation ? automation.set : automation.from)\n\nfunction sourceOf(recipe: LoopRecipe, target: RealizeTarget): { source: AudioScheduledSourceNode; frequency?: AudioParam } {\n if (recipe.source.kind === 'noise') return { source: noiseSource(target, true) }\n const oscillator = target.context.createOscillator()\n oscillator.type = recipe.source.wave\n if (recipe.source.frequency) oscillator.frequency.value = fixedFrequency(recipe.source.frequency)\n return { source: oscillator, frequency: oscillator.frequency }\n}\n\nfunction stopAll(sources: readonly AudioScheduledSourceNode[]): () => void {\n return () => {\n for (const source of sources) {\n try {\n source.stop()\n } catch {\n // already stopped\n }\n }\n }\n}\n\n/** `loopSet` on first use: gain from 0 and filter wired first, the source and filter set, an optional blade-beat stage, then the source starts. */\nexport function realizeGameLoop(recipe: LoopRecipe, target: RealizeTarget): RealizedLoop {\n const { context } = target\n const gain = context.createGain()\n const filters = (recipe.filters?.bank ?? []).map(() => context.createBiquadFilter())\n gain.gain.value = 0\n const last = filters.reduce<AudioNode | undefined>((previous, filter) => (previous ? previous.connect(filter) : filter), undefined)\n last?.connect(gain)\n const output = outputStage(recipe, target, gain)\n const { source, frequency } = sourceOf(recipe, target)\n recipe.filters?.bank.forEach((spec, index) => {\n const filter = filters[index] as BiquadFilterNode\n filter.type = spec.type\n filter.frequency.value = fixedFrequency(spec.frequency)\n if (spec.q !== undefined) filter.Q.value = fixed(spec.q)\n })\n const sources: AudioScheduledSourceNode[] = [source]\n for (const modulator of recipe.modulators ?? []) {\n const lfo = context.createOscillator()\n const depth = context.createGain()\n const stage = context.createGain()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = fixed(modulator.rate)\n depth.gain.value = fixed(modulator.depth as Range)\n stage.gain.value = modulator.base ?? 0\n lfo.connect(depth)\n depth.connect(stage.gain)\n last?.disconnect()\n last?.connect(stage)\n stage.connect(gain)\n lfo.start()\n sources.push(lfo)\n }\n source.connect(filters[0] ?? gain)\n source.start()\n return { gain, ...output, source, ...(frequency ? { frequency } : {}), ...(filters[0] ? { cutoff: filters[0].frequency } : {}), stop: stopAll(sources) }\n}\n\n/** The art scene's loops: source, filters, gain at its starting volume, a gain LFO, wired, started. */\nexport function realizeChainLoop(recipe: LoopRecipe, target: RealizeTarget, volume: number): RealizedLoop {\n const { context } = target\n const { source, frequency } = sourceOf(recipe, target)\n const filters = (recipe.filters?.bank ?? []).map((spec) =>\n filterNode(context, { type: spec.type, frequency: { value: fixedFrequency(spec.frequency) }, ...(spec.q === undefined ? {} : { q: fixed(spec.q) }) }, target.time),\n )\n const gain = gainNode(context, volume)\n const lfos = (recipe.modulators ?? []).map((modulator) => {\n const lfo = context.createOscillator()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = fixed(modulator.rate)\n const depth = gainNode(context, fixed(modulator.depth as Range))\n lfo.connect(depth)\n depth.connect(gain.gain)\n return lfo\n })\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(gain)\n const output = outputStage(recipe, target, gain)\n source.start()\n for (const lfo of lfos) lfo.start()\n return { gain, ...output, source, ...(frequency ? { frequency } : {}), ...(filters[0] ? { cutoff: filters[0].frequency } : {}), stop: stopAll([source, ...lfos]) }\n}\n","import type { Vec3 } from '@adatechnology/game-contracts'\n\nimport { cutoffDivisor, falloffGain } from '../falloff'\nimport { listenerDistance, panFor } from '../listener'\nimport type { DistanceMode, Listener } from '../listener'\nimport { LOOP_SMOOTHING, createLoopState } from '../loops'\nimport type { BusId, LoopRecipe } from '../recipe'\nimport type { RealizeTarget } from './nodes'\nimport { realizeChainLoop, realizeGameLoop } from './realize-loop'\nimport type { RealizedLoop } from './realize-loop'\n\n/**\n * What one `set` changes. `volume` and `frequency` glide as in the team loops. `position` places the loop: with a recipe `falloff` the level falls\n * with the distance from the listener (and the cutoff with `cutoffK`), with `pan` it goes to the listener's side. `cutoff` glides the first filter\n * (an engine opening up under load, a skid getting brighter).\n */\nexport type LoopSet = { readonly volume?: number; readonly frequency?: number; readonly position?: Vec3; readonly cutoff?: number }\n\n/** A continuous sound: `set` glides the volume and, for an oscillator, the frequency; `stop` tears the nodes down. */\nexport type AudioLoopHandle = {\n set(state: LoopSet): void\n stop(): void\n}\n\nexport type LoopEntry = { rewire(): void; stop(): void; readonly created: boolean }\n\n/** What a loop needs from its engine. */\nexport type LoopHost = {\n ready(): AudioContext | null\n output(bus: BusId): AudioNode\n prepareNoise(): unknown\n noise(): AudioBuffer\n register(loop: LoopEntry): void\n unregister(loop: LoopEntry): void\n /** Where the ears are now, for a loop with a `falloff` or `pan`. */\n listener?(): Listener\n readonly distance?: DistanceMode\n}\n\nconst INERT: AudioLoopHandle = { set() {}, stop() {} }\n\n/** A `game_loop` makes its nodes on the first audible `set`; a `chain_loop` makes them when it opens, at `volume` (default the recipe's). */\nexport function createLoopHandle(recipe: LoopRecipe | undefined, host: LoopHost, volume?: number): AudioLoopHandle {\n if (!recipe) return INERT\n const loopRecipe = recipe\n const isChain = loopRecipe.order === 'chain_loop'\n const opening = volume ?? loopRecipe.volume ?? 0\n const smoothing = loopRecipe.smoothing ?? LOOP_SMOOTHING\n let state = createLoopState(loopRecipe)\n let nodes: RealizedLoop | undefined\n\n const entry: LoopEntry = {\n get created() {\n return nodes !== undefined\n },\n rewire() {\n nodes?.out.disconnect()\n nodes?.out.connect(host.output(loopRecipe.bus))\n },\n stop() {\n nodes?.stop()\n nodes?.out.disconnect()\n nodes = undefined\n state = createLoopState(loopRecipe)\n host.unregister(entry)\n },\n }\n\n const create = (context: AudioContext, startVolume: number): RealizedLoop => {\n if (loopRecipe.source.kind === 'noise') host.prepareNoise()\n const target: RealizeTarget = { context, output: host.output(loopRecipe.bus), noise: host.noise, time: context.currentTime }\n const made = isChain ? realizeChainLoop(loopRecipe, target, startVolume) : realizeGameLoop(loopRecipe, target)\n host.register(entry)\n return made\n }\n\n const open = (): void => {\n const context = host.ready()\n if (!context) return\n nodes = create(context, opening)\n state = createLoopState({ ...loopRecipe, volume: opening }, true)\n }\n if (isChain) open()\n\n let position: Vec3 | undefined\n let cutoff: number | undefined\n const placed = loopRecipe.falloff !== undefined || loopRecipe.pan === true\n return {\n set(next) {\n if (isChain && !nodes) open()\n const context = host.ready()\n if (!context) return\n position = next.position ?? position\n cutoff = next.cutoff ?? cutoff\n const action = state.set(next)\n if (!action) return\n nodes ??= create(context, 0)\n const listener = placed && position ? host.listener?.() : undefined\n const distance = listener && position ? listenerDistance(listener, position, host.distance) : 0\n const level = listener ? falloffGain(loopRecipe.falloff, action.volume, distance) : action.volume\n nodes.gain.gain.setTargetAtTime(level, context.currentTime, smoothing.volume)\n if (action.frequency !== undefined && nodes.frequency) nodes.frequency.setTargetAtTime(action.frequency, context.currentTime, smoothing.frequency)\n if (cutoff !== undefined && nodes.cutoff) nodes.cutoff.setTargetAtTime(cutoff / cutoffDivisor(loopRecipe.falloff, distance), context.currentTime, smoothing.frequency)\n if (listener && position && nodes.panner) nodes.panner.pan.setTargetAtTime(panFor(listener, position), context.currentTime, smoothing.frequency)\n },\n stop: entry.stop,\n }\n}\n","/**\n * A continuous sound played from files (fire, rain, an engine idling): `SampleSound.loop` turns a sample sound into a loop that `engine.loop(id)` plays.\n * The takes are chained without a seam: each one starts `crossfade` seconds before the last one ends, the two crossed with equal-power ramps, and\n * the next take is drawn by the round-robin (never the same twice in a row while there are two or more). A take shorter than two crossfades\n * loops on itself (`AudioBufferSourceNode.loop`). While the files are not decoded the recipe loop of the fallback (or of the same id) plays, and\n * the files take over when they are ready, at the volume the loop has then.\n */\nimport { pickTake } from '../sample'\nimport type { BusId, SampleSound } from '../recipe'\nimport type { AudioLoopHandle, LoopEntry } from './engine-loop'\n\n/** The crossfade between two takes of a loop, in seconds, when `loop: true` gives none. */\nexport const DEFAULT_LOOP_CROSSFADE = 0.25\n/** Takes are scheduled until this far (seconds) past the clock, so a busy main thread (a heavy frame, a late timer) never leaves a gap. */\nconst LOOKAHEAD = 1.5\nconst VOLUME_SMOOTHING = 0.05\n\n/** The crossfade of a looping sample sound, or `undefined` when it does not loop. */\nexport function loopCrossfade(sound: SampleSound): number | undefined {\n if (!sound.loop) return undefined\n return sound.loop === true ? DEFAULT_LOOP_CROSSFADE : Math.max(0, sound.loop.crossfade ?? DEFAULT_LOOP_CROSSFADE)\n}\n\n/** Steps of the equal-power ramps (straight lines between points of the sine and cosine quarter). */\nexport const CROSSFADE_STEPS = 8\n\n/** The gain of an equal-power crossfade at `t` (0..1) for the take coming in; the take going out has the gain at `1 − t`. */\nexport const equalPowerIn = (t: number): number => Math.sin((Math.max(0, Math.min(1, t)) * Math.PI) / 2)\n\n// a quarter sine (in) or cosine (out) drawn as straight ramps, so it runs on any AudioParam (and on the recorder of the tests)\nconst ramp = (param: AudioParam, direction: 'in' | 'out', at: number, seconds: number): void => {\n const value = (t: number): number => (direction === 'in' ? equalPowerIn(t) : equalPowerIn(1 - t))\n param.setValueAtTime(value(0), at)\n for (let step = 1; step <= CROSSFADE_STEPS; step++) param.linearRampToValueAtTime(value(step / CROSSFADE_STEPS), at + (seconds * step) / CROSSFADE_STEPS)\n}\n\n/** What a sample loop needs from its engine. */\nexport type SampleLoopHost = {\n ready(): AudioContext | null\n /** The node sample voices of a bus go to (the limiter of the bus). */\n output(bus: BusId): AudioNode\n buffer(url: string): AudioBuffer | undefined\n isReady(sound: SampleSound): boolean\n /** Loads the files of the sound (resolves when they are decoded or failed). */\n load(sound: SampleSound): Promise<unknown>\n /** The recipe loop that plays while the files are not ready. */\n fallback(volume: number): AudioLoopHandle\n random(): number\n register(loop: LoopEntry): void\n unregister(loop: LoopEntry): void\n /** Whether a bus is muted now. */\n muted(bus: BusId): boolean\n}\n\ntype Segment = { readonly source: AudioBufferSourceNode; readonly gain: GainNode; readonly end: number }\n\n/** Plays a looping sample sound; falls back to the recipe loop while its files load. `volume` is the opening level (default 0, opened by `set`). */\nexport function createSampleLoopHandle(sound: SampleSound, host: SampleLoopHost, volume = 0): AudioLoopHandle {\n const crossfade = loopCrossfade(sound) ?? DEFAULT_LOOP_CROSSFADE\n let level = volume\n let stopped = false\n let fallback: AudioLoopHandle | undefined\n let master: GainNode | undefined\n let segments: Segment[] = []\n let last: number | undefined\n let timer: ReturnType<typeof setTimeout> | undefined\n\n const entry: LoopEntry = {\n get created() {\n return master !== undefined\n },\n rewire() {\n master?.disconnect()\n master?.connect(host.output(sound.bus))\n },\n stop() {\n stopped = true\n if (timer !== undefined) clearTimeout(timer)\n timer = undefined\n for (const segment of segments) {\n try {\n segment.source.stop()\n } catch {\n // already stopped\n }\n segment.source.disconnect()\n segment.gain.disconnect()\n }\n segments = []\n master?.disconnect()\n master = undefined\n fallback?.stop()\n fallback = undefined\n host.unregister(entry)\n },\n }\n\n const nextBuffer = (): AudioBuffer | undefined => {\n const takes = sound.close\n const take = pickTake(takes.length, last, host.random)\n last = take\n const ref = takes[take]\n return ref ? host.buffer(ref.url) : undefined\n }\n\n // schedules one take from `at`; returns when the next one starts\n const schedule = (context: AudioContext, output: AudioNode, at: number, first: boolean): number | undefined => {\n const buffer = nextBuffer()\n if (!buffer) return undefined\n const source = context.createBufferSource()\n source.buffer = buffer\n const gain = context.createGain()\n source.connect(gain)\n gain.connect(output)\n const fade = Math.min(crossfade, buffer.duration / 2)\n if (buffer.duration < 2 * crossfade || sound.close.length === 1) {\n // one take (or a take too short to cross): it loops on itself\n source.loop = true\n if (!first) ramp(gain.gain, 'in', at, Math.max(0.001, fade))\n source.start(at)\n segments.push({ source, gain, end: Number.POSITIVE_INFINITY })\n return undefined\n }\n if (first) gain.gain.setValueAtTime(1, at)\n else ramp(gain.gain, 'in', at, fade)\n const end = at + buffer.duration\n ramp(gain.gain, 'out', end - fade, fade)\n source.start(at)\n source.stop(end)\n segments.push({ source, gain, end })\n source.onended = () => {\n segments = segments.filter((segment) => segment.source !== source)\n source.disconnect()\n gain.disconnect()\n }\n return end - fade\n }\n\n const pump = (context: AudioContext, output: AudioNode, at: number, first: boolean): void => {\n if (stopped) return\n let next = schedule(context, output, at, first)\n // a late timer: catch up from the clock instead of stacking takes in the past\n while (next !== undefined && next < context.currentTime + LOOKAHEAD) next = schedule(context, output, Math.max(next, context.currentTime), false)\n if (next === undefined) return\n const wait = Math.max(0, (next - context.currentTime - LOOKAHEAD / 2) * 1000)\n timer = setTimeout(() => {\n timer = undefined\n pump(context, output, next, false)\n }, wait)\n }\n\n // the files play at the sound's own level (`SampleSound.gain`); the fallback recipe loop has its own\n const fileLevel = (): number => level * (sound.gain ?? 1)\n\n const startFiles = (): boolean => {\n if (stopped || master || !host.isReady(sound)) return master !== undefined\n const context = host.ready()\n if (!context) return false\n master = context.createGain()\n master.gain.setValueAtTime(fileLevel(), context.currentTime)\n master.connect(host.output(sound.bus))\n host.register(entry)\n pump(context, master, context.currentTime, true)\n if (fallback) {\n fallback.set({ volume: 0 })\n const old = fallback\n fallback = undefined\n setTimeout(() => old.stop(), VOLUME_SMOOTHING * 6000)\n }\n return true\n }\n\n const ensure = (): void => {\n if (stopped || master) return\n if (startFiles()) return\n if (!fallback) {\n fallback = host.fallback(level)\n void host\n .load(sound)\n .then(() => {\n if (level > 0 || master) startFiles()\n })\n .catch(() => undefined)\n }\n }\n\n if (volume > 0) ensure()\n\n return {\n set(next) {\n if (stopped) return\n if (next.volume !== undefined) level = host.muted(sound.bus) ? 0 : Math.max(0, next.volume)\n if (level > 0) ensure()\n const context = host.ready()\n if (master && context) master.gain.setTargetAtTime(fileLevel(), context.currentTime, VOLUME_SMOOTHING)\n fallback?.set(next.volume === undefined ? next : { ...next, volume: level })\n },\n stop: entry.stop,\n }\n}\n","import { bufferOf, fillNoise } from './noise'\n\n/** One noise buffer and the stream it is filled from. The samples are drawn before the sound that first needs them draws its own numbers. */\nexport type NoiseStore = { readonly random: () => number; samples?: Float32Array; buffer?: AudioBuffer; reset(): void }\n\nexport function createNoiseStore(random: () => number): NoiseStore {\n const store: NoiseStore = {\n random,\n reset() {\n store.samples = undefined\n store.buffer = undefined\n },\n }\n return store\n}\n\n/** Draws the samples (once): `sampleRate × seconds` of them, as the team code sizes its buffer. */\nexport function prepareNoise(store: NoiseStore, context: AudioContext, seconds: number): Float32Array {\n store.samples ??= fillNoise(store.random, Math.floor(context.sampleRate * seconds))\n return store.samples\n}\n\n/** The AudioBuffer (made on the first call, which is where the team code calls its `noise()`). */\nexport function noiseBuffer(store: NoiseStore, context: AudioContext, seconds: number): AudioBuffer {\n const samples = prepareNoise(store, context, seconds)\n store.buffer ??= bufferOf(context, [samples], context.sampleRate * seconds)\n return store.buffer\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The numbers of the shove a blast gives to a body that moves (a loose item, a piece of furniture, a person): all of them a game value, with a default that reads well in a room,\n * not a physical table. A host reads them once and lends them to the modules that move their own bodies (`ModuleHost.blastShove`).\n */\nexport interface BlastShoveOptions {\n /**\n * The share of the blast energy that reaches a body as motion: the speed at the centre is `sqrt(2 * energy * coupling / mass)`, before the falloff (default 0.02).\n */\n readonly coupling?: number\n /** Fastest a body is thrown, in m/s, at the centre of the blast (default 20). */\n readonly maxSpeed?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised from the horizontal outward direction (default 0.3). */\n readonly lift?: number\n /** Below this speed (m/s) nothing moves: a heavy thing far from a small blast stays where it is (default 0.3). */\n readonly minSpeed?: number\n /** Exponent of the falloff `(1 - distance / radius) ^ power`, the same as the damage of the destruction world (default 2). */\n readonly falloffPower?: number\n}\n\n/** The defaults of `BlastShoveOptions`. */\nexport const DEFAULT_BLAST_SHOVE: Readonly<Required<BlastShoveOptions>> = { coupling: 0.02, maxSpeed: 20, lift: 0.3, minSpeed: 0.3, falloffPower: 2 }\n\n/** A blast as the shove reads it: where, how much energy (J) and how far it reaches (m). `reach` (0..1) is the share that got through what stood in the way. */\nexport interface BlastSource {\n readonly point: Vec3\n readonly energy: number\n readonly radius: number\n readonly reach?: number\n /**\n * Kilograms of TNT equivalent of the charge. With it a body is pushed by the blast wave itself (`blast-impulse`), and the shove of loose items keeps this module's rule; without it the body\n * takes the charge from `energy` by `BlastImpulseOptions.tntPerJoule`.\n */\n readonly tnt?: number\n /** Inside this radius (metres) the blast is lethal: a body there that the blast reaches (not behind cover) goes down, wounded, wherever the wave pushed it. */\n readonly lethalRadius?: number\n}\n\n/** What a blast does to one body: how fast it leaves (m/s), the unit direction it leaves in, and how far from the centre it was. */\nexport interface BlastShove {\n readonly speed: number\n readonly direction: Vec3\n readonly distance: number\n /** The falloff applied, 0..1. */\n readonly falloff: number\n}\n\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 * `min(maxSpeed, sqrt(2 * energy * reach * coupling / mass)) * (1 - distance / radius) ^ 2`. Undefined when the body is outside the radius or the speed is under `minSpeed`.\n * The same rule moves the loose items and furniture of the test room and the people of the characters module, so a game that tunes the options tunes all of them.\n */\nexport function blastShove(blast: BlastSource, target: { readonly position: Vec3; readonly mass: number }, options: BlastShoveOptions = {}): BlastShove | undefined {\n const o = { ...DEFAULT_BLAST_SHOVE, ...options }\n const dx = target.position[0] - blast.point[0]\n const dy = target.position[1] - blast.point[1]\n const dz = target.position[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const falloff = (1 - distance / blast.radius) ** o.falloffPower\n const mass = Math.max(target.mass, 0.05)\n const speed = Math.min(o.maxSpeed, Math.sqrt((2 * blast.energy * (blast.reach ?? 1) * o.coupling) / mass)) * falloff\n if (!(speed >= o.minSpeed)) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const direction: Vec3 = distance > 1e-4 ? [dx / distance, dy / distance + o.lift, dz / distance] : [0, 1, 0]\n const length = Math.hypot(direction[0], direction[1], direction[2])\n return { speed, direction: [direction[0] / length, direction[1] / length, direction[2] / length], distance, falloff }\n}\n","/**\n * The push a blast gives a standing body, from the physics of the blast wave and not from a game coupling: the impulse of the wave per square metre at a distance from a charge of\n * `tnt` kg of TNT equivalent (Kinney and Graham's fit of the side-on impulse, scaled by the cube root of the charge), reflected on the body, over the area the body shows the wave,\n * divided by its mass. A hand grenade at 3 m gives a person a few tenths of a metre per second; what floors that person is the fragments, not the wave. A big charge close throws.\n */\n\n/** The numbers of the body a blast wave pushes. All have a default for a standing adult. */\nexport interface BlastImpulseOptions {\n /** Square metres of the body the wave meets: about 1.75 m tall by 0.4 m wide (default 0.7). */\n readonly bodyArea?: number\n /** How much of the push goes up: the direction is `(away, lift)` normalised (default 0.15: the wave runs along the ground). */\n readonly lift?: number\n /** Below this speed (m/s) the body does not move (default 0.3). */\n readonly minSpeed?: number\n /**\n * Kilograms of TNT per joule of the blast `energy`, for a blast that does not say its charge (`BlastSource.tnt`). Default 0.24 / 200000: the arsenal's energy scale, where the M67 (180 g\n * of Composition B, 0.24 kg of TNT) is 200 kJ. It is a game equivalence for blasts without a charge, not a physical constant.\n */\n readonly tntPerJoule?: number\n}\n\nexport const DEFAULT_BLAST_IMPULSE: Readonly<Required<BlastImpulseOptions>> = { bodyArea: 0.7, lift: 0.15, minSpeed: 0.3, tntPerJoule: 0.24 / 200000 }\n\n/** Closest distance (m) the fit is read at: inside it the charge is in contact and the body is torn apart anyway. */\nconst NEAREST = 0.3\n\n/**\n * Side-on (incident) specific impulse of the wave, in Pa·s, at `distance` metres from `tnt` kg of TNT in free air: Kinney and Graham, \"Explosive Shocks in Air\" (1985),\n * `I/W^(1/3) = 0.067 sqrt(1 + (Z/0.23)^4) / (Z^2 (1 + (Z/1.55)^3)^(1/3))` bar·ms per kg^(1/3), with the scaled distance `Z = R / W^(1/3)`.\n */\nexport function sideOnImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const w3 = Math.cbrt(tnt)\n const z = Math.max(distance, NEAREST) / w3\n const scaled = (0.067 * Math.sqrt(1 + (z / 0.23) ** 4)) / (z * z * Math.cbrt(1 + (z / 1.55) ** 3))\n return scaled * w3 * 100 // bar·ms to Pa·s\n}\n\n/**\n * The impulse per square metre a body facing the wave takes, Pa·s: the side-on impulse reflected. The reflection doubles a weak wave and grows up to about six times close to the charge,\n * where the wave is strong (the ratio of reflected to side-on impulse of the Kingery-Bulmash charts, fitted as `2 + 4 / (1 + Z^2)`).\n */\nexport function bodyImpulse(tnt: number, distance: number): number {\n if (!(tnt > 0)) return 0\n const z = Math.max(distance, NEAREST) / Math.cbrt(tnt)\n return sideOnImpulse(tnt, distance) * (2 + 4 / (1 + z * z))\n}\n\n/** The speed (m/s) a blast wave gives a free body of `mass` kg at `distance` metres from `tnt` kg of TNT, `reach` (0..1) of it getting through what stands in the way. */\nexport function blastBodySpeed(tnt: number, distance: number, mass: number, reach = 1, options: BlastImpulseOptions = {}): number {\n const area = options.bodyArea ?? DEFAULT_BLAST_IMPULSE.bodyArea\n return (bodyImpulse(tnt, distance) * area * Math.max(0, reach)) / Math.max(mass, 1)\n}\n","import { blastBodySpeed, DEFAULT_BLAST_IMPULSE } from './blast-impulse'\nimport type { BlastImpulseOptions } from './blast-impulse'\nimport type { BlastShoveOptions, BlastSource } from './blast-shove'\nimport type { Vec3 } from './destruction'\n\n/** From this speed (m/s) a blast takes a standing body off its feet. Below it the body is only pushed. */\nexport const KNOCK_DOWN_SPEED = 2.5\n/** The angle of a body lying where it fell (the same tilt a dead body takes). */\nexport const KNOCKED_DOWN_ANGLE = 1.35\n/** Seconds the body lies after it lands: this plus the landing speed times `STAND_UP_PER_SPEED`. */\nconst LIE_SECONDS = 1.6\n/** Seconds a body floored by its wounds (inside the lethal radius) lies before it gets up, when it is not dead. */\nconst WOUNDED_LIE_SECONDS = 6\n/** The share of the blast that has to get through for its fragments to reach a body: behind cover that stops half of it the fragments stop too. */\nexport const FRAGMENT_COVER = 0.5\n/** Seconds a body is stunned at the edge of the lethal radius (the ringing ears, the dizziness); it falls with the square of the way to the edge of the blast. */\nconst STUN_SECONDS = 4\nconst STAND_UP_PER_SPEED = 0.25\nconst FALL_SECONDS = 0.25\nconst RISE_SECONDS = 0.6\n/** m/s squared that slows a body sliding on the ground. */\nconst GROUND_FRICTION = 7\nconst GRAVITY = 9.81\n/** Height of the chest above the feet: where the blast takes the body. */\nexport const KNOCK_CHEST = 1.1\nconst CHEST = KNOCK_CHEST\n\n/** What a blast is doing to one body: its velocity (m/s), whether it is in the air, and how far down it is (0 on its feet, 1 lying). */\nexport interface Knock {\n velocity: [number, number, number]\n airborne: boolean\n /** 0..1 */\n lying: number\n /** Seconds left to lie on the ground after it stopped. */\n lieLeft: number\n /** Knocked off its feet by this blast. */\n down: boolean\n /** Floored by its wounds: inside the lethal radius and not behind cover. It lies longer and falls where it stood. */\n wounded?: boolean\n /** Seconds of stun the blast gave the body: dizziness and ringing ears. */\n stunSeconds?: number\n /** The horizontal unit direction away from the blast, even when the push is too weak to move the body: the way it falls. */\n away?: Vec3\n}\n\n/** The mass of a body in kg from its height (m) and its build (1 = average): 70 kg at 1.75 m. */\nexport const bodyMass = (height: number, build = 1): number => 70 * (height / 1.75) ** 2 * build\n\n/**\n * What a blast does to a body standing at `feet`, of `mass` kg. Undefined when the blast does not reach it or does nothing to it.\n *\n * The body is pushed by the blast wave (`blastBodySpeed`, from the charge `blast.tnt`, or from `energy` by `tntPerJoule`), taken at the chest and cut by `reach`, the share that got through\n * cover. It is floored when that push is `KNOCK_DOWN_SPEED` or more, or when it stands inside `lethalRadius` with the blast reaching it (the fragments and the overpressure fell it where it\n * stands). It is stunned for a while inside the radius. `options` are the shove numbers of the host's loose items; only their `minSpeed` applies to a body.\n */\nexport function knockOf(blast: BlastSource, feet: Vec3, mass: number, options?: BlastShoveOptions, impulse: BlastImpulseOptions = {}): Knock | undefined {\n const o = { ...DEFAULT_BLAST_IMPULSE, ...impulse }\n const chest: Vec3 = [feet[0], feet[1] + CHEST, feet[2]]\n const dx = chest[0] - blast.point[0]\n const dy = chest[1] - blast.point[1]\n const dz = chest[2] - blast.point[2]\n const distance = Math.hypot(dx, dy, dz)\n if (!(blast.radius > 0) || distance > blast.radius) return undefined\n const reach = Math.max(0, Math.min(1, blast.reach ?? 1))\n const tnt = blast.tnt ?? blast.energy * o.tntPerJoule\n let speed = blastBodySpeed(tnt, distance, mass, reach, o)\n const minSpeed = impulse.minSpeed ?? options?.minSpeed ?? o.minSpeed\n if (speed < minSpeed) speed = 0\n const struck = reach >= FRAGMENT_COVER\n const wounded = struck && blast.lethalRadius !== undefined && distance <= blast.lethalRadius\n const edge = 1 - distance / blast.radius\n const stunSeconds = struck ? STUN_SECONDS * edge * edge * reach : 0\n if (speed === 0 && !wounded && stunSeconds < 0.25) return undefined\n // straight above or below the centre there is no \"away\": the push goes up\n const horizontal = Math.hypot(dx, dz)\n const away: Vec3 = horizontal > 1e-4 ? [dx / horizontal, o.lift, dz / horizontal] : [0, 1, 0]\n const length = Math.hypot(away[0], away[1], away[2])\n const velocity: [number, number, number] = [(away[0] / length) * speed, (away[1] / length) * speed, (away[2] / length) * speed]\n return {\n velocity,\n airborne: velocity[1] > 0.5,\n lying: 0,\n lieLeft: wounded ? WOUNDED_LIE_SECONDS : 0,\n away: horizontal > 1e-4 ? [dx / horizontal, 0, dz / horizontal] : [0, 0, 0],\n down: speed >= KNOCK_DOWN_SPEED || wounded,\n ...(wounded ? { wounded } : {}),\n ...(stunSeconds >= 0.25 ? { stunSeconds } : {}),\n }\n}\n\n/**\n * Moves a body one step: it slides on the ground and slows, falls when it was knocked down, lies a while and gets up (a dead body stays down). Moves `position` in place; returns true when the\n * body is on its feet and still, and the knock can be dropped.\n */\nexport function stepKnock(knock: Knock, position: { x: number; y: number; z: number }, dt: number, groundAt: (x: number, z: number) => number, alive: boolean): boolean {\n const v = knock.velocity\n position.x += v[0] * dt\n position.z += v[2] * dt\n const ground = groundAt(position.x, position.z)\n if (knock.airborne || position.y > ground + 1e-4) {\n v[1] -= GRAVITY * dt\n position.y += v[1] * dt\n if (position.y <= ground) {\n position.y = ground\n v[1] = 0\n knock.airborne = false\n }\n } else position.y = ground\n const horizontal = Math.hypot(v[0], v[2])\n if (!knock.airborne && horizontal > 0) {\n const slowed = Math.max(0, horizontal - GROUND_FRICTION * dt)\n v[0] *= slowed / horizontal\n v[2] *= slowed / horizontal\n }\n const moving = horizontal > 0.05 || knock.airborne\n if (knock.down) {\n // a body floored where it stands (its wounds, not the push) still takes the time of a fall to reach the ground\n if (moving || knock.lying < 1) knock.lying = Math.min(1, knock.lying + dt / FALL_SECONDS)\n else if (alive) {\n knock.lieLeft = knock.lieLeft > 0 ? knock.lieLeft : LIE_SECONDS + Math.hypot(v[0], v[2]) * STAND_UP_PER_SPEED\n knock.lieLeft -= dt\n if (knock.lieLeft <= 0) knock.down = false\n }\n } else if (knock.lying > 0) knock.lying = Math.max(0, knock.lying - dt / RISE_SECONDS)\n return !moving && !knock.down && knock.lying === 0\n}\n","export interface CostOptions {\n /** Reads of `state()` and of `describe()` to time. Default 10 000. */\n reads?: number\n /** Ceiling, in milliseconds, for all the reads of one method. Default 50 (5 microseconds per read). */\n ceilingMs?: number\n /** Ceiling of heap growth, in bytes, over all the reads of one method (only where `process.memoryUsage` exists). Default 1 MiB. */\n allocationBytes?: number\n}\n\nconst DEFAULT_COST_READS = 10_000\nconst DEFAULT_COST_CEILING_MS = 50\nconst DEFAULT_COST_ALLOCATION_BYTES = 1024 * 1024\n\nconst heapUsedBytes = (): number | undefined => {\n const nodeProcess = (globalThis as { process?: { memoryUsage?: () => { heapUsed: number } } }).process\n return nodeProcess?.memoryUsage?.().heapUsed\n}\n\ntype CheckReadCostParams = { readonly name: string; readonly read: () => unknown; readonly options: CostOptions; readonly problems: string[] }\n\nexport const checkReadCost = ({ name, read, options, problems }: CheckReadCostParams): void => {\n const reads = options.reads ?? DEFAULT_COST_READS\n const ceilingMs = options.ceilingMs ?? DEFAULT_COST_CEILING_MS\n const allocationBytes = options.allocationBytes ?? DEFAULT_COST_ALLOCATION_BYTES\n if (read() !== read()) problems.push(`${name}() returns a new object on each read: cache it between changes (cost contract)`)\n // a first pass lets the engine compile and optimise the loop: that code and its feedback are heap too, and would read as the method allocating\n for (let i = 0; i < reads; i++) read()\n const heapBefore = heapUsedBytes()\n const started = performance.now()\n for (let i = 0; i < reads; i++) read()\n const elapsedMs = performance.now() - started\n const heapAfter = heapUsedBytes()\n if (elapsedMs > ceilingMs) problems.push(`${name}() took ${elapsedMs.toFixed(1)} ms for ${reads} reads, over the ${ceilingMs} ms ceiling (cost contract)`)\n if (heapBefore !== undefined && heapAfter !== undefined && heapAfter - heapBefore > allocationBytes)\n problems.push(`${name}() grew the heap by ${heapAfter - heapBefore} bytes over ${reads} reads, over the ${allocationBytes} byte ceiling (cost contract)`)\n}\n","import { checkReadCost } from './impact-cost'\nimport type { CostOptions } from './impact-cost'\nimport type { DamageType, DestructibleSpec, DestructionEvent, Hit, JointSpec, ObjectState, ToolKind, Vec3 } from './destruction'\n\n/**\n * What a game module implements for an object whose behaviour it owns (a vehicle with its own panel deformation, a creature, a machine). The\n * world (`DestructionWorld.register`) hosts it next to its own objects: raycast, shoot, explode, hit, disassemble, extinguish, update, state,\n * reset and `on` all route to it.\n *\n * Space: the impl receives hits in WORLD space and returns events in WORLD space (it owns its transform; the transform given to `register` or\n * `setTransform` is only used by the world for raycasts and blast range). Every event must carry `object === id` and name parts listed by\n * `describe()`.\n */\n/** World-space ray for `DestructibleImpl.surfaceRay`. */\nexport interface SurfaceRay {\n readonly origin: Vec3\n readonly direction: Vec3\n readonly maxDistance: number\n ignored?(part: string): boolean\n}\n\nexport interface SurfaceRayHit {\n readonly part: string\n readonly point: Vec3\n readonly normal: Vec3\n readonly distance: number\n /** Thickness the ray crosses in this part, metres. */\n readonly pathLen: number\n}\n\nexport interface DestructibleImpl {\n readonly id: string\n readonly name?: string\n /**\n * Parts, joints and structure in the impl's local space, for raycast, inspector and log.\n * COST CONTRACT (D8): called per frame by the renderer, so it is O(1), allocation-free and cached between changes: the same object comes\n * back until a hit, tool, fire or pose change alters it. `checkDestructible(impl, { cost: true })` measures it.\n */\n describe(): DestructibleSpec\n /** Apply one hit (see `IMPACT_CONTRACT` for the fields per type) and return the events it caused. */\n hit(hit: Hit): DestructionEvent[]\n /**\n * The real surface a ray meets, for an impl whose drawn shape is not its boxes (a car body): the boxes of `describe()` only say where to look, and a shot that crosses\n * them without touching the drawn surface goes on. `ignored` answers for the parts the round already went through. Null when the ray meets nothing.\n */\n surfaceRay?(ray: SurfaceRay): SurfaceRayHit | null\n /** Advance fire, melting, collapse and other timed behaviour. */\n update?(dt: number): DestructionEvent[]\n /**\n * COST CONTRACT (D8): the host reads it per part per frame, so it is O(1), allocation-free and cached between changes (see `describe()`).\n * The cached object is shared with every reader: treat it as read-only, copy before changing it.\n */\n state(): Readonly<ObjectState>\n reset?(): void\n /** The world took the object out (`DestructionWorld.remove`): the impl lets go of what it joined (shared queues, listeners). */\n dispose?(): void\n /** Same contract as `DestructionWorld.disassemble`: progress 0..1, or -1 when the tool cannot undo the joint. */\n disassemble?(jointId: string, tool: ToolKind, dt: number): number\n extinguish?(partId?: string): void\n /** Optional: an animation moved a part; `position` / `rotation` (Euler XYZ, radians) are object-local. Keep raycast and hit shapes in sync. */\n setPartPose?(partId: string, position: Vec3, rotation?: Vec3): void\n /** Plain JSON of the impl's own state, stored in `DestructionSnapshot.impls`. */\n serialize?(): unknown\n load?(data: unknown): void\n}\n\n/** The fields a weapon or hazard must put in a `Hit`, per damage type. THE impact contract. */\nexport interface ImpactContract {\n required: string[]\n optional: string[]\n note: string\n}\n\nexport const IMPACT_CONTRACT: Record<DamageType, ImpactContract> = {\n ballistic: { required: ['type', 'point', 'direction', 'energy', 'caliber'], optional: ['space', 'source'], note: 'bullets and pellets: joules and diameter in millimetres' },\n blunt: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'contact radius in metres (default 3 cm)' },\n slash: { required: ['type', 'point', 'energy'], optional: ['direction', 'radius', 'space', 'source'], note: 'axes, knives, machetes' },\n explosive: { required: ['type', 'point', 'energy', 'radius'], optional: ['lethalRadius', 'space', 'source'], note: 'point is the centre of the blast, radius the range in metres' },\n fire: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'flame temperature in °C; duration in seconds (call every frame with `dt`)' },\n heat: { required: ['type', 'point', 'temperature', 'radius'], optional: ['duration', 'space', 'source'], note: 'heat without flame (cutting torch, hot plate)' },\n}\n\n/** Problems with a hit according to the impact contract (empty when it is valid). */\nexport const checkHit = (hit: Hit): string[] => {\n const c = IMPACT_CONTRACT[hit.type]\n if (!c) return [`unknown damage type \"${String(hit.type)}\"`]\n const out: string[] = []\n for (const f of c.required) {\n const v = (hit as unknown as Record<string, unknown>)[f]\n if (v === undefined || (Array.isArray(v) ? v.some((n) => !Number.isFinite(n)) : typeof v === 'number' && !Number.isFinite(v))) out.push(`${hit.type} hit needs \"${f}\"`)\n }\n return out\n}\n\nexport interface CheckOptions {\n /**\n * Ids of every material the impl may use (the contracts package does not know the materials of your world: pass the ids of\n * `world.materials`, or the built-in plus your own). When omitted, the material check is skipped.\n */\n materials?: Iterable<string>\n /** Opt-in cost measurement (D8): `true` for the defaults, or the limits to use. */\n cost?: boolean | CostOptions\n}\n\nconst finiteJson = (v: unknown, path: string, out: string[]) => {\n if (typeof v === 'number') {\n if (!Number.isFinite(v)) out.push(`${path} is not a finite number`)\n } else if (Array.isArray(v)) v.forEach((x, i) => finiteJson(x, `${path}[${i}]`, out))\n else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) finiteJson(x, `${path}.${k}`, out)\n else if (typeof v === 'function' || typeof v === 'symbol' || typeof v === 'bigint') out.push(`${path} is not JSON`)\n}\n\n/**\n * Contract checker for the test room (it needs no world): `describe()` is valid, a 500 J ballistic hit at a part centre returns well-formed events of this impl, `state()`\n * matches `describe()`, hit points never go negative, `update(0.016)` returns an array and every event is JSON-serializable. It hits the impl\n * (and calls `reset()` afterwards when there is one). With `options.cost` it also times `state()` and `describe()` (the cost contract of D8).\n */\nexport const checkDestructible = (impl: DestructibleImpl, options: CheckOptions = {}): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const known = options.materials ? new Set(options.materials) : null\n let spec: DestructibleSpec | undefined\n try {\n spec = impl.describe()\n } catch (e) {\n return { ok: false, problems: [`describe() threw: ${String(e)}`] }\n }\n if (!spec || !Array.isArray(spec.parts) || spec.parts.length === 0) return { ok: false, problems: ['describe() must return at least one part'] }\n const ids = new Set<string>()\n for (const p of spec.parts) {\n if (ids.has(p.id)) problems.push(`duplicate part id \"${p.id}\"`)\n ids.add(p.id)\n if (known && !known.has(p.material)) problems.push(`part \"${p.id}\" has unknown material \"${p.material}\"`)\n if (!p.shape || !['box', 'cylinder', 'sphere'].includes(p.shape.kind)) problems.push(`part \"${p.id}\" has no valid shape`)\n if (!Array.isArray(p.position) || p.position.length !== 3) problems.push(`part \"${p.id}\" has no position`)\n }\n const jointIds = new Set<string>()\n for (const j of (spec.joints ?? []) as JointSpec[]) {\n if (!ids.has(j.a) || !ids.has(j.b)) problems.push(`joint \"${j.id ?? `${j.a}~${j.b}`}\" references an unknown part`)\n const jid = j.id ?? `${j.a}~${j.b}`\n if (jointIds.has(jid)) problems.push(`duplicate joint id \"${jid}\"`)\n jointIds.add(jid)\n }\n const checkState = (label: string) => {\n let st: ObjectState\n try {\n st = impl.state()\n } catch (e) {\n problems.push(`state() threw ${label}: ${String(e)}`)\n return\n }\n const sids = st.parts.map((p) => p.id).sort().join(',')\n if (sids !== [...ids].sort().join(',')) problems.push(`state() part ids do not match describe() ${label}`)\n for (const p of st.parts) if (!(p.hp >= 0)) problems.push(`part \"${p.id}\" has negative or invalid hp ${label}`)\n }\n const checkEvents = (events: unknown, label: string) => {\n if (!Array.isArray(events)) {\n problems.push(`${label} must return an array`)\n return\n }\n const evs = events as DestructionEvent[]\n evs.forEach((e, i) => {\n if (e.object !== impl.id) problems.push(`${label} event ${i} (${e.type}) has object \"${String(e.object)}\", expected \"${impl.id}\"`)\n const part = (e as { part?: string }).part\n if (part !== undefined && !ids.has(part)) problems.push(`${label} event ${i} (${e.type}) names unknown part \"${part}\"`)\n })\n const bad: string[] = []\n finiteJson(evs, 'events', bad)\n problems.push(...bad.map((b) => `${label}: ${b}`))\n try {\n const s = JSON.stringify(evs)\n if (JSON.stringify(JSON.parse(s)) !== s) problems.push(`${label} events do not survive a JSON round trip`)\n } catch (e) {\n problems.push(`${label} events are not JSON-serializable: ${String(e)}`)\n }\n }\n checkState('before the hit')\n const target = spec.parts[0]\n try {\n const hit: Hit = { type: 'ballistic', point: [target.position[0], target.position[1], target.position[2]], direction: [0, 0, -1], energy: 500, caliber: 9 }\n checkEvents(impl.hit(hit), 'hit()')\n } catch (e) {\n problems.push(`hit() threw: ${String(e)}`)\n }\n checkState('after the hit')\n if (impl.update) {\n try {\n checkEvents(impl.update(0.016), 'update()')\n } catch (e) {\n problems.push(`update() threw: ${String(e)}`)\n }\n checkState('after update')\n }\n try {\n impl.reset?.()\n } catch (e) {\n problems.push(`reset() threw: ${String(e)}`)\n }\n if (options.cost) {\n const cost = options.cost === true ? {} : options.cost\n try {\n checkReadCost({ name: 'state', read: () => impl.state(), options: cost, problems })\n checkReadCost({ name: 'describe', read: () => impl.describe(), options: cost, problems })\n } catch (e) {\n problems.push(`cost measurement threw: ${String(e)}`)\n }\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The slots of a body an item can cover (the item slot vocabulary: game-items imports it from here). */\nexport type BodySlot = 'head' | 'eyes' | 'torso' | 'arms' | 'hands' | 'legs' | 'feet' | 'over'\n\n/** The 11 segments of the detailed body model (the Arsenal ids). */\nexport type SegmentKind = 'head' | 'jaw' | 'neck' | 'torso' | 'pelvis' | 'upperArm' | 'forearm' | 'hand' | 'thigh' | 'shin' | 'foot'\n\n/** The 6 regions of the crowd model (the game regions 0..5). */\nexport type BodyRegion = 'head' | 'torso' | 'armL' | 'armR' | 'legL' | 'legR'\n\n/** Bits of the `missing` mask of a body. The instanced body shader reads them, so the values are part of the contract. */\nexport const MISSING_BITS = {\n head: 1,\n armL: 2,\n armR: 4,\n legL: 8,\n legR: 16,\n armLBroken: 32,\n armRBroken: 64,\n legLBroken: 128,\n legRBroken: 256,\n jaw: 512,\n} as const\n","import type { DestructibleSpec, PartSpec } from './destruction'\n\nexport interface CheckSpecOptions {\n /** Known material ids. When given, every part's material must be one of them. */\n materials?: Iterable<string>\n}\n\nexport interface SpecReport {\n /** False when there is at least one problem (warnings do not count). */\n ok: boolean\n problems: string[]\n /** Things that are legal but probably wrong, e.g. structural parts that cannot reach an anchored part. */\n warnings: string[]\n}\n\nconst STRUCTURE_ROLES = ['foundation', 'column', 'beam', 'slab', 'wall', 'partition', 'roof', 'stair', 'none']\nconst BEARS = [true, false, 'a_on_b', 'b_on_a']\n\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\nconst positive = (n: unknown): boolean => finite(n) && n > 0\nconst vec3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every(finite)\nconst nonNegative = (n: unknown): boolean => n === undefined || (finite(n) && n >= 0)\n\nconst FACES = ['both', '+', '-']\nconst BONDS = ['running', 'stack']\n\n/** Layers, reinforcement, units and breach: known materials, finite positive sizes. */\nconst checkStagedFields = (p: PartSpec | undefined, label: string, materials: Set<string> | null, problems: string[]): void => {\n const known = (m: unknown, what: string): void => {\n if (materials && !materials.has(m as string)) problems.push(`${label} ${what} has unknown material \"${String(m)}\"`)\n }\n ;(p?.layers ?? []).forEach((l, i) => {\n known(l?.material, `layer ${i}`)\n if (!positive(l?.thickness)) problems.push(`${label} layer ${i} thickness must be finite and positive`)\n if (!FACES.includes(l?.faces)) problems.push(`${label} layer ${i} has an invalid faces \"${String(l?.faces)}\"`)\n })\n const r = p?.reinforcement\n if (r) {\n known(r.material, 'reinforcement')\n if (!positive(r.spacing) || !positive(r.diameter)) problems.push(`${label} reinforcement spacing and diameter must be finite and positive`)\n if (r.residualCapacity !== undefined && !(finite(r.residualCapacity) && r.residualCapacity >= 0 && r.residualCapacity <= 1)) problems.push(`${label} reinforcement residualCapacity must be between 0 and 1`)\n }\n const u = p?.units\n if (u) {\n known(u.mortar, 'units mortar')\n if (!vec3(u.size) || !u.size.every(positive)) problems.push(`${label} units size must be three finite positive numbers`)\n if (!BONDS.includes(u.bond)) problems.push(`${label} units has an invalid bond \"${String(u.bond)}\"`)\n }\n if (p?.breach && p.breach.area !== undefined && !positive(p.breach.area)) problems.push(`${label} breach area must be finite and positive`)\n}\n\n/**\n * Static checks on a `DestructibleSpec` (no world needed), for items that give a `spec` instead of an `impl`: unique part ids, known materials\n * (when `options.materials` is given), joints that reference existing, different parts, finite positive sizes, non-negative mass / hp / capacity,\n * valid structure roles and `bears` directions. A structural part with no path of joints to an anchored part is a warning, not a problem: it\n * is allowed, it just falls.\n */\nexport const checkSpec = (spec: DestructibleSpec, options: CheckSpecOptions = {}): SpecReport => {\n const problems: string[] = []\n const warnings: string[] = []\n const materials = options.materials ? new Set(options.materials) : null\n const parts = Array.isArray(spec?.parts) ? spec.parts : []\n if (!Array.isArray(spec?.parts) || parts.length === 0) problems.push('the spec needs at least one part')\n const ids = new Set<string>()\n for (const p of parts) {\n const id = String(p?.id ?? '')\n const label = `part \"${id}\"`\n if (id === '') problems.push('a part has no id')\n else if (ids.has(id)) problems.push(`duplicate part id \"${id}\"`)\n ids.add(id)\n if (materials && !materials.has(p?.material)) problems.push(`${label} has unknown material \"${String(p?.material)}\"`)\n else if (typeof p?.material !== 'string' || p.material === '') problems.push(`${label} needs a material`)\n const s = p?.shape\n if (s?.kind === 'box') {\n if (!Array.isArray(s.size) || s.size.length !== 3 || !s.size.every(positive)) problems.push(`${label} box size must be three finite positive numbers`)\n } else if (s?.kind === 'cylinder') {\n if (!positive(s.radius) || !positive(s.height)) problems.push(`${label} cylinder radius and height must be finite and positive`)\n } else if (s?.kind === 'sphere') {\n if (!positive(s.radius)) problems.push(`${label} sphere radius must be finite and positive`)\n } else problems.push(`${label} has an unknown shape`)\n if (!vec3(p?.position)) problems.push(`${label} needs a finite position [x, y, z]`)\n if (p?.rotation !== undefined && !vec3(p.rotation)) problems.push(`${label} has an invalid rotation`)\n for (const f of ['mass', 'hp', 'thickness'] as const) if (!nonNegative(p?.[f])) problems.push(`${label} ${f} must be a finite number >= 0`)\n if (p?.fill !== undefined && !(finite(p.fill) && p.fill >= 0 && p.fill <= 1)) problems.push(`${label} fill must be between 0 and 1`)\n if (p?.structure) {\n if (!STRUCTURE_ROLES.includes(p.structure.role)) problems.push(`${label} has an invalid structure role \"${String(p.structure.role)}\"`)\n if (!nonNegative(p.structure.capacity)) problems.push(`${label} structure capacity must be a finite number >= 0`)\n }\n if (p?.contains && !nonNegative(p.contains.liters)) problems.push(`${label} contains.liters must be a finite number >= 0`)\n checkStagedFields(p, label, materials, problems)\n }\n\n const jointIds = new Set<string>()\n const edges: Array<[string, string]> = []\n for (const j of spec?.joints ?? []) {\n const id = j.id ?? `${j.a}~${j.b}`\n const label = `joint \"${id}\"`\n if (jointIds.has(id)) problems.push(`duplicate joint id \"${id}\"`)\n jointIds.add(id)\n if (!ids.has(j.a)) problems.push(`${label} references unknown part \"${String(j.a)}\"`)\n if (!ids.has(j.b)) problems.push(`${label} references unknown part \"${String(j.b)}\"`)\n if (j.a === j.b) problems.push(`${label} joins part \"${String(j.a)}\" to itself`)\n if (j.bears !== undefined && !BEARS.includes(j.bears)) problems.push(`${label} has an invalid bears \"${String(j.bears)}\"`)\n if (!nonNegative(j.strength)) problems.push(`${label} strength must be a finite number >= 0`)\n if (!nonNegative(j.seconds)) problems.push(`${label} seconds must be a finite number >= 0`)\n if (j.bears !== false && ids.has(j.a) && ids.has(j.b) && j.a !== j.b) edges.push([j.a, j.b])\n }\n\n // structural parts must reach an anchored part over the joints (only when the spec lists its joints: otherwise they are inferred later)\n const structural = parts.filter((p) => p?.structure && p.structure.role !== 'none')\n if (structural.length && spec.joints) {\n const anchored = parts.filter((p) => p.anchored || p.structure?.role === 'foundation').map((p) => p.id)\n const adj = new Map<string, string[]>()\n for (const [a, b] of edges) {\n adj.set(a, [...(adj.get(a) ?? []), b])\n adj.set(b, [...(adj.get(b) ?? []), a])\n }\n const seen = new Set(anchored)\n const queue = [...anchored]\n while (queue.length) {\n for (const n of adj.get(queue.pop()!) ?? []) {\n if (seen.has(n)) continue\n seen.add(n)\n queue.push(n)\n }\n }\n const lost = structural.filter((p) => !seen.has(p.id)).map((p) => p.id)\n if (lost.length) warnings.push(`structural part(s) ${lost.map((i) => `\"${i}\"`).join(', ')} cannot reach an anchored part, so they will fall`)\n }\n return { ok: problems.length === 0, problems, warnings }\n}\n","import type { BallisticExtras, Hit, HitIgnition, Vec3 } from './destruction'\n\n/**\n * A ballistic shot (one per pellet) as a weapon module produces it. Plain data: any damage model can consume it (`shotToHit` makes the `Hit`).\n */\nexport interface Shot {\n origin: Vec3\n /** Unit vector. */\n direction: Vec3\n /** Muzzle energy in joules. */\n energy: number\n /** Bullet diameter in millimetres. */\n caliber: number\n /** snake_case calibre id, e.g. `9x19`. */\n caliberId: string\n /** Muzzle speed in m/s. */\n speed: number\n /** Projectile mass in grams (one pellet for a shotgun load). */\n mass?: number\n /** Energy at a distance in metres, with the calibre's drag. */\n energyAt(distance: number): number\n pellet: number\n /** snake_case weapon id. */\n weapon: string\n source?: string\n /** Kind of the round that was loaded (`fmj`, `hp`, `ap`, `buck`, `slug`, `incendiary`, `tracer`...). */\n ammo?: string\n /** Millimetres of steel, concrete, brick and wood the round goes through at the muzzle (the ammo table of the weapons module). `shotToHit` scales it by the energy left. */\n penetration?: Readonly<Record<string, number>>\n incendiary?: boolean\n tracer?: boolean\n /** Chances that the round lights flammable vapour or fuel. */\n ignition?: HitIgnition\n}\n\n/**\n * The fields of the round that a damage model takes besides the geometry: the penetration by material scaled by the energy that is left at `distance`\n * (linear in the energy: half the energy goes through half as much), the incendiary and tracer flags and the ignition chances. Pass it as the sixth\n * argument of `DestructionWorld.shoot` or spread it in a `Hit`.\n */\nexport const shotExtras = (shot: Shot, distance = 0): BallisticExtras => {\n const out: { -readonly [K in keyof BallisticExtras]: BallisticExtras[K] } = {}\n if (shot.penetration) {\n const k = shot.energy > 0 ? Math.min(1, Math.max(0, shot.energyAt(distance) / shot.energy)) : 1\n const scaled: Record<string, number> = {}\n for (const key of Object.keys(shot.penetration)) scaled[key] = shot.penetration[key]! * k\n out.penetration = scaled\n }\n if (shot.incendiary) out.incendiary = true\n if (shot.tracer) out.tracer = true\n if (shot.ignition) out.ignition = { spark: shot.ignition.spark, flame: shot.ignition.flame }\n return out\n}\n\n/** One use of a non-firearm (melee swing, flame tick, heat tick, throw, tool tick, extinguisher tick). */\nexport type Use =\n | { kind: 'melee'; damage: 'blunt' | 'slash'; energy: number; radius: number; reach: number; origin: Vec3; direction: Vec3 }\n | { kind: 'flame'; temperature: number; radius: number; range: number; cone: boolean; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'heat'; temperature: number; radius: number; range: number; duration: number; origin: Vec3; direction: Vec3 }\n | {\n kind: 'throw'\n energy: number\n radius: number\n fuse: number\n velocity: Vec3\n origin: Vec3\n fire?: { temperature: number; radius: number; seconds: number }\n /** Explosive id (`m67`, `molotov`, `pg7v`...): the host looks the numbers up in the arsenal. Absent on a plain thrown object. */\n explosive?: string\n /** What sets it off: `timer` after `fuse` seconds, `impact` on the first hit once armed. */\n trigger?: 'timer' | 'impact'\n /** Metres the projectile must fly before an impact sets it off; closer, it hits without exploding (rocket launchers). */\n armDistance?: number\n /** Radius in metres of the wounding area (`radius` is the lethal one). */\n injuryRadius?: number\n /** Seconds the blast stuns whoever is inside the injury radius (flashbang). */\n stunSeconds?: number\n /** Seconds the thrower held it after pulling the pin: `fuse` is what was left of the full fuse when it left the hand. */\n cooked?: number\n /** Went off in the thrower's hand (held past the fuse): no velocity, `fuse` is 0 and the blast is at `origin`. */\n inHand?: boolean\n }\n /** An explosive set down where the trigger is pulled (mine, C4, charge): it waits for its trigger instead of flying. */\n | {\n kind: 'place'\n explosive: string\n /** `wire`: something trips it; `remote`: the player fires it; `timer`: after `fuse` seconds. */\n triggers: readonly ('timer' | 'wire' | 'remote')[]\n energy: number\n /** Lethal radius in metres. */\n radius: number\n injuryRadius: number\n /** Cone the blast goes through, in front of `direction` (mine); absent for a blast in every direction. */\n cone?: { halfAngleDeg: number; length: number }\n /** The wire a `wire` charge stretches from where it is set down: metres out, degrees from its facing (counter-clockwise from above) and metres above it. */\n tripwire?: { length: number; angleDeg: number; height: number }\n fuse?: number\n origin: Vec3\n direction: Vec3\n }\n /** The blast behind a rocket launcher: dangerous inside `radius` metres, in the cone around `direction` (pointing away from the target). */\n | { kind: 'backblast'; radius: number; halfAngleDeg: number; origin: Vec3; direction: Vec3 }\n | { kind: 'tool'; tool: string; reach: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'extinguish'; range: number; coolC: number; duration: number; origin: Vec3; direction: Vec3 }\n | { kind: 'hand'; reach: number; origin: Vec3; direction: Vec3 }\n\n/**\n * The `Hit` a ballistic shot makes at `point` (world space): the energy is what is left of the shot at that distance from its origin\n * (`shot.energyAt`), the direction and calibre come from the shot. `normal` (the surface normal at the point, when the caller knows it) does not\n * change the hit; it is accepted so that callers can pass what their raycast returned and so that a stricter implementation could use it.\n */\nexport const shotToHit = (shot: Shot, point: Vec3, normal?: Vec3): Hit => {\n void normal\n const dx = point[0] - shot.origin[0]\n const dy = point[1] - shot.origin[1]\n const dz = point[2] - shot.origin[2]\n const distance = Math.hypot(dx, dy, dz)\n return {\n type: 'ballistic',\n point: [point[0], point[1], point[2]],\n direction: [shot.direction[0], shot.direction[1], shot.direction[2]],\n energy: shot.energyAt(distance),\n caliber: shot.caliber,\n ...(shot.mass === undefined ? {} : { mass: shot.mass }),\n ...shotExtras(shot, distance),\n source: shot.source ?? shot.weapon,\n }\n}\n\n/**\n * The `Hit` a non-firearm `Use` makes at `point` (world space), or `null` for uses that do not damage by themselves.\n *\n * - `melee` -> `blunt` / `slash` with the swing's `energy`, contact `radius` and `direction`;\n * - `flame` -> `fire` and `heat` -> `heat`, with `temperature`, `duration` and a contact radius of at most 0.3 m (one ray of the cone);\n * - `throw` -> the blast (`explosive`, `energy`, `radius`, centred on `point`, the place it detonates). A thrown item with no blast energy but\n * a `fire` patch (a molotov) gives that patch as a `fire` hit (`temperature`, `radius`, `seconds` as `duration`). No energy and no fire -> `null`;\n * - `tool`, `extinguish` and `hand` -> `null` (tools work on joints, the extinguisher cools, the hand only grabs).\n *\n * `normal` does not change the hit (same as `shotToHit`).\n */\nexport const useToHit = (use: Use, point: Vec3, normal?: Vec3): Hit | null => {\n void normal\n const p: Vec3 = [point[0], point[1], point[2]]\n switch (use.kind) {\n case 'melee':\n return { type: use.damage, point: p, direction: [use.direction[0], use.direction[1], use.direction[2]], energy: use.energy, radius: use.radius }\n case 'flame':\n case 'heat':\n return {\n type: use.kind === 'flame' ? 'fire' : 'heat',\n point: p,\n direction: [use.direction[0], use.direction[1], use.direction[2]],\n temperature: use.temperature,\n radius: Math.min(use.radius, 0.3),\n duration: use.duration,\n }\n case 'throw':\n if (use.energy > 0) return { type: 'explosive', point: p, energy: use.energy, radius: use.radius }\n if (use.fire) return { type: 'fire', point: p, temperature: use.fire.temperature, radius: use.fire.radius, duration: use.fire.seconds }\n return null\n default:\n return null\n }\n}\n","import type { Hit } from './destruction'\n\n/**\n * How a container of flammable fluid (a fuel tank, a jerrycan, a gas bottle) is set alight by what hits it. A normal bullet that goes through only\n * makes a leak; the leak lights when something supplies a flame: a spark of a hard round on metal, an incendiary or tracer round, a fire nearby\n * or a blast. These are the numbers of the target side; the numbers of the round (core, jacket, incendiary, tracer) are in the weapons module\n * (`rules.ignition` of `@adatechnology/game-weapons`) and reach the target in `Hit.ignition`. Every number is a default to be changed per game.\n */\nexport interface IgnitionRules {\n /**\n * How much of the spark and of the flame of a round reaches the vapour, by how full the container is: points `[filled, factor]`, `filled` 0..1\n * (litres over capacity), `factor` 0..1, linear between points. A full container holds a mixture too rich to burn (the vapour has no air) and\n * mostly leaks; a nearly empty one holds the vapour/air mixture of a flammable range and lights the easiest; a dry one has little vapour left.\n * Default: 0.6 empty, 1 at 10 percent, 0.6 at 35, 0.3 at 65, 0.15 at 90 and 0.12 full.\n */\n fillCurve: ReadonlyArray<readonly [number, number]>\n /** 0..1: how much of the fill factor also weighs on the flame of an incendiary or tracer (1: as much as on a spark; 0: not at all). Default 0.5. */\n flameFillInfluence: number\n /** Chance of the flame of a round that is flagged `incendiary` or `tracer` but carries no `ignition` numbers (a host that passes only the flags). */\n flameDefaults: { incendiary: number; tracer: number }\n /**\n * What a spark needs to strike: a factor 0..1 by material id of the struck part. A material that is not listed but is metal takes\n * `sparkMetalDefault`; a part that is not metal never sparks. Default: steel and iron 1, aluminium 0.25.\n */\n sparkTarget: Readonly<Record<string, number>>\n sparkMetalDefault: number\n /**\n * Factor 0..1 on the spark by fluid (default 1): diesel has a flash point of 52 degrees C and more, so a spark that lights petrol vapour does\n * not light it (a flame does). Default: diesel 0.15.\n */\n sparkFluid: Readonly<Record<string, number>>\n /** A leaking container of flammable fluid within `radius` metres of a burning part or a burning fuel stain lights at `chancePerSecond`. */\n fireNear: { radius: number; chancePerSecond: number }\n}\n\n/** Defaults of `IgnitionRules`. */\nexport const DEFAULT_IGNITION_RULES: IgnitionRules = {\n fillCurve: [\n [0, 0.6],\n [0.1, 1],\n [0.35, 0.6],\n [0.65, 0.3],\n [0.9, 0.15],\n [1, 0.12],\n ],\n flameFillInfluence: 0.5,\n flameDefaults: { incendiary: 0.7, tracer: 0.2 },\n sparkTarget: { steel: 1, iron: 1, aluminium: 0.25 },\n sparkMetalDefault: 0.5,\n sparkFluid: { diesel: 0.15 },\n fireNear: { radius: 1.5, chancePerSecond: 0.5 },\n}\n\n/** Merges a partial `IgnitionRules` over the defaults (an object is merged one level deep). */\nexport const resolveIgnitionRules = (rules?: Partial<IgnitionRules>): IgnitionRules => ({\n ...DEFAULT_IGNITION_RULES,\n ...rules,\n flameDefaults: { ...DEFAULT_IGNITION_RULES.flameDefaults, ...rules?.flameDefaults },\n sparkTarget: { ...DEFAULT_IGNITION_RULES.sparkTarget, ...rules?.sparkTarget },\n sparkFluid: { ...DEFAULT_IGNITION_RULES.sparkFluid, ...rules?.sparkFluid },\n fireNear: { ...DEFAULT_IGNITION_RULES.fireNear, ...rules?.fireNear },\n})\n\n/** Linear interpolation of the fill curve at `fill` (0..1); outside the points it keeps the first or the last. */\nexport const fillFactor = (fill: number, curve: IgnitionRules['fillCurve'] = DEFAULT_IGNITION_RULES.fillCurve): number => {\n if (curve.length === 0) return 1\n const f = Math.min(1, Math.max(0, fill))\n if (f <= curve[0]![0]) return curve[0]![1]\n for (let i = 1; i < curve.length; i++) {\n const [x1, y1] = curve[i]!\n const [x0, y0] = curve[i - 1]!\n if (f <= x1) return x1 === x0 ? y1 : y0 + ((y1 - y0) * (f - x0)) / (x1 - x0)\n }\n return curve[curve.length - 1]![1]\n}\n\n/** The factor of what a spark strikes: 0 when the struck part is not metal. */\nexport const sparkTargetFactor = (materialId: string, metal: boolean, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number =>\n !metal ? 0 : rules.sparkTarget[materialId] ?? rules.sparkMetalDefault\n\n/**\n * Chance that one round that went through the wall of a container lights the fluid that leaks: the spark (only on metal) and the flame (any\n * wall), each weighed by the fill of the container; the two are independent. 0 when the round carries nothing (`Hit.ignition` absent and not\n * flagged `incendiary` or `tracer`): a plain bullet on a plain wall only leaks.\n */\nexport const ignitionChance = (hit: Pick<Hit, 'incendiary' | 'tracer' | 'ignition'>, target: { sparkTarget: number; fill: number; fluid?: string }, rules: IgnitionRules = DEFAULT_IGNITION_RULES): number => {\n const k = fillFactor(target.fill, rules.fillCurve)\n const spark = (hit.ignition?.spark ?? 0) * target.sparkTarget * (target.fluid === undefined ? 1 : rules.sparkFluid[target.fluid] ?? 1) * k\n const flameBase = hit.ignition?.flame ?? Math.max(hit.incendiary ? rules.flameDefaults.incendiary : 0, hit.tracer ? rules.flameDefaults.tracer : 0)\n const flame = flameBase * (1 - rules.flameFillInfluence * (1 - k))\n return 1 - (1 - Math.min(1, Math.max(0, spark))) * (1 - Math.min(1, Math.max(0, flame)))\n}\n","/**\n * The seal of a closed container (a food tin, a drink can, a jar, a bottle with a cap): what opens it and whether a breach spoils what is inside.\n * Plain data and one pure check, shared by the item rules (`resolveUse` of game-items) and any host that lets the player open and eat (the test room).\n */\nexport interface SealSpec {\n /** Ids of the tools that open it (items or weapons: `can_opener`, `knife`); any one of them is enough. */\n readonly openWith?: readonly string[]\n /** It opens by hand (a pull tab, a ring pull, a screw cap): no tool needed. */\n readonly byHand?: boolean\n /** A hole through the container or a leak spoils what is inside: it can no longer be eaten or drunk. */\n readonly spoilsWhenBreached?: boolean\n}\n\n/** The state of one container: opened, holed through (a shot, a blade) or leaking. */\nexport interface SealState {\n readonly opened?: boolean\n readonly breached?: boolean\n readonly leaked?: boolean\n}\n\n/** Why a sealed container cannot be eaten or drunk now. */\nexport type SealBlock = 'sealed' | 'breached' | 'leaked'\n\n/** Whether it can be opened with the tools at hand, and with which one (undefined when it opens by hand). */\nexport const sealOpener = (seal: SealSpec, tools: Iterable<string>): { readonly ok: boolean; readonly tool?: string } => {\n if (seal.byHand || !seal.openWith || seal.openWith.length === 0) return { ok: true }\n const have = new Set(tools)\n const tool = seal.openWith.find((id) => have.has(id))\n return tool === undefined ? { ok: false } : { ok: true, tool }\n}\n\n/** What stops eating or drinking it now, or undefined when nothing does. A spoiled container (breached, leaked) is blocked even once open. */\nexport const sealBlock = (seal: SealSpec, state: SealState): SealBlock | undefined => {\n if (seal.spoilsWhenBreached && state.breached) return 'breached'\n if (seal.spoilsWhenBreached && state.leaked) return 'leaked'\n if (!state.opened) return 'sealed'\n return undefined\n}\n","/** How a hand turns something round in strokes (a screw cap, a tap handle, a knob): what `twistStroke` answers for one moment of the turning. */\nexport interface TwistStroke {\n /** Radians the wrist is turned from the middle of its stroke, positive the way the part turns. */\n readonly angle: number\n /** Radians the part has turned in all, from 0 to `strokes * reach`. */\n readonly turned: number\n /** How closed the fingers are, 0 open to 1 closed: closed on the part while it turns, open while the wrist turns back. */\n readonly grip: number\n /** 0..1, how far the hand rises off the part while the wrist turns back (1 is `TWIST_LIFT` metres). */\n readonly lift: number\n}\n\nexport interface TwistOptions {\n /** Strokes of the wrist. Default 3. */\n readonly strokes?: number\n /** Radians the part turns in one stroke (a wrist turns about a quarter round with its hold). Default 1.6. */\n readonly reach?: number\n}\n\n/** Metres a hand rises off the part between two strokes. */\nexport const TWIST_LIFT = 0.012\n/** Share of each stroke spent turning the part; the rest turns the wrist back open. */\nconst TURNING = 0.7\n\nconst smooth = (k: number): number => k * k * (3 - 2 * k)\n\n/**\n * The hand turning a part round at `share` (0..1) of the whole turning: in each stroke the wrist turns with the part, then lets go, rises a little and turns back.\n * Pure and the same for every host, so first and third person turn the same hand the same way.\n */\nexport const twistStroke = (share: number, options: TwistOptions = {}): TwistStroke => {\n const strokes = Math.max(1, Math.round(options.strokes ?? 3))\n const reach = options.reach ?? 1.6\n const along = Math.min(1, Math.max(0, share)) * strokes\n const index = Math.min(strokes - 1, Math.floor(along))\n const phase = along - index\n if (phase <= TURNING) {\n const k = smooth(phase / TURNING)\n return { angle: reach * (k - 0.5), turned: reach * (index + k), grip: 1, lift: 0 }\n }\n const k = (phase - TURNING) / (1 - TURNING)\n return { angle: reach * (0.5 - smooth(k)), turned: reach * (index + 1), grip: 0.35, lift: Math.sin(k * Math.PI) }\n}\n","import type { Vec3 } from './destruction'\n\n/** Pose of one part (or of the whole item) at a key: position offset in metres and Euler XYZ rotation in radians, both relative to the rest pose. */\nexport interface AnimationPose {\n position?: Vec3\n rotation?: Vec3\n}\n\nexport interface AnimationKey {\n /** Seconds from the start of the clip. */\n t: number\n /** Pose of the item's root. */\n position?: Vec3\n rotation?: Vec3\n /** Poses of named parts: the key is a destruction part id (a pistol `reload` moves `mag`; a car door `open` rotates `door_l`). */\n parts?: Record<string, AnimationPose>\n}\n\nexport interface AnimationEventSpec {\n /** Seconds from the start of the clip. */\n t: number\n /** snake_case type the host maps (`sound`, `eject_casing`, `door_latch`...). */\n type: string\n data?: Record<string, unknown>\n /**\n * Seconds of real time the event fires before `t`, not stretched with the clip: a recorded sound whose hit comes that long after its start\n * (the click of a magazine seating) starts early so the hit lands on `t`. The player passes the lead it could apply as `data.lead`.\n */\n lead?: number\n}\n\n/** A use animation a module brings with its item. Poses between keys are interpolated by the player (the test room does it linearly). */\nexport interface AnimationClipSpec {\n /** snake_case: `reload`, `open`, `drink`... Unique within the item. */\n id: string\n /** Seconds. */\n duration: number\n keys: AnimationKey[]\n events?: AnimationEventSpec[]\n}\n\n/** What an item exposes when it brings its own animations. */\nexport interface ItemAnimationContract {\n animations: AnimationClipSpec[]\n}\n\nconst finite3 = (v: unknown): boolean => Array.isArray(v) && v.length === 3 && v.every((n) => typeof n === 'number' && Number.isFinite(n))\n\n/**\n * Problems with a clip (empty when it is valid): a snake_case id, a positive finite duration, at least one key, key and event times inside\n * `[0, duration]` and not going backwards, finite vectors, every named part one of `partIds`, event types that are non-empty strings and\n * JSON-serializable event data.\n */\nexport const checkAnimation = (clip: AnimationClipSpec, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const problems: string[] = []\n const parts = new Set(partIds)\n const id = String(clip?.id ?? '')\n if (!/^[a-z][a-z0-9_]*$/.test(id)) problems.push(`clip id \"${id}\" must be snake_case`)\n const label = `clip \"${id}\"`\n if (!(typeof clip?.duration === 'number' && Number.isFinite(clip.duration) && clip.duration > 0)) problems.push(`${label} needs a positive finite duration`)\n const dur = typeof clip?.duration === 'number' && clip.duration > 0 ? clip.duration : Infinity\n if (!Array.isArray(clip?.keys) || clip.keys.length === 0) {\n problems.push(`${label} needs at least one key`)\n return { ok: false, problems }\n }\n let prev = -Infinity\n clip.keys.forEach((k, i) => {\n if (!(typeof k.t === 'number' && Number.isFinite(k.t)) || k.t < 0 || k.t > dur + 1e-9) problems.push(`${label} key ${i} has t=${String(k.t)} outside 0..${dur}`)\n else if (k.t < prev) problems.push(`${label} key ${i} goes back in time (${k.t} < ${prev})`)\n else prev = k.t\n for (const f of ['position', 'rotation'] as const) if (k[f] !== undefined && !finite3(k[f])) problems.push(`${label} key ${i} has an invalid ${f}`)\n for (const [pid, pose] of Object.entries(k.parts ?? {})) {\n if (!parts.has(pid)) problems.push(`${label} key ${i} moves unknown part \"${pid}\"`)\n for (const f of ['position', 'rotation'] as const) if (pose?.[f] !== undefined && !finite3(pose[f])) problems.push(`${label} key ${i} part \"${pid}\" has an invalid ${f}`)\n }\n })\n let prevEv = -Infinity\n ;(clip.events ?? []).forEach((e, i) => {\n if (!(typeof e.t === 'number' && Number.isFinite(e.t)) || e.t < 0 || e.t > dur + 1e-9) problems.push(`${label} event ${i} has t=${String(e.t)} outside 0..${dur}`)\n else if (e.t < prevEv) problems.push(`${label} event ${i} goes back in time`)\n else prevEv = e.t\n if (typeof e.type !== 'string' || e.type === '') problems.push(`${label} event ${i} needs a type`)\n try {\n JSON.stringify(e.data ?? {})\n } catch {\n problems.push(`${label} event ${i} data is not JSON`)\n }\n })\n return { ok: problems.length === 0, problems }\n}\n","import type { AnimationClipSpec, AnimationEventSpec, AnimationPose } from './animation'\nimport { checkAnimation } from './animation'\nimport type { HostEvent } from './module'\n\n/** Clips a tool can bring, one per move of its cycle. A tool brings the ones it has; a missing clip is simply not played. */\nexport const TOOL_CLIP = {\n DRAW: 'draw',\n SHOT: 'shot',\n MISFIRE: 'misfire',\n EMPTY: 'empty',\n CYCLE: 'cycle',\n RELOAD: 'reload',\n FEED: 'feed',\n FAULT: 'fault',\n CLEAR: 'clear',\n SAFETY_ON: 'safety_on',\n SAFETY_OFF: 'safety_off',\n MODE: 'mode',\n /** A throwable with the pin out, held until it is thrown. */\n COOK: 'cook',\n /** The stock folds, unfolds, slides in or out (variants `fold`, `unfold`, `collapse`, `extend`). */\n STOCK: 'stock',\n /** A light or a laser is switched (variants `on`, `off`). */\n TOGGLE: 'toggle',\n} as const\nexport type ToolClipId = (typeof TOOL_CLIP)[keyof typeof TOOL_CLIP]\n\n/** What a renderer does when a rule event arrives. `variant` picks `<clip>_<variant>` when the tool has it, else `<clip>`. */\nexport type ToolAnimationStep =\n | { readonly type: 'play'; readonly clip: ToolClipId; readonly variant?: string; readonly duration?: number; readonly repeat?: number }\n /** Move the clip that is playing to the marker (a clip event `stage` with `data.stage`) the rule just reached. */\n | { readonly type: 'sync'; readonly stage: string }\n /** The rule says the phase is over: the clip jumps to its end if it is still running. */\n | { readonly type: 'finish'; readonly clip: ToolClipId }\n\nconst stockVariant = (event: Extract<HostEvent, { type: 'stock' }>): string => {\n const isFolding = event.kind === undefined ? false : event.kind.includes('fold')\n if (event.state === 'collapsed') return isFolding ? 'fold' : 'collapse'\n return isFolding ? 'unfold' : 'extend'\n}\n\n/** The move a host event asks of the tool in hand, or null when it has no motion. */\nexport const toolAnimationStep = (event: HostEvent): ToolAnimationStep | null => {\n switch (event.type) {\n case 'tool':\n return { type: 'play', clip: TOOL_CLIP.DRAW, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'shot':\n return { type: 'play', clip: TOOL_CLIP.SHOT, repeat: Math.max(1, event.rounds ?? 1) }\n case 'misfire':\n return { type: 'play', clip: TOOL_CLIP.MISFIRE }\n case 'empty':\n return { type: 'play', clip: TOOL_CLIP.EMPTY }\n case 'mode':\n return { type: 'play', clip: TOOL_CLIP.MODE, variant: event.mode }\n case 'fault':\n return { type: 'play', clip: TOOL_CLIP.FAULT, variant: event.fault }\n case 'clear':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CLEAR }\n return { type: 'play', clip: TOOL_CLIP.CLEAR, variant: event.fault, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'safety':\n return { type: 'play', clip: event.on ? TOOL_CLIP.SAFETY_ON : TOOL_CLIP.SAFETY_OFF }\n case 'cycle':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.CYCLE }\n return { type: 'play', clip: TOOL_CLIP.CYCLE, ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'reload':\n if (event.phase === 'end') return { type: 'finish', clip: TOOL_CLIP.RELOAD }\n return { type: 'play', clip: TOOL_CLIP.RELOAD, ...(event.kind === undefined ? {} : { variant: event.kind }), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'stage':\n return { type: 'sync', stage: event.stage }\n case 'feed':\n return { type: 'play', clip: TOOL_CLIP.FEED }\n case 'cook':\n if (event.phase === 'start') return { type: 'play', clip: TOOL_CLIP.COOK, duration: event.fuse }\n return { type: 'finish', clip: TOOL_CLIP.COOK }\n case 'stock':\n return { type: 'play', clip: TOOL_CLIP.STOCK, variant: stockVariant(event), ...(event.duration === undefined ? {} : { duration: event.duration }) }\n case 'toggle':\n return { type: 'play', clip: TOOL_CLIP.TOGGLE, variant: event.on ? 'on' : 'off' }\n default:\n return null\n }\n}\n\n/** Where a renderer puts the poses: every part of the tool by id (the ids the clips move), and the whole tool. Poses are offsets from rest. */\nexport interface ToolRig {\n setPartPose(partId: string, pose: AnimationPose): void\n setRootPose?(pose: AnimationPose): void\n}\n\n/** Clips by id, with the variants as `<clip>_<variant>`. */\nexport type ToolClipSet = Readonly<Record<string, AnimationClipSpec>>\n\n/** A renderer's tool animator: feed it the host events and the frame time. */\nexport interface ToolAnimator {\n handle(event: HostEvent): void\n update(dt: number): void\n /** Ids of the clips playing now. */\n readonly playing: readonly string[]\n dispose(): void\n}\n\nexport const STAGE_EVENT = 'stage'\n\n/** The clip with its times (keys and events) scaled so that it lasts `duration` seconds. */\nexport const scaleClip = (clip: AnimationClipSpec, duration: number): AnimationClipSpec => {\n const factor = clip.duration > 0 ? duration / clip.duration : 1\n return {\n ...clip,\n duration,\n keys: clip.keys.map((key) => ({ ...key, t: key.t * factor })),\n ...(clip.events ? { events: clip.events.map((event) => ({ ...event, t: event.t * factor })) } : {}),\n }\n}\n\nconst ZERO: [number, number, number] = [0, 0, 0]\nconst mix = (from: readonly number[], to: readonly number[], fraction: number): [number, number, number] => [\n (from[0] ?? 0) + ((to[0] ?? 0) - (from[0] ?? 0)) * fraction,\n (from[1] ?? 0) + ((to[1] ?? 0) - (from[1] ?? 0)) * fraction,\n (from[2] ?? 0) + ((to[2] ?? 0) - (from[2] ?? 0)) * fraction,\n]\n\n/** Pose of the whole tool (`partId` undefined) or of one part at `time`, linear between keys; a key that does not name it means rest. */\nexport const sampleClip = (clip: AnimationClipSpec, partId: string | undefined, time: number): { position: [number, number, number]; rotation: [number, number, number] } => {\n const points = clip.keys.map((key) => {\n const pose = partId === undefined ? key : key.parts?.[partId]\n return { t: key.t, position: pose?.position ?? ZERO, rotation: pose?.rotation ?? ZERO }\n })\n const first = points[0]\n if (!first || first.t > 0) points.unshift({ t: 0, position: ZERO, rotation: ZERO })\n const last = points[points.length - 1]\n if (!last) return { position: ZERO, rotation: ZERO }\n if (time >= last.t) return { position: mix(last.position, last.position, 0), rotation: mix(last.rotation, last.rotation, 0) }\n const index = Math.max(0, points.findIndex((point, i) => time >= point.t && time < (points[i + 1]?.t ?? Infinity)))\n const from = points[index]\n const to = points[index + 1]\n if (!from || !to) return { position: ZERO, rotation: ZERO }\n const fraction = to.t > from.t ? (time - from.t) / (to.t - from.t) : 0\n return { position: mix(from.position, to.position, fraction), rotation: mix(from.rotation, to.rotation, fraction) }\n}\n\n/** Problems with a clip set (empty when valid): each key is the clip id (or `<clip>_<variant>`), every clip passes `checkAnimation`, and a `stage` event names its stage. */\nexport const checkToolClips = (clips: ToolClipSet, partIds: Iterable<string>): { ok: boolean; problems: string[] } => {\n const parts = [...partIds]\n const problems: string[] = []\n for (const [key, clip] of Object.entries(clips)) {\n if (clip.id !== key) problems.push(`clip \"${key}\" has the id \"${clip.id}\"`)\n if (!(clip.duration > 0)) problems.push(`clip \"${key}\" has no duration`)\n problems.push(...checkAnimation(clip, parts).problems)\n for (const event of clip.events ?? []) if (event.type === STAGE_EVENT && typeof event.data?.stage !== 'string') problems.push(`clip \"${key}\" has a stage event without data.stage`)\n }\n return { ok: problems.length === 0, problems }\n}\n\ninterface Instance {\n readonly name: string\n readonly clip: AnimationClipSpec\n time: number\n delay: number\n fired: number\n}\n\nexport interface ToolClipPlayerOptions {\n clips: ToolClipSet\n rig: ToolRig\n /** Called for each clip event as its time passes (`eject_casing`, `drop_magazine`, `stage`...). */\n onEvent?(event: AnimationEventSpec, clip: string): void\n /** Seconds between the rounds of a `repeat` (a burst): default 0.1. */\n repeatInterval?(): number\n}\n\n/** The default player of a tool's clips: runs the steps of `toolAnimationStep` against a rig, scaled to the duration the rule gives. */\nexport interface ToolClipPlayer {\n apply(step: ToolAnimationStep): void\n update(dt: number): void\n readonly playing: readonly string[]\n /** The clips being played with the time each has reached and the clip itself (scaled to the duration the rule gave), for a renderer that has to follow what the clip does now (the hands working a part). */\n readonly running: ReadonlyArray<{ readonly name: string; readonly time: number; readonly clip: AnimationClipSpec }>\n}\n\n/**\n * The clip with every event that has a `lead` moved that many seconds earlier, the lead it got in `data.lead`. A led event never goes before 0\n * nor before the event written ahead of it (a fast clip keeps its order: the lead shrinks). Run after `scaleClip`: the lead is real time, the\n * clip's stretch does not touch it.\n */\nexport const leadClipEvents = (clip: AnimationClipSpec): AnimationClipSpec => {\n const events = clip.events ?? []\n if (!events.some((event) => (event.lead ?? 0) > 0)) return clip\n let floor = 0\n const led = events.map((event) => {\n const lead = Math.max(0, Math.min(event.t - floor, event.lead ?? 0))\n const t = event.t - lead\n floor = Math.max(floor, t)\n if (event.lead === undefined) return event\n const moved: AnimationEventSpec = { ...event, t, data: lead > 0 ? { ...event.data, lead } : { ...event.data } }\n delete moved.lead\n return moved\n })\n return { ...clip, events: led }\n}\n\nexport const createToolClipPlayer = (options: ToolClipPlayerOptions): ToolClipPlayer => {\n const { clips, rig, onEvent } = options\n let instances: Instance[] = []\n\n const find = (clip: string, variant?: string): { name: string; clip: AnimationClipSpec } | undefined => {\n const name = variant !== undefined && clips[`${clip}_${variant}`] ? `${clip}_${variant}` : clip\n const found = clips[name]\n return found ? { name, clip: found } : undefined\n }\n\n const render = (instance: Instance): void => {\n const time = Math.min(instance.time, instance.clip.duration)\n const root = sampleClip(instance.clip, undefined, time)\n if (instance.clip.keys.some((key) => key.position || key.rotation)) rig.setRootPose?.(root)\n const touched = new Set(instance.clip.keys.flatMap((key) => Object.keys(key.parts ?? {})))\n for (const id of touched) rig.setPartPose(id, sampleClip(instance.clip, id, time))\n }\n\n const fireEvents = (instance: Instance, upTo: number): void => {\n const events = instance.clip.events ?? []\n while (instance.fired < events.length && (events[instance.fired]?.t ?? Infinity) <= upTo + 1e-9) {\n const event = events[instance.fired]\n instance.fired += 1\n if (event) onEvent?.(event, instance.name)\n }\n }\n\n return {\n apply(step) {\n if (step.type === 'sync') {\n for (const instance of instances) {\n const marker = (instance.clip.events ?? []).find((event) => event.type === STAGE_EVENT && event.data?.stage === step.stage)\n if (marker && instance.time < marker.t) instance.time = marker.t\n }\n return\n }\n if (step.type === 'finish') {\n for (const instance of instances) {\n if (instance.name !== step.clip && !instance.name.startsWith(`${step.clip}_`)) continue\n fireEvents(instance, instance.clip.duration)\n instance.time = instance.clip.duration\n }\n return\n }\n const found = find(step.clip, step.variant)\n if (!found) return\n const clip = leadClipEvents(step.duration && step.duration > 0 ? scaleClip(found.clip, step.duration) : found.clip)\n const interval = options.repeatInterval?.() ?? 0.1\n instances = instances.filter((existing) => existing.name !== found.name || existing.delay > 0)\n for (let round = 0; round < (step.repeat ?? 1); round++) {\n instances.push({ name: found.name, clip, time: 0, delay: round * interval, fired: 0 })\n }\n },\n update(dt) {\n for (const instance of instances) {\n const carried = instance.delay > 0 ? dt - instance.delay : dt\n if (instance.delay > 0) {\n instance.delay = Math.max(0, instance.delay - dt)\n if (instance.delay > 0) continue\n }\n instance.time += carried\n fireEvents(instance, instance.time)\n render(instance)\n }\n instances = instances.filter((instance) => instance.delay > 0 || instance.time < instance.clip.duration)\n },\n get playing() {\n return instances.map((instance) => instance.name)\n },\n get running() {\n return instances.filter((instance) => instance.delay <= 0).map((instance) => ({ name: instance.name, time: instance.time, clip: instance.clip }))\n },\n }\n}\n","export const FRAME_PHASES = ['input', 'fixedSimulate', 'lateSimulate', 'present', 'render', 'idle'] as const\nexport type FramePhase = (typeof FRAME_PHASES)[number]\n\n/**\n * Presentation work a system leaves for later frames, run in small units within a shared time budget.\n * Never simulation: nothing that consumes a seeded generator or decides an outcome may wait in a queue.\n */\nexport interface DeferredQueue {\n /** Stable name for stats and logs (see `DEFERRED_QUEUE_ID`). */\n readonly id: string\n /**\n * Units waiting. 0 means idle; the budget skips the queue without calling `run`. `frame` is the budget's frame counter: a queue may\n * report 0 for the rest of a frame (the crease queue does in the frame a panel was torn). Same value for repeated calls in one frame.\n */\n pending(frame?: number): number\n /**\n * Runs units in order until `clock() >= deadline`. Contract: when `pending() > 0` it runs **at least one** unit, even with a deadline\n * already past; it never runs a unit after it saw the deadline pass. Returns how many units it ran.\n */\n run(deadline: number, clock: () => number): number\n /** Runs everything now (synchronous step, clear, dispose). */\n flush(): void\n /**\n * Called by `budget.register`: from now on the owner stops draining on its own (no MessageChannel, no drain inside `update`).\n * Never called by a getter; a queue nobody registered keeps today's internal draining.\n */\n attach?(): void\n /** Called by the unregister function and by `budget.dispose`: the owner goes back to its internal draining. */\n detach?(): void\n}\n\n/** Where a module registers a deferred queue with the host's budget. */\nexport interface DeferredQueueOptions {\n /** Higher runs first. See DEFERRED_PRIORITY. */\n readonly priority: number\n /** `present` runs before the render (the work must show this frame); `idle` runs after it. Default `idle`. */\n readonly phase?: 'present' | 'idle'\n /** Starvation guard: the queue runs at least one unit every this many frames, even with the budget spent. Default 4. */\n readonly minEveryFrames?: number\n /** Milliseconds of every frame kept for this queue before the others share the rest (when it has work). Default 0. */\n readonly reserveMs?: number\n}\n\n/** The ids of the kit's queues: what `DeferredQueue.id` says and what `DEFERRED_PRIORITY` is keyed by. */\nexport const DEFERRED_QUEUE_ID = {\n DESTRUCTION_EVENTS: 'destruction.events',\n BREACH_PAINT: 'floorplan.breach-paint',\n AUDIO_VOICES: 'audio.voices',\n VEHICLE_CREASE: 'vehicles.crease',\n} as const\n\n/** Default priorities and reserves of the kit's queues; a host may override any of them. */\nexport const DEFERRED_PRIORITY = {\n [DEFERRED_QUEUE_ID.DESTRUCTION_EVENTS]: { priority: 300, phase: 'present' },\n [DEFERRED_QUEUE_ID.BREACH_PAINT]: { priority: 250, phase: 'present' },\n [DEFERRED_QUEUE_ID.AUDIO_VOICES]: { priority: 200, phase: 'idle', reserveMs: 1 },\n [DEFERRED_QUEUE_ID.VEHICLE_CREASE]: { priority: 100, phase: 'idle' },\n} as const satisfies Readonly<Record<string, DeferredQueueOptions>>\n\nexport interface DeferredQueueReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\n/**\n * Checks the `DeferredQueue` contract. `fill` leaves the queue with at least two units waiting (the same call is made on a fresh queue).\n * It cannot prove the queue only carries presentation work: that is a rule of review.\n */\nexport function checkDeferredQueue(queue: DeferredQueue, fill: () => void): DeferredQueueReport {\n const problems: string[] = []\n fill()\n const waiting = queue.pending(1)\n if (waiting < 2) problems.push(`fill() must leave at least 2 units waiting (pending is ${waiting})`)\n if (queue.pending(1) !== waiting) problems.push('pending(frame) changed between two calls in the same frame')\n const ran = queue.run(0, () => 1)\n if (ran !== 1) problems.push(`run with a deadline already past must run exactly one unit (ran ${ran})`)\n if (waiting >= 2 && queue.pending(2) !== waiting - 1) problems.push(`one unit ran but pending went from ${waiting} to ${queue.pending(2)}`)\n try {\n queue.attach?.()\n queue.attach?.()\n queue.detach?.()\n queue.detach?.()\n } catch (error) {\n problems.push(`attach/detach must be idempotent: ${error instanceof Error ? error.message : String(error)}`)\n }\n queue.flush()\n if (queue.pending(3) !== 0) problems.push(`flush must leave nothing pending (pending is ${queue.pending(3)})`)\n if (queue.run(0, () => 1) !== 0) problems.push('run on an empty queue must run no unit')\n return { ok: problems.length === 0, problems }\n}\n","const WARNED_KEY = Symbol.for('@adatechnology/game-contracts.warned')\n\ntype WarnedHolder = { [WARNED_KEY]?: Set<string> }\n\nconst warnedKeys = (): Set<string> => {\n const holder = globalThis as WarnedHolder\n return (holder[WARNED_KEY] ??= new Set<string>())\n}\n\ndeclare const process: { readonly env: { readonly NODE_ENV?: string } }\n\n// The literal `process.env.NODE_ENV` is what bundlers replace; where there is no `process` the reference throws and counts as development.\nconst isProduction = (): boolean => {\n try {\n return process.env.NODE_ENV === 'production'\n } catch {\n return false\n }\n}\n\nconst isQuiet = (): boolean => (globalThis as { __GAME_KIT_QUIET__?: unknown }).__GAME_KIT_QUIET__ === true\n\n/**\n * Warns on the console the first time `key` is seen, and only outside production and when `globalThis.__GAME_KIT_QUIET__` is not `true`: for a silent fallback that keeps working (an adapter that made its own effects\n * world or audio engine because the host lent none). The seen keys live on `globalThis`, so several bundles of the kit on one page warn once together.\n */\nexport const warnOnce = (key: string, message: string): void => {\n if (isQuiet() || isProduction()) return\n const seen = warnedKeys()\n if (seen.has(key)) return\n seen.add(key)\n console.warn(`[game-kit] ${message}`)\n}\n\n/** Forgets what `warnOnce` has seen (tests that count warnings). */\nexport const resetWarnOnce = (): void => warnedKeys().clear()\n","import { warnOnce } from './warn'\n\ntype PlainObject = Record<string, unknown>\ntype Entry = { readonly id: string }\n\n/** Keys that would reach the prototype of the result when a patch comes from parsed JSON. */\nconst UNSAFE_KEYS: ReadonlySet<string> = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst isPlainObject = (value: unknown): value is PlainObject =>\n typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype\n\n/** Recursively optional; arrays and functions are replaced as a whole, objects are merged. */\nexport type DeepPartial<TValue> = TValue extends (...args: never[]) => unknown\n ? TValue\n : TValue extends readonly unknown[]\n ? TValue\n : TValue extends object\n ? { [TKey in keyof TValue]?: DeepPartial<TValue[TKey]> }\n : TValue\n\n/** Merges `patch` over `base`: plain objects merge field by field, arrays, functions and primitives replace. `undefined` in the patch is ignored. */\nexport const deepMerge = <TBase extends object>(base: TBase, patch: object | undefined): TBase => {\n if (!patch) return base\n const result: PlainObject = { ...(base as PlainObject) }\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined || UNSAFE_KEYS.has(key)) continue\n const current = result[key]\n result[key] = isPlainObject(current) && isPlainObject(value) ? deepMerge(current, value) : value\n }\n return result as TBase\n}\n\n/** The shipped entries with the ones from `extra` added or, when the id exists, replaced. */\nexport const mergeById = <TEntry extends Entry>(shipped: readonly TEntry[], extra: readonly TEntry[] | undefined): Map<string, TEntry> => {\n const entries = new Map<string, TEntry>()\n for (const entry of [...shipped, ...(extra ?? [])]) entries.set(entry.id, entry)\n return entries\n}\n\n/** Applies `patch` by id; a patch for an id that does not exist is ignored (and warned about once, in development). */\nexport const applyPatches = <TEntry extends Entry>(entries: Map<string, TEntry>, patches: Readonly<Record<string, DeepPartial<TEntry> | Partial<TEntry>>> | undefined): void => {\n for (const [id, patch] of Object.entries(patches ?? {})) {\n const entry = entries.get(id)\n if (entry) entries.set(id, deepMerge(entry, patch))\n else warnOnce(`registry.patch.${id}`, `patch for \"${id}\" ignored: no entry has that id`)\n }\n}\n\n/** Takes the ids out; an id that does not exist is ignored (and warned about once, in development). */\nexport const removeIds = (entries: Map<string, unknown>, ids: readonly string[] | undefined): void => {\n for (const id of ids ?? []) {\n if (!entries.delete(id)) warnOnce(`registry.remove.${id}`, `remove of \"${id}\" ignored: no entry has that id`)\n }\n}\n","import type { Vec3 } from './destruction'\n\n/**\n * The bench of a module: controls, layers and counters it declares as data. The host keeps the values, draws them in a generic way and hands\n * every change back through `ModuleHost.bench`. Nothing here is specific to a kind of module.\n */\nexport type ControlValue = number | boolean | string\n\nexport interface ChoiceOption {\n readonly id: string\n readonly name: string\n /** Heading the host lists the option under (`optgroup`, a grouped row of buttons). Options of a group must sit next to each other. */\n readonly group?: string\n}\n\ninterface ControlBase {\n /** snake_case, unique across the module's controls, layers and metrics. */\n readonly id: string\n /** Display name, already translated for the locale the host asked for. */\n readonly name: string\n readonly hint?: string\n readonly hidden?: boolean\n /**\n * The change (or the press, for an action) takes a noticeable time, a third of a second or more: the host shows its loading indicator while it works, with this text, or the control's name for `true`.\n * Only the host's own controls panel does it; a change made through `TestRoom.bench().set / act` runs at once.\n */\n readonly slow?: boolean | string\n}\n\nexport interface NumberControl extends ControlBase {\n readonly kind: 'number'\n readonly min: number\n readonly max: number\n readonly step?: number\n readonly unit?: string\n readonly default: number\n}\n\nexport interface BooleanControl extends ControlBase {\n readonly kind: 'boolean'\n readonly default: boolean\n}\n\nexport interface ChoiceControl extends ControlBase {\n readonly kind: 'choice'\n readonly options: readonly ChoiceOption[]\n readonly default: string\n}\n\n/** A button: no value, only the press. */\nexport interface ActionControl extends ControlBase {\n readonly kind: 'action'\n}\n\nexport type ModuleControl = NumberControl | BooleanControl | ChoiceControl | ActionControl\n\n/** Something of the module the viewer turns on or off (smoke, flash, casings). */\nexport interface ModuleLayer {\n readonly id: string\n readonly name: string\n /** On unless `false`. */\n readonly default?: boolean\n}\n\n/** Pulled: the room calls read only when it samples (~4 Hz, or on TestRoom.metrics()). */\nexport interface ModuleMetric {\n readonly id: string\n readonly name: string\n readonly unit?: string\n /** Budget: the host shows a bar and warns past it. */\n readonly max?: number\n readonly digits?: number\n read(): number | string\n}\n\nexport type BenchChange =\n | { readonly kind: 'control'; readonly id: string; readonly value: ControlValue }\n | { readonly kind: 'layer'; readonly id: string; readonly on: boolean }\n | { readonly kind: 'action'; readonly id: string }\n\nexport interface ControlPatch {\n readonly hidden?: boolean\n readonly disabled?: boolean\n readonly options?: readonly ChoiceOption[]\n readonly value?: ControlValue\n}\n\n/** What the host lends a module that declares a bench: the current values and the changes. */\nexport interface ModuleBench {\n value(id: string): ControlValue | undefined\n layer(id: string): boolean\n /** Right after attach returns, the host sends one change per control (not actions) and per layer, in declaration order. */\n onChange(listener: (change: BenchChange) => void): () => void\n /** `value` sets without emitting (no echo loops); `options` falls back to the first option if the value is no longer offered. */\n patch(id: string, patch: ControlPatch): void\n /** Move the host camera (a near / middle / far choice). */\n look(eye: Vec3, target: Vec3): void\n /** Shows a sheet on the host's panel, or takes it down with `null`. A host without a sheet area ignores it. */\n sheet?(sheet: BenchSheet | null): void\n}\n\n/**\n * A card of text the module puts on the host's panel (the sheet of an effect, of a weapon): what it is, its numbers, its steps, its colours and,\n * optionally, a strip of segments over time. Names and texts are already translated for the host's locale.\n */\nexport interface BenchSheet {\n readonly kicker?: string\n readonly title: string\n readonly body?: string\n readonly facts?: readonly { readonly label: string; readonly value: string }[]\n readonly steps?: readonly { readonly at: string; readonly text: string }[]\n readonly swatches?: readonly { readonly color: string; readonly name: string }[]\n readonly note?: string\n /** A strip of named segments (seconds), with tick marks and a playhead that follows the module metric `metric`. */\n readonly timeline?: {\n readonly segments: readonly { readonly name: string; readonly start: number; readonly end: number; readonly color: string }[]\n readonly ticks: readonly number[]\n readonly metric: string\n }\n}\n\nexport interface BenchReport {\n readonly ok: boolean\n readonly problems: readonly string[]\n}\n\nexport interface BenchDeclaration {\n readonly controls?: readonly ModuleControl[]\n readonly layers?: readonly ModuleLayer[]\n readonly metrics?: readonly ModuleMetric[]\n}\n\nconst SNAKE_CASE = /^[a-z][a-z0-9_]*$/\nconst finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n)\n\nfunction checkControl(control: ModuleControl, problems: string[]): void {\n const label = `control \"${control.id}\"`\n if (control.kind === 'number') {\n if (!finite(control.min) || !finite(control.max) || control.min >= control.max) problems.push(`${label} needs min < max`)\n if (control.step !== undefined && !(finite(control.step) && control.step > 0)) problems.push(`${label} needs a step > 0`)\n if (!finite(control.default) || control.default < control.min || control.default > control.max) problems.push(`${label} default ${String(control.default)} is outside ${control.min}..${control.max}`)\n return\n }\n if (control.kind !== 'choice') return\n if (control.options.length === 0) {\n problems.push(`${label} needs at least one option`)\n return\n }\n const seen = new Set<string>()\n const groups = new Set<string>()\n let previousGroup: string | undefined\n for (const option of control.options) {\n if (seen.has(option.id)) problems.push(`${label} repeats option \"${option.id}\"`)\n seen.add(option.id)\n if (option.group !== undefined && (typeof option.group !== 'string' || option.group === '')) problems.push(`${label} option \"${option.id}\" has an empty group`)\n else if (option.group !== undefined && option.group !== previousGroup && groups.has(option.group)) problems.push(`${label} group \"${option.group}\" is split: its options must be next to each other`)\n if (typeof option.group === 'string' && option.group !== '') groups.add(option.group)\n previousGroup = option.group\n }\n if (!seen.has(control.default)) problems.push(`${label} default \"${control.default}\" is not among its options`)\n}\n\n/** snake_case ids unique across controls, layers and metrics; min < max; step > 0; default in range; options non-empty, unique, default among them, each group in one run; metric max > 0. */\nexport function checkBench(declared: BenchDeclaration): BenchReport {\n const problems: string[] = []\n const ids = new Set<string>()\n const claim = (kind: string, id: string): void => {\n if (!SNAKE_CASE.test(id)) problems.push(`${kind} id \"${id}\" must be snake_case`)\n if (ids.has(id)) problems.push(`duplicate id \"${id}\" across controls, layers and metrics`)\n ids.add(id)\n }\n for (const control of declared.controls ?? []) {\n claim('control', control.id)\n checkControl(control, problems)\n }\n for (const layer of declared.layers ?? []) claim('layer', layer.id)\n for (const metric of declared.metrics ?? []) {\n claim('metric', metric.id)\n if (metric.max !== undefined && !(finite(metric.max) && metric.max > 0)) problems.push(`metric \"${metric.id}\" needs a max > 0`)\n }\n return { ok: problems.length === 0, problems }\n}\n","/** The weather, light and ground as the world is right now. Written by whoever drives the weather, read by whoever reacts to it. */\nexport interface EnvironmentState {\n /** Rain in mm/h; 0 is dry. */\n readonly rain: number\n /** Wind in m/s along x and z, and its strength (the length of that vector). */\n readonly windX: number\n readonly windZ: number\n readonly windSpeed: number\n /** Strongest gust in m/s. */\n readonly gust: number\n /** Render fog far distance in metres. */\n readonly fogFar: number\n /** How far one can see for gameplay, in metres (not the render fog). */\n readonly visibility: number\n /** 0 is full daylight, 1 is the darkest night. */\n readonly nightFactor: number\n readonly temperatureC: number\n /** Wet ground, 0..1: rises with rain and dries after it stops. */\n readonly wetness: number\n}\n\nexport type EnvironmentKey = keyof EnvironmentState\n\n/** A calm dry day (the normal world, before anything went wrong). */\nexport const DEFAULT_ENVIRONMENT: EnvironmentState = {\n rain: 0,\n windX: 0,\n windZ: 0,\n windSpeed: 0,\n gust: 0,\n fogFar: 220,\n visibility: 220,\n nightFactor: 0,\n temperatureC: 20,\n wetness: 0,\n}\n\n/** The host's environment (`ModuleHost.environment`): a store the weather module writes to and the others read. */\nexport interface EnvironmentBus {\n get(): EnvironmentState\n /** Merges `patch` into the state; listeners hear it only when a value really changed. */\n set(patch: Partial<EnvironmentState>): void\n /** Hears every change with the keys that changed. Returns the unsubscribe function. */\n on(listener: (state: EnvironmentState, changed: readonly EnvironmentKey[]) => void): () => void\n}\n\n/** A plain store that implements the bus; the test room and tests use it, a game may bring its own. */\nexport function createEnvironmentBus(initial: Partial<EnvironmentState> = {}): EnvironmentBus {\n let state: EnvironmentState = { ...DEFAULT_ENVIRONMENT, ...initial }\n const listeners = new Set<(state: EnvironmentState, changed: readonly EnvironmentKey[]) => void>()\n return {\n get: () => state,\n set(patch) {\n const changed = (Object.keys(patch) as EnvironmentKey[]).filter((key) => patch[key] !== undefined && patch[key] !== state[key])\n if (changed.length === 0) return\n const next = { ...state } as { -readonly [Key in EnvironmentKey]: number }\n for (const key of changed) next[key] = patch[key] as number\n state = next\n for (const listener of [...listeners]) listener(state, changed)\n },\n on(listener) {\n listeners.add(listener)\n return () => void listeners.delete(listener)\n },\n }\n}\n","import { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nimport type { DeepPartial } from './registry'\n\n/** One category (kind) of items. Defaults and required contracts are inherited from the `extends` chain. */\nexport interface CategoryDef<TDefaults extends object = Record<string, unknown>> {\n readonly id: string\n /** Parent category id; the child inherits its defaults and its required contracts. */\n readonly extends?: string\n /** Field values every entry of this kind starts with; objects merge down the chain, arrays replace. */\n readonly defaults?: DeepPartial<TDefaults>\n /** Contract ids (`ContractChecker.id`) every entry of this kind, or of a descendant, must satisfy. */\n readonly requires?: readonly string[]\n /** An abstract category only groups: entries cannot declare it directly, only its descendants. */\n readonly abstract?: boolean\n}\n\n/** Where a checker is being run: the entry's kind and the chain of categories root first. */\nexport interface ContractContext {\n readonly kind: string\n readonly chain: readonly string[]\n}\n\n/** A named contract: returns the problems of an entry, each a short phrase like `missing leftover.despawnSeconds`. Empty means it holds. */\nexport interface ContractChecker<TEntry> {\n readonly id: string\n check(entry: TEntry, ctx: ContractContext): string[]\n}\n\nexport interface CategoryOptions {\n /** Categories added to the shipped ones; the same id replaces. */\n readonly extra?: readonly CategoryDef[]\n /** Partial changes by id, applied after `extra`. */\n readonly patches?: Readonly<Record<string, DeepPartial<CategoryDef> | Partial<CategoryDef>>>\n /** Ids taken out of the tree (their children are then reported by `check()`). */\n readonly remove?: readonly string[]\n}\n\nexport interface CategoryRegistry {\n get(id: string): CategoryDef | undefined\n has(id: string): boolean\n ids(): string[]\n /** Root first, ending at `id`. Throws on an unknown id, an unknown parent or a cycle. */\n chain(id: string): string[]\n /** `defaults` merged along the chain, root first, so the closest category wins. */\n defaults(id: string): Record<string, unknown>\n /** Union of `requires` along the chain, order kept, without duplicates. */\n requires(id: string): string[]\n /** True when `id` is `ancestorId` or descends from it. */\n isA(id: string, ancestorId: string): boolean\n /** Problems in the tree itself: duplicate ids, unknown `extends`, cycles. */\n check(): string[]\n}\n\nexport interface CategorizedOptions {\n /** Field of the entry that names its category. Default `kind`. */\n readonly kindField?: string\n /** Known gaps by entry id: problems starting with one of these texts go to `allowed`, so the list can shrink over time. */\n readonly allow?: Readonly<Record<string, readonly string[]>>\n}\n\nexport interface CategorizedReport {\n readonly ok: boolean\n readonly problems: string[]\n readonly allowed: string[]\n}\n\nexport const defineCategories = (defs: readonly CategoryDef[], options: CategoryOptions = {}): CategoryRegistry => {\n const problems: string[] = []\n const duplicates = (list: readonly CategoryDef[]): void => {\n const ids = new Set<string>()\n for (const def of list) {\n if (ids.has(def.id)) problems.push(`duplicate category \"${def.id}\"`)\n ids.add(def.id)\n }\n }\n duplicates(defs)\n duplicates(options.extra ?? [])\n\n const entries = mergeById(defs, options.extra)\n applyPatches(entries, options.patches)\n removeIds(entries, options.remove)\n\n const chain = (id: string): string[] => {\n const path: string[] = []\n let current: string | undefined = id\n while (current !== undefined) {\n const def = entries.get(current)\n if (!def) throw new Error(path.length === 0 ? `unknown category \"${current}\"` : `category \"${path[0]}\" has unknown parent \"${current}\"`)\n if (path.includes(current)) throw new Error(`category cycle: ${[...path, current].reverse().join(' -> ')}`)\n path.push(current)\n current = def.extends\n }\n return path.reverse()\n }\n\n const registry: CategoryRegistry = {\n get: (id) => entries.get(id),\n has: (id) => entries.has(id),\n ids: () => [...entries.keys()],\n chain,\n defaults: (id) => chain(id).reduce<Record<string, unknown>>((acc, ancestor) => deepMerge(acc, entries.get(ancestor)?.defaults), {}),\n requires: (id) => {\n const out: string[] = []\n for (const ancestor of chain(id)) for (const contract of entries.get(ancestor)?.requires ?? []) if (!out.includes(contract)) out.push(contract)\n return out\n },\n isA: (id, ancestorId) => {\n try {\n return chain(id).includes(ancestorId)\n } catch {\n return false\n }\n },\n check: () => {\n const found = [...problems]\n for (const [id, def] of entries) {\n if (def.extends !== undefined && !entries.has(def.extends)) found.push(`category \"${id}\" extends unknown \"${def.extends}\"`)\n else {\n try {\n chain(id)\n } catch (error) {\n const message = (error as Error).message\n // The same cycle is found from each of its members; the dedupe keeps one line per distinct message.\n if (message.startsWith('category cycle') && !found.includes(message)) found.push(message)\n }\n }\n }\n return found\n },\n }\n return registry\n}\n\n/** The entry with the defaults of its category underneath: the entry wins, objects merge, arrays replace. */\nexport const resolveEntry = <TEntry extends object>(registry: CategoryRegistry, entry: TEntry, kindField = 'kind'): TEntry =>\n deepMerge(registry.defaults(String((entry as Record<string, unknown>)[kindField])) as TEntry, entry)\n\n/** Checks that each entry has a known, concrete kind and satisfies every contract its chain requires. */\nexport const checkCategorized = <TEntry extends { readonly id: string }>(\n entries: readonly TEntry[],\n registry: CategoryRegistry,\n checkers: readonly ContractChecker<TEntry>[],\n options: CategorizedOptions = {},\n): CategorizedReport => {\n const kindField = options.kindField ?? 'kind'\n const byId = new Map(checkers.map((checker) => [checker.id, checker]))\n const problems: string[] = [...registry.check()]\n const allowed: string[] = []\n\n for (const entry of entries) {\n const kind = String((entry as Record<string, unknown>)[kindField])\n if (!registry.has(kind)) {\n problems.push(`\"${entry.id}\" has unknown kind \"${kind}\"`)\n continue\n }\n if (registry.get(kind)?.abstract) {\n problems.push(`\"${entry.id}\" has abstract kind \"${kind}\"`)\n continue\n }\n let path: string[]\n try {\n path = registry.chain(kind)\n } catch (error) {\n problems.push(`\"${entry.id}\" (${kind}): ${(error as Error).message}`)\n continue\n }\n const resolved = resolveEntry(registry, entry, kindField)\n for (const contract of registry.requires(kind)) {\n const owner = path.find((ancestor) => registry.get(ancestor)?.requires?.includes(contract)) ?? kind\n const checker = byId.get(contract)\n if (!checker) {\n problems.push(`kind \"${kind}\" requires contract \"${contract}\" but no checker is registered`)\n continue\n }\n const prefix = `\"${entry.id}\" (${kind}): `\n for (const problem of checker.check(resolved, { kind, chain: path })) {\n const text = `${prefix}${problem}, required by ${owner}`\n if ((options.allow?.[entry.id] ?? []).some((start) => problem.startsWith(start))) allowed.push(text)\n else problems.push(text)\n }\n }\n }\n return { ok: problems.length === 0, problems: [...new Set(problems)], allowed }\n}\n","/**\n * Where a drawn object comes from. Every builder of the kit that draws a piece (a car of the fleet, a house or a wall, a piece of furniture, a person, an\n * animal, a plant, an item, a weapon) marks the root it returns, and every renderer that draws for the room (effects, debris, liquids, the room itself)\n * marks its own roots, so a host can tell a piece of the kit from something drawn on the spot. Duck-typed on three.js objects (`userData`, `parent`,\n * `children`), so the contracts stay free of three.js.\n */\nexport const KIT_ORIGIN_KEY = 'kitOrigin'\n\n/** What drew an object: the package and the kind of piece (`vehicle`, `structure`, `furniture`, `person`... or `effect`, `room` for what is not a piece). */\nexport interface KitOrigin {\n readonly owner: string\n readonly kind: string\n /** The catalogue id of the piece, when it has one. */\n readonly id?: string\n /** Drawn as a simple stand-in shape because the kit has no model of the piece yet (an item with no team model): a model still to make. */\n readonly standIn?: boolean\n}\n\ninterface Node {\n userData?: Record<string, unknown>\n parent?: Node | null\n children?: readonly Node[]\n name?: string\n visible?: boolean\n isMesh?: boolean\n isPoints?: boolean\n isLine?: boolean\n isSprite?: boolean\n}\n\n/** Marks `object` as drawn by `origin.owner` and returns it. */\nexport function markKitOrigin<T>(object: T, origin: KitOrigin): T {\n const node = object as unknown as Node\n node.userData = node.userData ?? {}\n node.userData[KIT_ORIGIN_KEY] = { ...origin }\n return object\n}\n\n/** The origin of the object or of its nearest marked ancestor; null when nothing up the tree is marked. */\nexport function kitOriginOf(object: unknown): KitOrigin | null {\n for (let node = object as Node | null | undefined; node; node = node.parent) {\n const origin = node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined\n if (origin && typeof origin.owner === 'string') return origin\n }\n return null\n}\n\n/** A drawn thing that no builder of the kit marked: what was drawn on the spot. */\nexport interface UnmarkedDrawing {\n /** The names of the object and its named ancestors, outermost first. */\n readonly path: string\n readonly object: unknown\n}\n\n/** Every visible mesh, line, point cloud or sprite under `root` with no marked ancestor (`root` itself not counted as one). */\nexport function unmarkedDrawings(root: unknown): UnmarkedDrawing[] {\n const out: UnmarkedDrawing[] = []\n const pathOf = (node: Node): string => {\n const names: string[] = []\n for (let n: Node | null | undefined = node; n && n !== root; n = n.parent) if (n.name) names.push(n.name)\n return names.reverse().join(' > ') || '(no name)'\n }\n const walk = (node: Node, marked: boolean): void => {\n if (node.visible === false) return\n const here = marked || (node !== root && Boolean((node.userData?.[KIT_ORIGIN_KEY] as KitOrigin | undefined)?.owner))\n if (!here && (node.isMesh || node.isPoints || node.isLine || node.isSprite)) out.push({ path: pathOf(node), object: node })\n for (const child of node.children ?? []) walk(child, here)\n }\n walk(root as Node, false)\n return out\n}\n","/** A floor rectangle in an object's own space, metres (x across, z along). */\nexport interface Footprint {\n readonly minX: number\n readonly maxX: number\n readonly minZ: number\n readonly maxZ: number\n}\n\n/** What `footprintBlocker` reads of an object: its world matrix (three.js `Object3D`, duck-typed so the contracts stay free of three.js). */\nexport interface FootprintObject {\n readonly matrixWorld: { readonly elements: ArrayLike<number> }\n readonly parent?: unknown\n updateWorldMatrix?(updateParents: boolean, updateChildren: boolean): void\n}\n\n/**\n * The `ModuleHost.addBlocker` function of a solid object standing on the floor: the walking player stays out of `footprint`, a rectangle in the object's own space,\n * so the object blocks turned with it and follows it when it moves. An object out of the scene (no parent) blocks nothing.\n */\nexport function footprintBlocker(object: FootprintObject | (() => FootprintObject | null | undefined), footprint: Footprint | (() => Footprint | null | undefined)): (x: number, z: number, radius: number) => boolean {\n return (x, z, radius) => {\n const o = typeof object === 'function' ? object() : object\n const fp = typeof footprint === 'function' ? footprint() : footprint\n if (!o || !fp || !o.parent) return false\n o.updateWorldMatrix?.(true, false)\n const e = o.matrixWorld.elements\n // the world point in the object's own floor axes: its x and z columns are at right angles, so a projection on each (over its squared length, for a scale) inverts the matrix\n const dx = x - (e[12] as number)\n const dz = z - (e[14] as number)\n const ax = (e[0] as number) ** 2 + (e[1] as number) ** 2 + (e[2] as number) ** 2\n const az = (e[8] as number) ** 2 + (e[9] as number) ** 2 + (e[10] as number) ** 2\n const lx = (dx * (e[0] as number) + dz * (e[2] as number)) / (ax || 1)\n const lz = (dx * (e[8] as number) + dz * (e[10] as number)) / (az || 1)\n return lx > fp.minX - radius && lx < fp.maxX + radius && lz > fp.minZ - radius && lz < fp.maxZ + radius\n }\n}\n","/**\n * The sounds of a body (footsteps, jumps, landings, blows, hurt), as ids every package agrees on: the rule that knows what the body did\n * (`game-player`, a host's own player) names the sound, and the bank that knows how it sounds (`game-audio`'s `BODY_FOLEY_BANK`) answers it.\n * A game swaps the sound of an id (a sample instead of the synthesis) without touching the rule.\n */\n\n/** What the feet touch, by how it sounds (not by what it is made of: a wooden floor and a plywood board both sound `wood`). */\nexport const SURFACE_IDS = ['concrete', 'asphalt', 'wood', 'tile', 'dirt', 'grass', 'gravel', 'sand', 'metal', 'water', 'glass', 'carpet'] as const\nexport type SurfaceId = (typeof SURFACE_IDS)[number]\n\n/** The surface a body stands on when nobody says (the test room's floor is a concrete slab). */\nexport const DEFAULT_SURFACE: SurfaceId = 'concrete'\n\n/** How the feet move: a run hits harder and shorter; a crouched step is the walk, quieter. */\nexport const GAIT_IDS = ['walk', 'run'] as const\nexport type GaitId = (typeof GAIT_IDS)[number]\n\n/** How hard a landing is: `light` for a jump on the spot or a step down (up to about 5 m/s), `heavy` for a drop of more than a metre and a half. */\nexport const LANDING_IDS = ['light', 'heavy'] as const\nexport type LandingId = (typeof LANDING_IDS)[number]\n\n/** The fall speed (m/s) from which a landing is `heavy`. */\nexport const HEAVY_LANDING_SPEED = 5.5\n\nexport type FootstepSoundId = `footstep_${SurfaceId}_${GaitId}`\nexport type LandSoundId = `land_${SurfaceId}_${LandingId}`\n\n/**\n * How a blow is struck, by the body part or the tool that does it. `blade` stabs or slashes, `blunt` is a club, a bat, a pipe or a hammer, `chop` an\n * axe or a machete driven down.\n */\nexport const BLOW_IDS = ['punch', 'kick', 'shove', 'blade', 'blunt', 'chop'] as const\nexport type BlowId = (typeof BLOW_IDS)[number]\n\n/** What the blow meets: a body (flesh and bone, the head apart), something else (the material answers with its own impact), or nothing. */\nexport type BlowTarget = 'body' | 'head' | 'object' | 'air'\n\n/** The sounds of the body that are not a footstep or a landing. */\nexport const BODY_SOUND_IDS = [\n 'jump',\n 'cloth_rustle',\n 'body_fall',\n 'fall_damage',\n 'player_hurt',\n 'player_breath_run',\n 'player_death',\n 'bite',\n 'grab',\n 'punch_swing',\n 'punch_hit_body',\n 'punch_hit_face',\n 'punch_hit_object',\n 'kick_swing',\n 'kick_hit',\n 'kick_hit_object',\n 'shove_two_hands',\n 'knife_swing',\n 'knife_stab',\n 'knife_slash',\n 'knife_hit_object',\n 'blunt_swing',\n 'blunt_hit',\n 'blunt_hit_object',\n 'axe_swing',\n 'axe_chop',\n 'axe_hit_object',\n] as const\nexport type BodySoundId = (typeof BODY_SOUND_IDS)[number]\n\n/** Every sound of a body: what a host plays for the player, a survivor or a zombie. */\nexport type BodyFoleyId = FootstepSoundId | LandSoundId | BodySoundId\n\nexport const footstepSoundId = (surface: SurfaceId, gait: GaitId): FootstepSoundId => `footstep_${surface}_${gait}`\nexport const landSoundId = (surface: SurfaceId, fallSpeed: number): LandSoundId => `land_${surface}_${fallSpeed >= HEAVY_LANDING_SPEED ? 'heavy' : 'light'}`\n\n/** Every footstep and landing id, in the order of the surfaces. */\nexport const FOOTSTEP_SOUND_IDS: readonly FootstepSoundId[] = SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstepSoundId(surface, gait)))\nexport const LAND_SOUND_IDS: readonly LandSoundId[] = SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((landing): LandSoundId => `land_${surface}_${landing}`))\nexport const BODY_FOLEY_IDS: readonly BodyFoleyId[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n\nconst SWING: Readonly<Record<BlowId, BodySoundId | null>> = {\n punch: 'punch_swing',\n kick: 'kick_swing',\n // two hands pushed out do not whistle: the shove is one sound, at the contact\n shove: null,\n blade: 'knife_swing',\n blunt: 'blunt_swing',\n chop: 'axe_swing',\n}\n\n/**\n * Seconds from the start of a swing's sound to its loudest point (the limb or the tool at full speed, just before the contact). A host that knows when the\n * blow lands starts the swing this long before; one that does not plays the swing now and the hit this long after.\n */\nexport const SWING_LEAD_SECONDS: Readonly<Record<BlowId, number>> = { punch: 0.07, kick: 0.09, shove: 0, blade: 0.05, blunt: 0.1, chop: 0.11 }\n\n/** The swing through the air, played as the blow starts (`null`: the blow has none). */\nexport const swingSoundId = (blow: BlowId): BodySoundId | null => SWING[blow]\n\nconst HIT: Readonly<Record<BlowId, Readonly<Record<Exclude<BlowTarget, 'air'>, BodySoundId>>>> = {\n punch: { body: 'punch_hit_body', head: 'punch_hit_face', object: 'punch_hit_object' },\n kick: { body: 'kick_hit', head: 'kick_hit', object: 'kick_hit_object' },\n shove: { body: 'shove_two_hands', head: 'shove_two_hands', object: 'shove_two_hands' },\n blade: { body: 'knife_stab', head: 'knife_stab', object: 'knife_hit_object' },\n blunt: { body: 'blunt_hit', head: 'blunt_hit', object: 'blunt_hit_object' },\n chop: { body: 'axe_chop', head: 'axe_chop', object: 'axe_hit_object' },\n}\n\n/**\n * The body's side of a blow that lands: the knuckles, the shoe, the blade or the club meeting what it hit. On an object the material's own impact\n * plays too (the wood, the metal); this is the part that says it was a punch and not a shot.\n */\nexport const hitSoundId = (blow: BlowId, target: Exclude<BlowTarget, 'air'>): BodySoundId => HIT[blow][target]\n\n/**\n * The surface a material sounds like underfoot, by the material ids of `game-destruction` and `game-terrain` (unknown ids: `fallback`). Data, so\n * a game with its own materials passes its own table to `surfaceOfMaterial`.\n */\nexport const MATERIAL_SURFACES: Readonly<Record<string, SurfaceId>> = {\n concrete: 'concrete',\n mortar: 'concrete',\n stone: 'concrete',\n brick: 'concrete',\n 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 wax: 'dirt',\n flesh_fruit: 'dirt',\n turf: 'grass',\n foliage: 'grass',\n cactus: 'grass',\n gravel: 'gravel',\n sand: 'sand',\n steel: 'metal',\n cast_iron: 'metal',\n aluminium: 'metal',\n copper: 'metal',\n water: 'water',\n glass: 'glass',\n tempered_glass: 'glass',\n fabric: 'carpet',\n foam: 'carpet',\n leather: 'carpet',\n rubber: 'carpet',\n paper: 'carpet',\n}\n\nexport const isSurfaceId = (value: unknown): value is SurfaceId => typeof value === 'string' && (SURFACE_IDS as readonly string[]).includes(value)\n\n/** The surface of a material id; a surface id passes through. */\nexport function surfaceOfMaterial(material: string | undefined, table: Readonly<Record<string, SurfaceId>> = MATERIAL_SURFACES, fallback: SurfaceId = DEFAULT_SURFACE): SurfaceId {\n if (material === undefined) return fallback\n if (isSurfaceId(material)) return material\n return table[material] ?? fallback\n}\n","/**\n * @adatechnology/game-contracts: the contracts every game module (vehicles, furniture, plants, houses, weapons) depends on, and nothing else.\n * Types plus tiny pure checkers, no runtime dependencies. The default destruction world, the renderers and the test room are optional.\n */\nexport type {\n ChainDelay,\n Crack,\n DamageStage,\n DamageType,\n DebrisKind,\n Dent,\n DestructibleSpec,\n BlastOptions,\n BlastReport,\n ConfinementOptions,\n ExplosionChain,\n FragmentHitOptions,\n ShelterOptions,\n DestructionEvent,\n DestructionEventType,\n FluidKind,\n Fragment,\n FragmentMark,\n FractureStyle,\n BallisticExtras,\n Hit,\n HitIgnition,\n HitResult,\n Hole,\n JointKind,\n JointSpec,\n JointState,\n MaterialId,\n ObjectState,\n PartShape,\n PartSpec,\n PartBreach,\n PartState,\n PartStatus,\n PartUnits,\n Quat,\n RayHit,\n Reinforcement,\n TensionRebar,\n TunedMassDamper,\n WindExposure,\n WindState,\n PileSpec,\n SoilLayer,\n SoilProfile,\n SoilState,\n StructureRole,\n SurfaceLayer,\n ToolKind,\n Vec3,\n} from './destruction'\nexport type { BusyOptions, BusySink, BusyTask } from './busy'\nexport { blastShove, DEFAULT_BLAST_SHOVE } from './blast-shove'\nexport { bodyMass, FRAGMENT_COVER, KNOCK_CHEST, KNOCK_DOWN_SPEED, KNOCKED_DOWN_ANGLE, knockOf, stepKnock } from './blast-knock'\nexport { blastBodySpeed, bodyImpulse, DEFAULT_BLAST_IMPULSE, sideOnImpulse } from './blast-impulse'\nexport type { BlastImpulseOptions } from './blast-impulse'\nexport type { Knock } from './blast-knock'\nexport type { BlastShove, BlastShoveOptions, BlastSource } from './blast-shove'\nexport { IMPACT_CONTRACT, checkDestructible, checkHit } from './impact'\nexport type { CheckOptions, DestructibleImpl, ImpactContract, SurfaceRay, SurfaceRayHit } from './impact'\nexport type { CostOptions } from './impact-cost'\nexport { MISSING_BITS } from './body'\nexport type { BodyRegion, BodySlot, SegmentKind } from './body'\nexport { checkSpec } from './spec'\nexport type { CheckSpecOptions, SpecReport } from './spec'\nexport { shotToHit, shotExtras, useToHit } from './weapons'\nexport { DEFAULT_IGNITION_RULES, fillFactor, ignitionChance, resolveIgnitionRules, sparkTargetFactor } from './ignition'\nexport type { IgnitionRules } from './ignition'\nexport type { Shot, Use } from './weapons'\nexport type { ContainerSpec, ItemUseDef, LiquidId } from './fluids'\nexport { sealBlock, sealOpener } from './seal'\nexport type { SealBlock, SealSpec, SealState } from './seal'\nexport type { HandPose, HandTargetSource, HandTargets } from './hands'\nexport { TWIST_LIFT, twistStroke } from './twist'\nexport type { TwistOptions, TwistStroke } from './twist'\nexport type { EffectHandle, EffectRequest, EffectSink, Enclosure, EnclosureBox } from './effects'\nexport type { WarmUpProbes } from './warm-up'\nexport { checkAnimation } from './animation'\nexport type { AnimationClipSpec, AnimationEventSpec, AnimationKey, AnimationPose, ItemAnimationContract } from './animation'\nexport { STAGE_EVENT, TOOL_CLIP, checkToolClips, createToolClipPlayer, leadClipEvents, sampleClip, scaleClip, toolAnimationStep } from './tool-animation'\nexport type { ToolAnimationStep, ToolAnimator, ToolClipId, ToolClipPlayer, ToolClipPlayerOptions, ToolClipSet, ToolRig } from './tool-animation'\nexport { DEFERRED_PRIORITY, DEFERRED_QUEUE_ID, FRAME_PHASES, checkDeferredQueue } from './frame'\nexport type { DeferredQueue, DeferredQueueOptions, DeferredQueueReport, FramePhase } from './frame'\nexport type { FrameOptions, AreaPlacement, GroundLayout, GroundZone, HostEvent, HostGraphics, HostTool, HostToolAttachment, ModuleArea, ModuleHost, ModuleView, ModuleItemFluid, ModuleItemSeal, ModuleScenario, PlayerState, ItemSeat, ItemSounds, TestableItem, TestableModule, Thumbnail, ToolCommand, ToolCommandResult, HostReach } from './module'\nexport { applyPatches, deepMerge, mergeById, removeIds } from './registry'\nexport type { DeepPartial } from './registry'\nimport { resetWarnOnce as resetWarnOnceForTests } from './warn'\n\nexport { warnOnce } from './warn'\n/** @deprecated Import it from `@adatechnology/game-contracts/testing`. */\nexport const resetWarnOnce = resetWarnOnceForTests\nexport { checkBench } from './bench'\nexport type {\n ActionControl,\n BenchChange,\n BenchDeclaration,\n BenchReport,\n BenchSheet,\n BooleanControl,\n ChoiceControl,\n ChoiceOption,\n ControlPatch,\n ControlValue,\n ModuleBench,\n ModuleControl,\n ModuleLayer,\n ModuleMetric,\n NumberControl,\n} from './bench'\nexport type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from './audio'\nexport { DEFAULT_ENVIRONMENT, createEnvironmentBus } from './environment'\nexport type { EnvironmentBus, EnvironmentKey, EnvironmentState } from './environment'\nexport { checkCategorized, defineCategories, resolveEntry } from './categories'\nexport type { CategorizedOptions, CategorizedReport, CategoryDef, CategoryOptions, CategoryRegistry, ContractChecker, ContractContext } from './categories'\nexport { KIT_ORIGIN_KEY, kitOriginOf, markKitOrigin, unmarkedDrawings } from './origin'\nexport type { KitOrigin, UnmarkedDrawing } from './origin'\nexport { footprintBlocker } from './footprint'\nexport type { Footprint, FootprintObject } from './footprint'\nexport {\n BLOW_IDS,\n BODY_FOLEY_IDS,\n BODY_SOUND_IDS,\n DEFAULT_SURFACE,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n HEAVY_LANDING_SPEED,\n LANDING_IDS,\n LAND_SOUND_IDS,\n MATERIAL_SURFACES,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n hitSoundId,\n isSurfaceId,\n landSoundId,\n surfaceOfMaterial,\n swingSoundId,\n} from './foley'\nexport type { BlowId, BlowTarget, BodyFoleyId, BodySoundId, FootstepSoundId, GaitId, LandSoundId, LandingId, SurfaceId } from './foley'\n","import { DEFERRED_QUEUE_ID } from '@adatechnology/game-contracts'\nimport type { DeferredQueue } from '@adatechnology/game-contracts'\n\n/** A sound waiting to be built: `run` builds it, `drop` gives its voice back when it waited too long to still make sense. */\nexport type StartJob = { readonly queuedAt: number; run(): void; drop(): void }\n\nexport type StartQueueOptions = {\n /** Most milliseconds of main-thread work one task spends building voices (at least one voice is always built). Default 2. */\n readonly budgetMs?: number\n /** A voice still waiting after this many milliseconds is dropped instead of starting late. Default 250. */\n readonly maxLatencyMs?: number\n}\n\nexport type StartQueue = {\n push(job: Omit<StartJob, 'queuedAt'>): void\n clear(): void\n readonly size: number\n /** The same queue as a `DeferredQueue` for a shared frame budget. Asking for it changes nothing: the queue drains by itself until a budget attaches it. */\n deferredQueue?(): DeferredQueue\n}\n\nconst nowMs = (): number => (typeof performance === 'undefined' ? Date.now() : performance.now())\n\nfunction scheduleTask(task: () => void): void {\n if (typeof MessageChannel === 'undefined') {\n setTimeout(task, 0)\n return\n }\n const channel = new MessageChannel()\n channel.port1.onmessage = () => {\n channel.port1.close()\n task()\n }\n channel.port2.postMessage(0)\n}\n\n/** Builds voices in small timed slices between frames, so a burst (an explosion's debris, glass and metal) never lands inside one frame. */\n/** The queue this package makes always has its `deferredQueue`; a third-party `StartQueue` may leave it out. */\nexport type OwnStartQueue = StartQueue & { deferredQueue(): DeferredQueue }\n\nexport function createStartQueue(options: StartQueueOptions = {}): OwnStartQueue {\n const budgetMs = options.budgetMs ?? 2\n const maxLatencyMs = options.maxLatencyMs ?? 250\n let jobs: StartJob[] = []\n let scheduled = false\n // true once a frame budget owns the draining: nothing schedules a task by itself\n let attached = false\n\n const runNext = (): void => {\n const job = jobs.shift() as StartJob\n if (nowMs() - job.queuedAt > maxLatencyMs) job.drop()\n else job.run()\n }\n\n const drain = (): void => {\n scheduled = false\n if (attached) return\n const began = nowMs()\n while (jobs.length > 0) {\n runNext()\n if (nowMs() - began >= budgetMs) break\n }\n if (jobs.length > 0) schedule()\n }\n\n const schedule = (): void => {\n if (scheduled || attached) return\n scheduled = true\n scheduleTask(drain)\n }\n\n const queue: OwnStartQueue = {\n push(job) {\n jobs.push({ ...job, queuedAt: nowMs() })\n schedule()\n },\n clear() {\n for (const job of jobs) job.drop()\n jobs = []\n },\n get size() {\n return jobs.length\n },\n deferredQueue: () => deferredQueue,\n }\n\n const deferredQueue: DeferredQueue = {\n id: DEFERRED_QUEUE_ID.AUDIO_VOICES,\n pending: () => jobs.length,\n run(deadline, clock) {\n let ran = 0\n while (jobs.length > 0) {\n runNext()\n ran++\n if (clock() >= deadline) break\n }\n return ran\n },\n flush() {\n while (jobs.length > 0) runNext()\n },\n attach() {\n attached = true\n },\n detach() {\n attached = false\n if (jobs.length > 0) schedule()\n },\n }\n return queue\n}\n","// The game's routines (jogo.js), one builder each: the nodes are created, set and wired in the routine's own order, so the trace of a plan\n// matches the trace of the team function. The level is already in the envelope; every builder connects straight to the bus.\nimport type { PlannedFilter, PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nconst end = (layer: PlannedLayer, start: number): number => start + layer.duration + layer.tail\nconst firstFilter = (layer: PlannedLayer): PlannedFilter | undefined => layer.filters?.bank[0]\nconst offsetOf = (layer: PlannedLayer): number => (layer.source.kind === 'noise' ? layer.source.offset : 0)\n\nfunction setFilter(node: BiquadFilterNode, filter: PlannedFilter | undefined, time: number): void {\n if (!filter) return\n node.type = filter.type\n assign(node.frequency, filter.frequency, time)\n if (filter.q !== undefined) node.Q.value = filter.q\n}\n\n/** `sfx` (L62089): gain to the bus first, then the noise, its lowpass, the envelope, and a random start in the noise. */\nexport function realizeBurst(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const gain = context.createGain()\n gain.connect(target.output)\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filter = context.createBiquadFilter()\n source.connect(filter)\n filter.connect(gain)\n setFilter(filter, firstFilter(layer), time)\n applyEnvelope(gain.gain, layer.envelope, time)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n return voiceOf([source])\n}\n\n/** `grito` (L62128): noise through a parallel formant bank (each band with its own level), a gain LFO for roughness. */\nexport function realizeScream(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const gain = context.createGain()\n gain.connect(target.output)\n for (const band of layer.filters?.bank ?? []) {\n const filter = context.createBiquadFilter()\n filter.type = band.type\n if (band.q !== undefined) filter.Q.value = band.q\n assign(filter.frequency, band.frequency, time)\n rampTo(filter.frequency, band.frequency, time)\n const level = context.createGain()\n level.gain.value = band.level ?? 1\n source.connect(filter)\n filter.connect(level)\n level.connect(gain)\n }\n const sources: AudioScheduledSourceNode[] = [source]\n const lfos = layer.modulators.map((modulator) => {\n const lfo = context.createOscillator()\n const depth = context.createGain()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = modulator.rate\n depth.gain.value = modulator.depth\n lfo.connect(depth)\n depth.connect(gain.gain)\n return lfo\n })\n applyEnvelope(gain.gain, layer.envelope, time)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n for (const lfo of lfos) {\n lfo.start(time)\n lfo.stop(end(layer, time))\n sources.push(lfo)\n }\n return voiceOf(sources)\n}\n\n/** `voz` (L62143): oscillator → bandpass → gain; the filter frequency is set after the pitch sweep. */\nexport function realizeGroan(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n const gain = context.createGain()\n const filter = context.createBiquadFilter()\n const band = firstFilter(layer)\n if (layer.source.kind === 'osc') oscillator.type = layer.source.wave\n if (band) {\n filter.type = band.type\n if (band.q !== undefined) filter.Q.value = band.q\n }\n if (layer.source.kind === 'osc') {\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n if (band) assign(filter.frequency, band.frequency, time)\n applyEnvelope(gain.gain, layer.envelope, time)\n oscillator.connect(filter)\n filter.connect(gain)\n gain.connect(target.output)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return voiceOf([oscillator])\n}\n\n/** `boom` (L68278): one oscillator sweeping down into a gain. */\nexport function realizeBoom(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n const gain = context.createGain()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n applyEnvelope(gain.gain, layer.envelope, time)\n oscillator.connect(gain)\n gain.connect(target.output)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return voiceOf([oscillator])\n}\n\n/** `chiado` (L69998): gain, noise and bandpass created first, then set, then wired. */\nexport function realizeStatic(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const gain = context.createGain()\n const source = context.createBufferSource()\n const filter = context.createBiquadFilter()\n source.buffer = target.noise()\n setFilter(filter, firstFilter(layer), time)\n applyEnvelope(gain.gain, layer.envelope, time)\n source.connect(filter)\n filter.connect(gain)\n gain.connect(target.output)\n source.start(time, offsetOf(layer))\n source.stop(end(layer, time))\n return voiceOf([source])\n}\n\n/** `buzina` (L70272): one oscillator per layer into one gain with the first layer's envelope. */\nexport function realizeChord(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layers = plan.layers\n const oscillators = layers.map(() => context.createOscillator())\n const gain = context.createGain()\n // the team writes `o.type = o2.type = 'square'`, which assigns right to left\n for (let index = layers.length - 1; index >= 0; index--) {\n const source = (layers[index] as PlannedLayer).source\n if (source.kind === 'osc') (oscillators[index] as OscillatorNode).type = source.wave\n }\n layers.forEach((layer, index) => {\n if (layer.source.kind === 'osc') assign((oscillators[index] as OscillatorNode).frequency, layer.source.frequency, target.time + layer.at)\n })\n applyEnvelope(gain.gain, (layers[0] as PlannedLayer).envelope, target.time + (layers[0] as PlannedLayer).at)\n for (const oscillator of oscillators) oscillator.connect(gain)\n gain.connect(target.output)\n layers.forEach((layer, index) => (oscillators[index] as OscillatorNode).start(target.time + layer.at))\n layers.forEach((layer, index) => (oscillators[index] as OscillatorNode).stop(end(layer, target.time + layer.at)))\n return voiceOf(oscillators)\n}\n\n/**\n * `bichoSom` (L66625): gain and filter are created before the level is checked (a silent plan stops there), then each repeat is an oscillator\n * with its own envelope into the shared filter, whose frequency and Q are set again on every repeat.\n */\nexport function realizeCalls(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const gain = context.createGain()\n const filter = context.createBiquadFilter()\n if (plan.silent) return voiceOf([])\n const band = firstFilter(plan.layers[0] as PlannedLayer)\n if (band) filter.type = band.type\n filter.connect(gain)\n gain.connect(target.output)\n const oscillators = plan.layers.map((layer) => {\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n if (band) {\n assign(filter.frequency, band.frequency, time)\n if (band.q !== undefined) filter.Q.value = band.q\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope)\n envelope.connect(filter)\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return oscillator\n })\n return voiceOf(oscillators)\n}\n","// The art scene's primitives (cena L1319–1328, L1369): `sNoise`, `sTone` and `voice`, each layer with its own output stage (`outAt`: distance\n// gain, pan, reverb send), and the siren straight to the bus. Built in the team's order so the traces match node for node.\nimport type { PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, filterNode, gainNode, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nconst end = (layer: PlannedLayer, start: number): number => start + layer.duration + layer.tail\n\n/** `outAt`: the layer level, the stereo panner when the plan pans and the context has one, the bus, then the reverb send. */\nfunction outputStage(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): GainNode {\n const { context } = target\n const level = gainNode(context, layer.level)\n let node: AudioNode = level\n if (plan.pan !== undefined && typeof context.createStereoPanner === 'function') {\n const panner = context.createStereoPanner()\n panner.pan.value = plan.pan\n level.connect(panner)\n node = panner\n }\n node.connect(target.output)\n if (layer.wet && target.wet) {\n const send = gainNode(context, layer.wet)\n node.connect(send)\n send.connect(target.wet)\n }\n return level\n}\n\nfunction realizeNoiseLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const { context } = target\n const time = target.time + layer.at\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filters = (layer.filters?.bank ?? []).map((filter) => {\n const node = filterNode(context, filter, time)\n rampTo(node.frequency, filter.frequency, time)\n return node\n })\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n source.start(time, layer.source.kind === 'noise' ? layer.source.offset : 0)\n source.stop(end(layer, time))\n return [source]\n}\n\nfunction realizeToneLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const { context } = target\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n oscillator.start(time)\n oscillator.stop(end(layer, time))\n return [oscillator]\n}\n\nfunction realizeVoiceLayer(plan: SoundPlan, layer: PlannedLayer, target: RealizeTarget): AudioScheduledSourceNode[] {\n const source = layer.source\n if (source.kind !== 'formant_voice') return []\n const { context } = target\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n oscillator.type = source.wave\n assign(oscillator.frequency, source.frequency, time)\n rampTo(oscillator.frequency, source.frequency, time)\n const vibrato = context.createOscillator()\n vibrato.frequency.value = source.vibrato.rate\n const vibratoDepth = gainNode(context, source.vibrato.depth)\n vibrato.connect(vibratoDepth)\n vibratoDepth.connect(oscillator.frequency)\n const formants = source.formants.map((formant) => filterNode(context, { type: 'bandpass', frequency: { value: formant.frequency }, q: formant.q }, time))\n const breath = noiseSource(target, true)\n const breathBand = filterNode(context, { type: 'bandpass', frequency: { value: source.breath.frequency }, q: source.breath.q }, time)\n const breathLevel = gainNode(context, source.breath.gain)\n const mix = gainNode(context, source.mix)\n for (const formant of formants) oscillator.connect(formant)\n breath.connect(breathBand)\n breathBand.connect(breathLevel)\n for (const formant of formants) formant.connect(mix)\n breathLevel.connect(mix)\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n mix.connect(envelope)\n envelope.connect(outputStage(plan, layer, target))\n const stop = end(layer, time)\n oscillator.start(time)\n vibrato.start(time)\n breath.start(time, source.breath.offset)\n oscillator.stop(stop)\n vibrato.stop(stop)\n breath.stop(stop)\n return [oscillator, vibrato, breath]\n}\n\n/** Every layer in order, each with its own output stage. */\nexport function realizeLayered(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const sources = plan.layers.flatMap((layer) => {\n if (layer.source.kind === 'noise') return realizeNoiseLayer(plan, layer, target)\n if (layer.source.kind === 'osc') return realizeToneLayer(plan, layer, target)\n return realizeVoiceLayer(plan, layer, target)\n })\n return voiceOf(sources)\n}\n\n/** The siren: oscillator with a frequency LFO, envelope, lowpass, straight to the bus with a reverb send. */\nexport function realizeSiren(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const { context } = target\n const layer = plan.layers[0] as PlannedLayer\n const time = target.time + layer.at\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const depths = layer.modulators.map((modulator) => {\n const lfo = context.createOscillator()\n if (modulator.wave) lfo.type = modulator.wave\n lfo.frequency.value = modulator.rate\n const depth = gainNode(context, modulator.depth)\n lfo.connect(depth)\n if (modulator.target === 'frequency') depth.connect(oscillator.frequency)\n return { lfo, depth, target: modulator.target }\n })\n const lfos = depths.map(({ lfo }) => lfo)\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n for (const { depth, target: modulated } of depths) if (modulated === 'gain') depth.connect(envelope.gain)\n const filters = (layer.filters?.bank ?? []).map((filter) => filterNode(context, filter, time))\n let tail: AudioNode = oscillator\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope)\n envelope.connect(target.output)\n if (layer.wet && target.wet) {\n const send = gainNode(context, layer.wet)\n envelope.connect(send)\n send.connect(target.wet)\n }\n const stop = end(layer, time)\n oscillator.start(time)\n for (const lfo of lfos) lfo.start(time)\n oscillator.stop(stop)\n for (const lfo of lfos) lfo.stop(stop)\n return voiceOf([oscillator, ...lfos])\n}\n","// The weapon audio of the kit (`weapons-three`, first written against raw WebAudio): per layer, either a noise burst (source, filter, envelope gain)\n// or an oscillator (oscillator, envelope gain), created in that order and chained straight to the bus. The level is already in the envelope.\nimport type { PlannedLayer, SoundPlan } from '../plan'\nimport { applyEnvelope, assign, filterNode, noiseSource, rampTo, voiceOf } from './nodes'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\n\nfunction noiseLayer(layer: PlannedLayer, target: RealizeTarget, time: number): AudioScheduledSourceNode {\n const { context } = target\n const source = noiseSource(target, layer.source.kind === 'noise' && layer.source.loop)\n const filters = (layer.filters?.bank ?? []).map((filter) => filterNode(context, filter, time))\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n let tail: AudioNode = source\n for (const filter of filters) tail = tail.connect(filter)\n tail.connect(envelope).connect(target.output)\n source.start(time, layer.source.kind === 'noise' ? layer.source.offset : 0)\n source.stop(time + layer.duration + layer.tail)\n return source\n}\n\nfunction toneLayer(layer: PlannedLayer, target: RealizeTarget, time: number): AudioScheduledSourceNode {\n const { context } = target\n const oscillator = context.createOscillator()\n if (layer.source.kind === 'osc') {\n oscillator.type = layer.source.wave\n assign(oscillator.frequency, layer.source.frequency, time)\n rampTo(oscillator.frequency, layer.source.frequency, time)\n }\n const envelope = context.createGain()\n applyEnvelope(envelope.gain, layer.envelope, time)\n oscillator.connect(envelope).connect(target.output)\n oscillator.start(time)\n oscillator.stop(time + layer.duration + layer.tail)\n return oscillator\n}\n\n/** One noise burst or one tone per layer, in the order written. */\nexport function realizeWeapon(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n const sources = plan.layers.map((layer) => {\n const time = target.time + layer.at\n return layer.source.kind === 'noise' ? noiseLayer(layer, target, time) : toneLayer(layer, target, time)\n })\n return voiceOf(sources)\n}\n","import type { SoundPlan } from '../plan'\nimport type { BuildOrder } from '../recipe'\nimport type { RealizedVoice, RealizeTarget } from './nodes'\nimport { realizeBoom, realizeBurst, realizeCalls, realizeChord, realizeGroan, realizeScream, realizeStatic } from './realize-game'\nimport { realizeLayered, realizeSiren } from './realize-layered'\nimport { realizeWeapon } from './realize-weapon'\n\nconst BUILDERS: Readonly<Record<BuildOrder, (plan: SoundPlan, target: RealizeTarget) => RealizedVoice>> = {\n layered: realizeLayered,\n burst: realizeBurst,\n scream: realizeScream,\n groan: realizeGroan,\n boom: realizeBoom,\n static: realizeStatic,\n chord: realizeChord,\n calls: realizeCalls,\n siren: realizeSiren,\n weapon: realizeWeapon,\n}\n\n/** Builds a plan's nodes on `target`, in the node order of the team routine its `order` names. */\nexport function realize(plan: SoundPlan, target: RealizeTarget): RealizedVoice {\n return BUILDERS[plan.order](plan, target)\n}\n","import type { PlannedAutomation, PlannedFilter, PlannedLayer, PlannedModulator, PlannedSource, SoundPlan } from './plan'\nimport type { SoundSet } from './recipe'\n\nconst tuneAutomation = (automation: PlannedAutomation, rate: number): PlannedAutomation => {\n const tuned: { -readonly [K in keyof PlannedAutomation]: PlannedAutomation[K] } = { ...automation }\n if (automation.value !== undefined) tuned.value = automation.value * rate\n if (automation.from !== undefined) tuned.from = automation.from * rate\n if (automation.to !== undefined) tuned.to = automation.to * rate\n if (automation.at !== undefined) tuned.at = automation.at / rate\n return tuned\n}\n\nconst tuneFilter = (filter: PlannedFilter, rate: number): PlannedFilter => ({ ...filter, frequency: tuneAutomation(filter.frequency, rate) })\n\nconst tuneSource = (source: PlannedSource, rate: number): PlannedSource => {\n switch (source.kind) {\n case 'noise':\n return source\n case 'osc':\n return { ...source, frequency: tuneAutomation(source.frequency, rate) }\n case 'formant_voice':\n return {\n ...source,\n frequency: tuneAutomation(source.frequency, rate),\n formants: source.formants.map((formant) => ({ ...formant, frequency: formant.frequency * rate })),\n breath: { ...source.breath, frequency: source.breath.frequency * rate },\n }\n }\n}\n\nconst tuneModulator = (modulator: PlannedModulator, rate: number): PlannedModulator => ({\n ...modulator,\n rate: modulator.rate * rate,\n ...(modulator.target === 'frequency' ? { depth: modulator.depth * rate } : {}),\n})\n\nconst tuneLayer = (layer: PlannedLayer, rate: number): PlannedLayer => ({\n ...layer,\n at: layer.at / rate,\n duration: layer.duration / rate,\n tail: layer.tail / rate,\n source: tuneSource(layer.source, rate),\n ...(layer.filters ? { filters: { ...layer.filters, bank: layer.filters.bank.map((filter) => tuneFilter(filter, rate)) } } : {}),\n modulators: layer.modulators.map((modulator) => tuneModulator(modulator, rate)),\n envelope: layer.envelope.map((point) => ({ ...point, time: point.time / rate })),\n})\n\n/**\n * A plan played faster or slower, as a tape would: every frequency (tones, filters, formants, LFOs) times `rate`, every time divided by it. Noise\n * has no pitch of its own, so its colour moves with its filters. `rate` 1 gives the plan back.\n */\nexport function retunePlan(plan: SoundPlan, rate: number): SoundPlan {\n if (rate === 1 || !(rate > 0)) return plan\n return { ...plan, length: plan.length / rate, layers: plan.layers.map((layer) => tuneLayer(layer, rate)) }\n}\n\n/** Remembers the last variant of each set, so the next draw never repeats it. */\nexport type SetPicker = {\n /** The variant to play and its rate, drawn from `random` (two numbers: the variant, then the rate). */\n pick(set: SoundSet, random: () => number): { readonly id: string; readonly rate: number }\n /** Forget the last variants (a fresh scene). */\n reset(): void\n}\n\nexport function createSetPicker(): SetPicker {\n const last = new Map<string, number>()\n return {\n pick(set, random) {\n const count = set.variants.length\n const previous = last.get(set.id)\n let index: number\n if (count === 1) index = 0\n else if (set.repeat || previous === undefined) index = Math.min(count - 1, Math.floor(random() * count))\n else {\n // one of the others: draw among count − 1 and skip the previous\n index = Math.min(count - 2, Math.floor(random() * (count - 1)))\n if (index >= previous) index += 1\n }\n last.set(set.id, index)\n const [min, max] = set.rate ?? [1, 1]\n const rate = min === max ? min : min + random() * (max - min)\n return { id: set.variants[index] as string, rate }\n },\n reset: () => last.clear(),\n }\n}\n","/**\n * Decoded sample buffers by url. Files load once (concurrent asks share the same promise), decode on the engine's context and stay until `clear`.\n * The bytes come from a `SampleLoader`: `fetch` by default, or anything else (a single-file page passes the files inlined as base64).\n */\n\n/** Gets the bytes of a file. */\nexport type SampleLoader = (url: string) => Promise<ArrayBuffer>\n\nexport type SampleStatus = 'none' | 'loading' | 'ready' | 'failed'\n\nexport type SampleLoadReport = { readonly loaded: readonly string[]; readonly failed: readonly { readonly url: string; readonly error: string }[] }\n\nexport type SampleStore = {\n status(url: string): SampleStatus\n /** The decoded buffer, once ready. */\n buffer(url: string): AudioBuffer | undefined\n /** Whether every url is ready. */\n ready(urls: readonly string[]): boolean\n load(urls: readonly string[], context: BaseAudioContext): Promise<SampleLoadReport>\n /** Seconds of the decoded file, or `undefined` while not ready. */\n seconds(url: string): number | undefined\n clear(): void\n}\n\n/** `fetch` relative to `baseUrl` (default the page). */\nexport function fetchLoader(baseUrl?: string): SampleLoader {\n return async (url) => {\n const target = baseUrl ? new URL(url, baseUrl).toString() : url\n const response = await fetch(target)\n if (!response.ok) throw new Error(`${response.status} ${response.statusText} for ${target}`)\n return response.arrayBuffer()\n }\n}\n\n/** Bytes of files given inline as base64 (or `data:` urls), by url. */\nexport function inlineLoader(files: Readonly<Record<string, string>>): SampleLoader {\n return async (url) => {\n const text = files[url]\n if (text === undefined) throw new Error(`no inline file for ${url}`)\n const base64 = text.startsWith('data:') ? text.slice(text.indexOf(',') + 1) : text\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)\n return bytes.buffer\n }\n}\n\nconst decode = (context: BaseAudioContext, bytes: ArrayBuffer): Promise<AudioBuffer> =>\n new Promise((resolve, reject) => {\n // the callback form also covers old Safari, where decodeAudioData returns no promise\n const result = context.decodeAudioData(bytes, resolve, reject) as Promise<AudioBuffer> | undefined\n result?.catch?.(reject)\n })\n\nexport function createSampleStore(loader: SampleLoader = fetchLoader()): SampleStore {\n const buffers = new Map<string, AudioBuffer>()\n const pending = new Map<string, Promise<AudioBuffer>>()\n const failed = new Map<string, string>()\n let generation = 0\n\n const loadOne = (url: string, context: BaseAudioContext): Promise<AudioBuffer> => {\n const existing = buffers.get(url)\n if (existing) return Promise.resolve(existing)\n const inFlight = pending.get(url)\n if (inFlight) return inFlight\n const started = generation\n failed.delete(url)\n const promise = loader(url)\n .then((bytes) => decode(context, bytes))\n .then((buffer) => {\n if (started === generation) buffers.set(url, buffer)\n return buffer\n })\n .catch((error: unknown) => {\n if (started === generation) failed.set(url, error instanceof Error ? error.message : String(error))\n throw error\n })\n .finally(() => {\n if (pending.get(url) === promise) pending.delete(url)\n })\n pending.set(url, promise)\n return promise\n }\n\n return {\n status(url) {\n if (buffers.has(url)) return 'ready'\n if (pending.has(url)) return 'loading'\n if (failed.has(url)) return 'failed'\n return 'none'\n },\n buffer: (url) => buffers.get(url),\n ready: (urls) => urls.every((url) => buffers.has(url)),\n seconds: (url) => buffers.get(url)?.duration,\n async load(urls, context) {\n const results = await Promise.allSettled(urls.map((url) => loadOne(url, context)))\n const loaded: string[] = []\n const errors: { url: string; error: string }[] = []\n results.forEach((result, index) => {\n const url = urls[index] as string\n if (result.status === 'fulfilled') loaded.push(url)\n else errors.push({ url, error: result.reason instanceof Error ? result.reason.message : String(result.reason) })\n })\n return { loaded, failed: errors }\n },\n clear() {\n generation++\n buffers.clear()\n pending.clear()\n failed.clear()\n },\n }\n}\n","import { OPEN_CUTOFF } from '../sample'\nimport type { SamplePlan } from '../sample'\nimport { gainNode, voiceOf } from './nodes'\nimport type { RealizedVoice } from './nodes'\n\nexport type SampleTarget = {\n readonly context: BaseAudioContext\n readonly output: AudioNode\n readonly buffer: (url: string) => AudioBuffer | undefined\n readonly time: number\n}\n\n/** A sample voice can also be faded out (the choke of its sound). */\nexport type RealizedSampleVoice = RealizedVoice & { fade(at: number, seconds: number): void }\n\n/**\n * Builds a sample plan: each layer is a buffer source at the planned rate with its own gain, the layers meet in one voice gain (the choke fades it),\n * one lowpass (left out when open) and one stereo panner (when the plan has a pan), then the bus. A layer whose buffer is not loaded is skipped.\n */\nexport function realizeSample(plan: SamplePlan, target: SampleTarget): RealizedSampleVoice {\n const context = target.context\n let head: AudioNode = target.output\n if (plan.pan !== undefined && typeof context.createStereoPanner === 'function') {\n const panner = context.createStereoPanner()\n panner.pan.value = plan.pan\n panner.connect(head)\n head = panner\n }\n if (plan.cutoff < OPEN_CUTOFF) {\n const lowpass = context.createBiquadFilter()\n lowpass.type = 'lowpass'\n lowpass.frequency.value = plan.cutoff\n lowpass.Q.value = 0.7\n lowpass.connect(head)\n head = lowpass\n }\n const voice = context.createGain()\n voice.connect(head)\n head = voice\n const sources: AudioBufferSourceNode[] = []\n for (const layer of plan.layers) {\n const buffer = target.buffer(layer.url)\n if (!buffer) continue\n const source = context.createBufferSource()\n source.buffer = buffer\n source.playbackRate.value = layer.rate\n const gain = gainNode(context as AudioContext, layer.gain)\n source.connect(gain)\n gain.connect(head)\n source.start(target.time + layer.at)\n sources.push(source)\n }\n const realized = voiceOf(sources)\n return {\n ...realized,\n fade(at, seconds) {\n voice.gain.setValueAtTime(1, at)\n voice.gain.linearRampToValueAtTime(0, at + seconds)\n for (const source of sources) {\n try {\n source.stop(at + seconds)\n } catch {\n // already stopped\n }\n }\n },\n }\n}\n\n/** Seconds a sample plan lasts with its buffers (the longest layer, at its rate). */\nexport function sampleLength(plan: SamplePlan, seconds: (url: string) => number | undefined): number {\n let length = 0\n for (const layer of plan.layers) length = Math.max(length, layer.at + (seconds(layer.url) ?? 0) / layer.rate)\n return length\n}\n","import type { DeferredQueue, Vec3 } from '@adatechnology/game-contracts'\n\nimport { createSoundRegistry } from '../bank'\nimport type { SoundRegistry } from '../bank'\nimport { falloffGain, isSilent } from '../falloff'\nimport { DEFAULT_LISTENER, listenerDistance } from '../listener'\nimport type { DistanceMode, Listener } from '../listener'\nimport { DEFAULT_MIX, busGain, resolveMix } from '../mix'\nimport type { BusSetting, MixProfile } from '../mix'\nimport { planSound } from '../plan'\nimport type { PlanInput, SoundPlan } from '../plan'\nimport type { BusId, SoundBank, SoundRecipe } from '../recipe'\nimport { createRng, streamFor } from '../rng'\nimport { busPriority, createVoiceManager } from '../voices'\nimport type { VoiceGroup } from '../voices'\nimport { buildChain } from './chain'\nimport type { MixChain } from './chain'\nimport { globalContext, unlockContext } from './context'\nimport { createLoopHandle } from './engine-loop'\nimport type { AudioLoopHandle, LoopHost } from './engine-loop'\nimport { createSampleLoopHandle } from './sample-loop'\nimport { createNoiseStore, noiseBuffer, prepareNoise } from './engine-noise'\nimport type { NoiseStore } from './engine-noise'\nimport type { RealizedVoice } from './nodes'\nimport { createStartQueue } from './engine-queue'\nimport type { StartQueueOptions } from './engine-queue'\nimport { realize } from './realize'\nimport { createSetPicker, retunePlan } from '../variation'\nimport { planSample, sampleUrls } from '../sample'\nimport type { SampleEnvironment, SampleMemory, SamplePlan, SampleSound } from '../sample'\nimport { createSampleStore, fetchLoader } from './sample-store'\nimport type { SampleLoadReport, SampleLoader, SampleStatus } from './sample-store'\nimport { realizeSample, sampleLength } from './realize-sample'\nimport type { RealizedSampleVoice } from './realize-sample'\n\nexport type PlayOptions = {\n readonly position?: Vec3\n /** Meters; overrides `position` for the distance (not for the pan). */\n readonly distance?: number\n readonly volume?: number\n readonly params?: Readonly<Record<string, number>>\n /** This sound's own stream: same seed, same sound. */\n readonly seed?: number\n /** Seconds from now. */\n readonly delay?: number\n /** Built now instead of waiting in the engine's deferred start queue: for a sound that has to land on the frame the player sees it (a blow's\n * contact, a heel strike, a landing). The queue builds a voice on the next frame budget and drops it after its latency, which at a low frame\n * rate is late or silent. Default false. */\n readonly urgent?: boolean\n /** A named stream of the engine (`streamFor(seed, name)`), so one subject never shifts another's sounds. */\n readonly channel?: string\n /** The tail a sample sound plays (default the engine's, see `setEnvironment`). */\n readonly environment?: SampleEnvironment\n /** 0 (light) to 1 (heavy): the tier of takes a sample sound plays (criterion C7). */\n readonly intensity?: number\n /** 0 (clear) to 1 (behind a wall) for this play, over the engine's `occlusion` (a test bench puts a wall in between). Sample sounds only. */\n readonly occlusion?: number\n}\n\n/** A playing voice: a recipe (`kind: 'recipe'`, the plan of the synthesized sound) or files (`kind: 'sample'`). */\nexport type VoiceHandle =\n | { readonly id: number; readonly kind: 'recipe'; readonly plan: SoundPlan; stop(): void }\n | { readonly id: number; readonly kind: 'sample'; readonly plan: SamplePlan; stop(): void }\n\n/**\n * A voice that started, for measuring (criterion C1: the event against the start of the sound). Times are the context clock, in seconds:\n * `requestedAt` when `play` was called, `startAt` when the first sample of the sound leaves the engine; `outputLatency` is what the device adds\n * after that (`baseLatency + outputLatency` of the context, 0 when unknown).\n */\nexport type VoiceStartEvent = {\n readonly id: string\n readonly kind: 'recipe' | 'sample'\n /** The sample sound this recipe stood in for while its files were not loaded. */\n readonly fallbackOf?: string\n /** The bank the played id is registered in (`kit_samples`, `user_samples`, a recipe bank...). */\n readonly bank?: string\n readonly requestedAt: number\n readonly startAt: number\n readonly outputLatency: number\n readonly level: number\n readonly distance: number\n readonly pan?: number\n /** The files a sample voice plays, by layer. */\n readonly layers?: readonly { readonly role: string; readonly url: string; readonly take: number; readonly rate: number }[]\n /** The tier of takes a sample voice played (criterion C7). */\n readonly tier?: string\n}\n\nexport type SampleOptions = {\n /** Gets the bytes of a file (default `fetch`, relative to `baseUrl`). */\n readonly loader?: SampleLoader\n readonly baseUrl?: string\n /** Load a sound's files the first time it is played (default true); the fallback plays meanwhile. */\n readonly autoLoad?: boolean\n /**\n * The peak limiter every sample voice of a bus goes through before the bus (criteria C6 and C9: no sound and no burst goes over −1 dBFS): linear\n * up to `knee` (default 0.5, −6 dBFS), then bent smoothly to `ceiling` (default 0.891, −1 dBFS), with no delay. `false` leaves it out.\n */\n readonly limiter?: false | { readonly knee?: number; readonly ceiling?: number }\n}\n\n/** A subject's own random stream; `ownNoise` also gives it its own noise buffer, filled from that stream (the order `createWeaponAudio` uses). */\nexport type AudioChannel = {\n readonly random: () => number\n play(id: string, options?: PlayOptions): VoiceHandle | null\n plan(id: string, options?: PlayOptions): SoundPlan | null\n}\n\nexport type AudioStats = {\n readonly context: 'none' | AudioContextState\n readonly voices: number\n readonly peak: number\n readonly dropped: number\n readonly maxVoices: number\n readonly loops: number\n}\n\nexport type AudioEngineOptions = {\n /** Seeds the engine stream: the noise, the reverb impulse and every sound played without its own seed or channel. Default 1. */\n readonly seed?: number\n /** Default `art_scene` (Q1). */\n readonly mix?: string | MixProfile\n readonly profiles?: Readonly<Record<string, MixProfile>>\n readonly banks?: readonly SoundBank[]\n readonly maxVoices?: number\n readonly groups?: Readonly<Record<string, VoiceGroup>>\n readonly distance?: DistanceMode\n /** 0 (clear) to 1 (behind a wall) for a sound at a point; without it there is no occlusion (Q8). */\n readonly occlusion?: (point: Vec3) => number\n readonly createContext?: () => AudioContext | null\n /** Build voices in timed slices between frames instead of inside `play` (a sound starts a few ms late; a burst never costs a frame). Off by default. */\n readonly deferredStart?: StartQueueOptions\n /** Where sample sounds get their files. */\n readonly samples?: SampleOptions\n /** The tail sample sounds play when `play` names none (default `outdoor`). */\n readonly environment?: SampleEnvironment\n /** Called when a voice is built (recipe or sample): the measuring hook of the criteria. */\n readonly onVoiceStart?: (event: VoiceStartEvent) => void\n}\n\nexport type AudioEngine = {\n readonly registry: SoundRegistry\n register(bank: SoundBank): void\n /** Pure: the plan a sound would play with, from `options.seed` or the engine seed; draws nothing from the live streams. */\n plan(id: string, options?: PlayOptions): SoundPlan | null\n /** Pure: the plan a sample sound would play with (no round-robin memory), from `options.seed` or the engine seed. */\n planSample(id: string, options?: PlayOptions): SamplePlan | null\n /** Loads the files of these sample sounds (default all registered). Creates the context; resolves when every file is decoded or failed. */\n loadSamples(ids?: readonly string[]): Promise<SampleLoadReport>\n /** `ready` when every file of the sound is decoded. */\n sampleStatus(id: string): SampleStatus\n /** The tail sample sounds play from now on. */\n setEnvironment(environment: SampleEnvironment): void\n /** The node everything is mixed into before the speakers (to record or meter the whole output), or `null` before the context exists. */\n output(): AudioNode | null\n /** Another place files come from: urls `accepts` takes go to `loader`, the rest to the engine's own (a bench lends its calibration takes). */\n addSampleSource(accepts: (url: string) => boolean, loader: SampleLoader): void\n /** Follows every voice built from now on (as `onVoiceStart` does); returns the unsubscribe function. */\n watchVoices(listener: (event: VoiceStartEvent) => void): () => void\n play(id: string, options?: PlayOptions): VoiceHandle | null\n playPlan(plan: SoundPlan, options?: { readonly delay?: number }): VoiceHandle | null\n loop(id: string, options?: { readonly volume?: number }): AudioLoopHandle\n channel(options: { readonly seed?: number; readonly random?: () => number; readonly ownNoise?: boolean }): AudioChannel\n setListener(listener: Listener): void\n setBus(id: BusId, setting: BusSetting): void\n setMix(mix: string | MixProfile): void\n /** The master volume of the current chain and of any later one (0 to 1). */\n setMaster(gain: number): void\n /** Creates the context and the mixing chain if needed and resumes it; call from a click or a key. */\n unlock(): void\n /** Creates the context, the mixing chain (reverb impulse included) and the shared noise buffer now, so the first sound does not pay for them inside a frame. Returns false without a context. */\n warmUp(): boolean\n stats(): AudioStats\n /** RMS (0 to 1) of what a bus carries now, read from an analyser the first time you ask; sounds started before that do not reach it. 0 without a context. */\n level(bus: BusId): number\n /**\n * The voice start queue as a `DeferredQueue` for a shared frame budget (`budget.register` attaches it and the queue stops scheduling its own tasks), or `null`\n * without `deferredStart`. Asking for it changes nothing.\n */\n deferredQueue?(): DeferredQueue | null\n dispose(): void\n}\n\n/** The limiter's transfer curve over ±`range`: linear up to `knee`, then a tanh bend that never passes `ceiling`. */\nexport function limiterCurve(knee: number, ceiling: number, range: number, points = 2049): Float32Array<ArrayBuffer> {\n const curve = new Float32Array(points)\n const room = Math.max(1e-6, ceiling - knee)\n for (let index = 0; index < points; index++) {\n const value = ((index / (points - 1)) * 2 - 1) * range\n const size = Math.abs(value)\n const bent = size <= knee ? size : knee + room * Math.tanh((size - knee) / room)\n curve[index] = Math.sign(value) * bent\n }\n return curve\n}\n\ntype Admission = { readonly bus: BusId; readonly group?: string; readonly priority?: number }\n\nconst usesNoise = (recipe: SoundRecipe): boolean => recipe.layers.some((layer) => layer.source.kind !== 'osc')\nconst planUsesNoise = (plan: SoundPlan): boolean => plan.layers.some((layer) => layer.source.kind !== 'osc')\n\n/**\n * The sound engine: plans recipes and builds them on a lazily created AudioContext through one of the team mixing chains. Without an AudioContext\n * (Node, workers) every call except `plan` does nothing.\n */\nexport function createAudioEngine(options: AudioEngineOptions = {}): AudioEngine {\n const seed = options.seed ?? 1\n const registry = createSoundRegistry(options.banks)\n const voices = createVoiceManager({ ...(options.groups ? { groups: options.groups } : {}), ...(options.maxVoices === undefined ? {} : { maxVoices: options.maxVoices }) })\n const engineRandom = createRng(seed)\n const shared = createNoiseStore(engineRandom)\n const busSettings = new Map<BusId, BusSetting>()\n const busNodes = new Map<BusId, GainNode>()\n const meters = new Map<BusId, { readonly analyser: AnalyserNode; readonly data: Float32Array<ArrayBuffer> }>()\n const active = new Map<number, RealizedVoice>()\n const loops = new Set<{ rewire(): void; stop(): void; readonly created: boolean }>()\n const named = new Map<string, () => number>()\n let mix = resolveMix(options.mix ?? DEFAULT_MIX, options.profiles)\n let context: AudioContext | null = null\n let chain: MixChain | null = null\n let listener: Listener = DEFAULT_LISTENER\n let lastTime = 0\n let environment: SampleEnvironment = options.environment ?? 'outdoor'\n const sampleLimiters = new Map<BusId, AudioNode>()\n // recipes go straight to the bus (their traces match the team routines node for node); recorded files go through a limiter of their bus. It is a\n // waveshaper, not a compressor: a compressor of the browser looks 6 ms ahead, which C1 (≤ 20 ms from the event) cannot spare.\n const sampleOutput = (bus: BusId): AudioNode => {\n const setting = options.samples?.limiter\n if (setting === false || !context) return outputFor(bus)\n const existing = sampleLimiters.get(bus)\n if (existing) return existing\n const range = 4\n const input = context.createGain()\n input.gain.value = 1 / range\n const shaper = context.createWaveShaper()\n shaper.curve = limiterCurve(setting?.knee ?? 0.5, setting?.ceiling ?? 0.891, range)\n ensureBus(bus)\n input.connect(shaper)\n shaper.connect(outputFor(bus))\n sampleLimiters.set(bus, input)\n return input\n }\n const chokes = new Map<string, { readonly id: number; readonly voice: RealizedSampleVoice }[]>()\n // the voices of a choked sound still ringing (the limiter forgets the ones that ended)\n const choked = (id: string): { readonly id: number; readonly voice: RealizedSampleVoice }[] => {\n const list = (chokes.get(id) ?? []).filter((entry) => active.has(entry.id))\n chokes.set(id, list)\n return list\n }\n const watchers = new Set<(event: VoiceStartEvent) => void>()\n const announce = (event: VoiceStartEvent): void => {\n options.onVoiceStart?.(event)\n for (const watcher of watchers) watcher(event)\n }\n const sources: { readonly accepts: (url: string) => boolean; readonly loader: SampleLoader }[] = []\n const baseLoader = options.samples?.loader ?? fetchLoader(options.samples?.baseUrl)\n const sampleStore = createSampleStore((url) => (sources.find((source) => source.accepts(url))?.loader ?? baseLoader)(url))\n const memory: SampleMemory = new Map()\n const latencyOf = (audio: BaseAudioContext): number => {\n const live = audio as Partial<Pick<AudioContext, 'baseLatency' | 'outputLatency'>>\n return (live.baseLatency ?? 0) + (live.outputLatency ?? 0)\n }\n\n const outputFor = (bus: BusId): AudioNode => (busNodes.get(bus) ?? chain?.master) as AudioNode\n\n // a bus somebody asked the level of gets an analyser as soon as it has a node, so sounds started before the first reading are metered too\n const watched = new Set<BusId>()\n const meterOf = (bus: BusId): { readonly analyser: AnalyserNode; readonly data: Float32Array<ArrayBuffer> } | undefined => {\n const existing = meters.get(bus)\n if (existing) return existing\n const node = busNodes.get(bus)\n if (!context || !node || typeof context.createAnalyser !== 'function') return undefined\n const analyser = context.createAnalyser()\n analyser.fftSize = 1024\n node.connect(analyser)\n const made = { analyser, data: new Float32Array(analyser.fftSize) }\n meters.set(bus, made)\n return made\n }\n\n const ensureBus = (bus: BusId): void => {\n if (!context || !chain || busNodes.has(bus)) return\n const node = context.createGain()\n node.connect(chain.master)\n busNodes.set(bus, node)\n if (watched.has(bus)) meterOf(bus)\n }\n\n const ready = (): AudioContext | null => {\n if (context) return context\n const created = (options.createContext ?? globalContext)()\n if (!created) return null\n context = created\n chain = buildChain(created, mix, engineRandom)\n if (mix.noise.create === 'eager') noiseBuffer(shared, created, mix.noise.seconds)\n for (const [bus, setting] of Object.entries(mix.buses ?? {}) as [BusId, BusSetting][]) {\n busSettings.set(bus, { ...setting, ...busSettings.get(bus) })\n }\n for (const [bus, setting] of busSettings) {\n ensureBus(bus)\n ;(busNodes.get(bus) as GainNode).gain.value = busGain(setting)\n }\n lastTime = created.currentTime\n return created\n }\n\n const advance = (): void => {\n if (!context) return\n const elapsed = context.currentTime - lastTime\n lastTime = context.currentTime\n if (elapsed > 0) for (const id of voices.advance(elapsed)) active.delete(id)\n }\n\n const inputFor = (recipe: SoundRecipe, playOptions: PlayOptions, random: () => number): PlanInput => ({\n random,\n listener,\n noiseSeconds: mix.noise.seconds,\n ...(options.distance ? { distanceMode: options.distance } : {}),\n ...(playOptions.volume === undefined ? {} : { volume: playOptions.volume }),\n ...(playOptions.distance === undefined ? {} : { distance: playOptions.distance }),\n ...(playOptions.position ? { position: playOptions.position } : {}),\n ...(playOptions.params ? { params: playOptions.params } : {}),\n ...(options.occlusion && playOptions.position && recipe.falloff?.model !== 'none' ? { occlusion: options.occlusion(playOptions.position) } : {}),\n })\n\n const startQueue = options.deferredStart ? createStartQueue(options.deferredStart) : null\n\n const build = (plan: SoundPlan, store: NoiseStore, delay: number, requestedAt: number, fallbackOf?: string): RealizedVoice => {\n const audio = context as AudioContext\n const time = audio.currentTime + delay\n const realized = realize(plan, {\n context: audio,\n output: outputFor(plan.bus),\n ...(chain?.wet ? { wet: chain.wet } : {}),\n noise: () => noiseBuffer(store, audio, mix.noise.seconds),\n time,\n })\n const recipeBank = registry.bankOf(plan.id)\n announce({\n id: plan.id,\n kind: 'recipe',\n ...(fallbackOf ? { fallbackOf } : {}),\n ...(recipeBank ? { bank: recipeBank } : {}),\n requestedAt,\n startAt: time,\n outputLatency: latencyOf(audio),\n level: plan.level,\n distance: plan.distance,\n ...(plan.pan === undefined ? {} : { pan: plan.pan }),\n })\n return realized\n }\n\n // the voice a deferred sound is tracked by until it is built: `stop` cancels it or stops what was built\n const deferVoice = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay: number, fallbackOf?: string): RealizedVoice => {\n const requestedAt = context?.currentTime ?? 0\n let built: RealizedVoice | null = null\n let cancelled = false\n const pending: RealizedVoice = {\n get sources() {\n return built?.sources ?? []\n },\n stop() {\n cancelled = true\n built?.stop()\n },\n }\n ;(startQueue as ReturnType<typeof createStartQueue>).push({\n run() {\n if (!cancelled && context) built = build(plan, store, delay, requestedAt, fallbackOf)\n },\n drop() {\n if (voiceId === undefined) return\n voices.release(voiceId)\n active.delete(voiceId)\n },\n })\n return pending\n }\n\n const start = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay = 0, fallbackOf?: string, urgent = false): VoiceHandle | null => {\n const realized = startQueue && !urgent ? deferVoice(plan, store, voiceId, delay, fallbackOf) : build(plan, store, delay, context?.currentTime ?? 0, fallbackOf)\n if (voiceId === undefined) return null\n voices.setLength(voiceId, plan.length + delay)\n active.set(voiceId, realized)\n return {\n id: voiceId,\n kind: 'recipe',\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const admit = (recipe: Admission, gain: number, distance: number): number | null => {\n const decision = voices.request({ ...(recipe.group ? { group: recipe.group } : {}), priority: recipe.priority ?? busPriority(recipe.bus), gain, distance, length: 0 })\n if (!decision.accepted) return null\n for (const id of decision.evicted) {\n active.get(id)?.stop()\n active.delete(id)\n }\n return decision.id\n }\n\n // a set id (`SoundBank.sets`) plays one of its variants, never the last one, at a drawn rate; a recipe id plays itself at rate 1\n const picker = createSetPicker()\n const resolve = (id: string, random: () => number, chooser = picker): { readonly id: string; readonly rate: number } => {\n if (registry.sound(id)) return { id, rate: 1 }\n const set = registry.set(id)\n return set ? chooser.pick(set, random) : { id, rate: 1 }\n }\n\n const loadSounds = (sounds: readonly SampleSound[]): Promise<SampleLoadReport> => {\n const audio = ready()\n if (!audio) return Promise.resolve({ loaded: [], failed: sounds.flatMap(sampleUrls).map((url) => ({ url, error: 'no audio context' })) })\n return sampleStore.load([...new Set(sounds.flatMap(sampleUrls))], audio)\n }\n\n const sampleInput = (playOptions: PlayOptions, random: () => number, withMemory: boolean) => ({\n random,\n listener,\n environment: playOptions.environment ?? environment,\n ...(withMemory ? { memory } : {}),\n ...(options.distance ? { distanceMode: options.distance } : {}),\n ...(playOptions.volume === undefined ? {} : { volume: playOptions.volume }),\n ...(playOptions.intensity === undefined ? {} : { intensity: playOptions.intensity }),\n ...(playOptions.distance === undefined ? {} : { distance: playOptions.distance }),\n ...(playOptions.position ? { position: playOptions.position } : {}),\n ...(playOptions.occlusion !== undefined\n ? { occlusion: playOptions.occlusion }\n : options.occlusion && playOptions.position\n ? { occlusion: options.occlusion(playOptions.position) }\n : {}),\n })\n\n // undefined: the files are not ready and there is no fallback, so the recipe of the same id (if any) plays\n const playSample = (sample: SampleSound, playOptions: PlayOptions, random: () => number, store: NoiseStore): VoiceHandle | null | undefined => {\n if (busSettings.get(sample.bus)?.muted) return null\n if (!sampleStore.ready(sampleUrls(sample))) {\n if (options.samples?.autoLoad !== false && ready()) void loadSounds([sample]).catch(() => undefined)\n if (sample.fallback && sample.fallback !== sample.id) return playWith(sample.fallback, playOptions, random, store, sample.id)\n return registry.sound(sample.id) ? undefined : null\n }\n const plan = planSample(sample, sampleInput(playOptions, playOptions.seed === undefined ? random : createRng(playOptions.seed), true))\n if (!plan) return null\n const audio = ready()\n if (!audio) return null\n unlockContext(audio)\n advance()\n const voiceId = admit(plan, plan.level, plan.distance)\n if (voiceId === null) return null\n const requestedAt = audio.currentTime\n const time = requestedAt + (playOptions.delay ?? 0)\n const chokeList = sample.choke ? choked(sample.id) : undefined\n const realized = realizeSample(plan, { context: audio, output: sampleOutput(plan.bus), buffer: (url) => sampleStore.buffer(url), time })\n const sampleBank = registry.bankOf(plan.id)\n announce({\n id: plan.id,\n kind: 'sample',\n ...(sampleBank ? { bank: sampleBank } : {}),\n requestedAt,\n startAt: time,\n outputLatency: latencyOf(audio),\n level: plan.level,\n distance: plan.distance,\n ...(plan.pan === undefined ? {} : { pan: plan.pan }),\n layers: plan.layers.map((layer) => ({ role: layer.role, url: layer.url, take: layer.take, rate: layer.rate })),\n ...(plan.tier ? { tier: plan.tier } : {}),\n })\n voices.setLength(voiceId, sampleLength(plan, (url) => sampleStore.seconds(url)) + (playOptions.delay ?? 0))\n active.set(voiceId, realized)\n if (chokeList && sample.choke) {\n chokeList.push({ id: voiceId, voice: realized })\n while (chokeList.length > Math.max(1, sample.choke.voices)) {\n const oldest = chokeList.shift()\n if (!oldest) break\n oldest.voice.fade(time, sample.choke.fade ?? 0.03)\n voices.release(oldest.id)\n active.delete(oldest.id)\n }\n }\n return {\n id: voiceId,\n kind: 'sample',\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const playWith = (asked: string, playOptions: PlayOptions, streamRandom: () => number, store: NoiseStore, fallbackOf?: string): VoiceHandle | null => {\n const sample = fallbackOf === undefined ? registry.sample(asked) : undefined\n if (sample) {\n const played = playSample(sample, playOptions, streamRandom, store)\n if (played !== undefined) return played\n }\n const seeded = playOptions.seed === undefined ? null : createRng(playOptions.seed)\n const { id, rate } = resolve(asked, seeded ?? streamRandom)\n const random = seeded ?? streamRandom\n const recipe = registry.sound(id)\n if (!recipe || busSettings.get(recipe.bus)?.muted) return null\n const distance = playOptions.distance ?? (playOptions.position ? listenerDistance(listener, playOptions.position, options.distance) : 0)\n const level = falloffGain(recipe.falloff, playOptions.volume ?? 1, distance)\n const silent = isSilent(recipe.falloff, level)\n // a sound too quiet to play does not even start the context (the team routines return before touching it)\n if (silent && !recipe.keepSilent) return null\n const audio = ready()\n if (!audio) return null\n unlockContext(audio)\n advance()\n const voiceId = silent ? undefined : admit(recipe, level, distance)\n if (voiceId === null) return null\n if (!silent && usesNoise(recipe)) prepareNoise(store, audio, mix.noise.seconds)\n const plan = planSound(recipe, inputFor(recipe, playOptions, random))\n return plan ? start(retunePlan(plan, rate), store, voiceId, playOptions.delay, fallbackOf, playOptions.urgent) : null\n }\n\n const randomFor = (playOptions: PlayOptions): (() => number) => {\n if (playOptions.channel === undefined) return engineRandom\n const existing = named.get(playOptions.channel)\n if (existing) return existing\n const stream = streamFor(seed, playOptions.channel)\n named.set(playOptions.channel, stream)\n return stream\n }\n\n // pure: a set is drawn with a picker of its own, so planning never moves what `play` picks next\n const planWith = (asked: string, playOptions: PlayOptions, random: () => number): SoundPlan | null => {\n const { id, rate } = resolve(asked, random, createSetPicker())\n const recipe = registry.sound(id)\n const plan = recipe ? planSound(recipe, inputFor(recipe, playOptions, random)) : null\n return plan ? retunePlan(plan, rate) : null\n }\n\n const loopHost: LoopHost = {\n ready,\n output: outputFor,\n prepareNoise: () => context && prepareNoise(shared, context, mix.noise.seconds),\n noise: () => noiseBuffer(shared, context as AudioContext, mix.noise.seconds),\n register: (loop) => void loops.add(loop),\n unregister: (loop) => void loops.delete(loop),\n listener: () => listener,\n ...(options.distance ? { distance: options.distance } : {}),\n }\n\n return {\n registry,\n register: (bank) => registry.register(bank),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\n planSample(id, playOptions = {}) {\n const sample = registry.sample(id)\n return sample ? planSample(sample, sampleInput(playOptions, createRng(playOptions.seed ?? seed), false)) : null\n },\n loadSamples(ids) {\n const chosen = (ids ?? registry.sampleIds()).map((id) => registry.sample(id)).filter((sample): sample is SampleSound => sample !== undefined)\n return loadSounds(chosen)\n },\n sampleStatus(id) {\n const sample = registry.sample(id)\n if (!sample) return 'none'\n const statuses = sampleUrls(sample).map((url) => sampleStore.status(url))\n if (statuses.every((status) => status === 'ready')) return 'ready'\n if (statuses.includes('failed')) return 'failed'\n if (statuses.includes('loading')) return 'loading'\n return statuses.includes('ready') ? 'loading' : 'none'\n },\n setEnvironment(next) {\n environment = next\n },\n output: () => chain?.master ?? null,\n addSampleSource(accepts, loader) {\n sources.push({ accepts, loader })\n },\n watchVoices(listener) {\n watchers.add(listener)\n return () => void watchers.delete(listener)\n },\n play: (id, playOptions = {}) => playWith(id, playOptions, randomFor(playOptions), shared),\n playPlan(plan, playOptions = {}) {\n const audio = ready()\n if (!audio) return null\n advance()\n const recipe = { id: plan.id, bus: plan.bus, layers: [], sources: [], priority: plan.priority, ...(plan.group ? { group: plan.group } : {}) }\n const voiceId = plan.silent ? undefined : admit(recipe, plan.level, plan.distance)\n if (voiceId === null) return null\n if (planUsesNoise(plan)) prepareNoise(shared, audio, mix.noise.seconds)\n return start(plan, shared, voiceId, playOptions.delay)\n },\n loop(id, loopOptions = {}) {\n const sample = registry.sample(id)\n if (!sample?.loop) return createLoopHandle(registry.loop(id), loopHost, loopOptions.volume)\n return createSampleLoopHandle(\n sample,\n {\n ready,\n output: sampleOutput,\n buffer: (url) => sampleStore.buffer(url),\n isReady: (sound) => sampleStore.ready(sampleUrls(sound)),\n load: (sound) => (options.samples?.autoLoad === false ? Promise.resolve() : loadSounds([sound])),\n fallback: (volume) => createLoopHandle(registry.loop(sample.fallback ?? sample.id) ?? registry.loop(sample.id), loopHost, volume),\n random: engineRandom,\n register: loopHost.register,\n unregister: loopHost.unregister,\n muted: (bus) => busSettings.get(bus)?.muted === true,\n },\n loopOptions.volume,\n )\n },\n channel(channelOptions) {\n const random = channelOptions.random ?? (channelOptions.seed === undefined ? engineRandom : createRng(channelOptions.seed))\n const store = channelOptions.ownNoise ? createNoiseStore(random) : shared\n return {\n random,\n play: (id, playOptions = {}) => playWith(id, playOptions, random, store),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\n }\n },\n setListener(next) {\n listener = next\n },\n setBus(id, setting) {\n busSettings.set(id, { ...busSettings.get(id), ...setting })\n if (!context) return\n ensureBus(id)\n ;(busNodes.get(id) as GainNode).gain.value = busGain(busSettings.get(id))\n },\n setMix(next) {\n const previous = mix\n mix = resolveMix(next, options.profiles)\n if (!context || !chain) return\n const old = chain\n chain = buildChain(context, mix, engineRandom)\n if (mix.noise.seconds !== previous.noise.seconds) shared.reset()\n for (const node of busNodes.values()) {\n node.disconnect()\n node.connect(chain.master)\n }\n for (const loop of loops) loop.rewire()\n old.disconnect()\n },\n setMaster(gain) {\n mix = { ...mix, master: gain }\n if (chain) chain.master.gain.value = gain\n },\n unlock() {\n const audio = ready()\n if (audio) unlockContext(audio)\n },\n warmUp() {\n const audio = ready()\n if (!audio) return false\n noiseBuffer(shared, audio, mix.noise.seconds)\n return true\n },\n level(bus) {\n watched.add(bus)\n ensureBus(bus)\n const meter = meterOf(bus)\n if (!meter) return 0\n meter.analyser.getFloatTimeDomainData(meter.data)\n let sum = 0\n for (const sample of meter.data) sum += sample * sample\n return Math.sqrt(sum / meter.data.length)\n },\n deferredQueue: () => startQueue?.deferredQueue() ?? null,\n stats() {\n advance()\n const voiceStats = voices.stats()\n return {\n context: context ? context.state : 'none',\n voices: voiceStats.active,\n peak: voiceStats.peak,\n dropped: voiceStats.dropped,\n maxVoices: voiceStats.maxVoices,\n loops: [...loops].filter((loop) => loop.created).length,\n }\n },\n dispose() {\n // closing the context ends every voice; they only leave the limiter\n startQueue?.clear()\n for (const id of active.keys()) voices.release(id)\n for (const loop of [...loops]) loop.stop()\n active.clear()\n void context?.close()\n context = null\n chain = null\n busNodes.clear()\n meters.clear()\n shared.reset()\n sampleStore.clear()\n memory.clear()\n sampleLimiters.clear()\n chokes.clear()\n },\n }\n}\n","/**\n * Measurements of rendered sound (pure, on plain sample arrays), for the criteria C1–C9: when it starts, how loud and how bright it is, which side\n * it is on, how long it rings and how many separate hits a burst has.\n */\n\nexport type Channels = readonly Float32Array[]\n\n/** Linear amplitude to dBFS (−Infinity for 0). */\nexport const dbOf = (amplitude: number): number => (amplitude > 0 ? 20 * Math.log10(amplitude) : -Infinity)\n\nconst clampIndex = (channels: Channels, index: number): number => Math.max(0, Math.min(channels[0]?.length ?? 0, Math.round(index)))\n\n/** The loudest sample of every channel between two sample indexes (linear). */\nexport function peakOf(channels: Channels, start = 0, end = Number.POSITIVE_INFINITY): number {\n let peak = 0\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, end)\n for (let index = from; index < to; index++) {\n const value = Math.abs(channel[index] as number)\n if (value > peak) peak = value\n }\n }\n return peak\n}\n\n/** Index of the loudest sample (any channel) between two indexes. */\nexport function peakIndex(channels: Channels, start = 0, end = Number.POSITIVE_INFINITY): number {\n let peak = -1\n let at = -1\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, end)\n for (let index = from; index < to; index++) {\n const value = Math.abs(channel[index] as number)\n if (value > peak) {\n peak = value\n at = index\n }\n }\n }\n return at\n}\n\n/** First sample index at or after `start` whose amplitude (any channel) reaches `threshold`, or −1. */\nexport function onsetIndex(channels: Channels, start = 0, threshold = 0.001): number {\n const length = channels[0]?.length ?? 0\n for (let index = clampIndex(channels, start); index < length; index++) {\n for (const channel of channels) if (Math.abs(channel[index] as number) >= threshold) return index\n }\n return -1\n}\n\n/** RMS of all channels between two indexes, dBFS. */\nexport function rmsDb(channels: Channels, start: number, end: number): number {\n let sum = 0\n let count = 0\n const from = clampIndex(channels, start)\n for (const channel of channels) {\n const to = Math.min(channel.length, Math.round(end))\n for (let index = from; index < to; index++) {\n const value = channel[index] as number\n sum += value * value\n count++\n }\n }\n return count === 0 ? -Infinity : dbOf(Math.sqrt(sum / count))\n}\n\n/** Spectral centroid (Hz) of `size` samples from `start` (channels summed, Hann window, plain DFT): the brightness of the sound. */\nexport function centroidHz(channels: Channels, sampleRate: number, start: number, size = 2048): number {\n const from = clampIndex(channels, start)\n const frame = new Float64Array(size)\n for (const channel of channels) {\n for (let index = 0; index < size; index++) frame[index] = (frame[index] as number) + ((channel[from + index] as number | undefined) ?? 0)\n }\n for (let index = 0; index < size; index++) frame[index] = (frame[index] as number) * (0.5 - 0.5 * Math.cos((2 * Math.PI * index) / (size - 1)))\n let weighted = 0\n let total = 0\n const bins = size / 2\n for (let bin = 1; bin < bins; bin++) {\n let re = 0\n let im = 0\n const step = (2 * Math.PI * bin) / size\n for (let index = 0; index < size; index++) {\n const value = frame[index] as number\n re += value * Math.cos(step * index)\n im -= value * Math.sin(step * index)\n }\n const magnitude = Math.hypot(re, im)\n weighted += magnitude * ((bin * sampleRate) / size)\n total += magnitude\n }\n return total > 0 ? weighted / total : 0\n}\n\n/** Energy balance from −1 (all left) to 1 (all right) between two indexes. */\nexport function balanceOf(left: Float32Array, right: Float32Array, start: number, end: number): number {\n let l = 0\n let r = 0\n const to = Math.min(left.length, right.length, Math.round(end))\n for (let index = Math.max(0, Math.round(start)); index < to; index++) {\n l += (left[index] as number) ** 2\n r += (right[index] as number) ** 2\n }\n return l + r > 0 ? (r - l) / (r + l) : 0\n}\n\n/** Seconds from `start` to the last 10 ms window louder than `floorDb` (how long the sound rings, tail included). */\nexport function ringSeconds(channels: Channels, sampleRate: number, start: number, floorDb = -60): number {\n const window = Math.max(1, Math.round(sampleRate * 0.01))\n const length = channels[0]?.length ?? 0\n let last = clampIndex(channels, start)\n for (let index = last; index < length; index += window) {\n if (dbOf(peakOf(channels, index, index + window)) > floorDb) last = index + window\n }\n return (last - start) / sampleRate\n}\n\n/**\n * Separate hits in a burst: attacks of the 2 ms envelope, where it jumps to twice the mean of the 20 ms before it and reaches `threshold`, at least\n * 30 ms apart (so a rapid fire over a long tail still counts every shot).\n */\nexport function countHits(channels: Channels, sampleRate: number, threshold: number): number {\n const window = Math.max(1, Math.round(sampleRate * 0.002))\n const length = channels[0]?.length ?? 0\n const envelope: number[] = []\n for (let index = 0; index < length; index += window) envelope.push(peakOf(channels, index, index + window))\n const history = 10\n const refractory = Math.round(0.03 / 0.002)\n let hits = 0\n let quietUntil = -1\n for (let index = 0; index < envelope.length; index++) {\n const level = envelope[index] as number\n if (index < quietUntil || level < threshold) continue\n let sum = 0\n for (let back = Math.max(0, index - history); back < index; back++) sum += envelope[back] as number\n const before = index === 0 ? 0 : sum / Math.min(history, index)\n if (level >= 2 * before) {\n hits++\n quietUntil = index + refractory\n }\n }\n return hits\n}\n\n/** Peak of the last `seconds` of a file against its own peak, dB (≤ −40: it fades out, it does not end on a cut). */\nexport function endDropDb(channels: Channels, sampleRate: number, seconds = 0.005): number {\n const length = channels[0]?.length ?? 0\n const whole = peakOf(channels)\n if (whole === 0) return -Infinity\n return dbOf(peakOf(channels, length - Math.round(sampleRate * seconds), length) / whole)\n}\n","/**\n * The measuring harness of the sound criteria (C1–C10 of the sound checklist). Each criterion plays the sound through a real engine on an\n * `OfflineAudioContext` (the same mix, limiter and realizer the game uses, rendered faster than real time), and measures the rendered output: when it\n * starts against the event, how loud and bright it is at each distance, which side, how many takes, how it ends. Runs in a browser (or anything with\n * an `OfflineAudioContext`); C10 is the owner's ear, so it is left open with a recording to listen to (`recordOutput`).\n */\nimport type { MixProfile } from '../mix'\nimport type { SoundBank } from '../recipe'\nimport { createRng } from '../rng'\nimport { planSample, sampleUrls } from '../sample'\nimport type { SampleEnvironment, SampleSound } from '../sample'\nimport { createAudioEngine } from '../webaudio/engine'\nimport type { AudioEngine, PlayOptions, VoiceStartEvent } from '../webaudio/engine'\nimport type { SampleLoader } from '../webaudio/sample-store'\nimport { balanceOf, centroidHz, dbOf, endDropDb, onsetIndex, peakIndex, peakOf, ringSeconds, rmsDb } from './analyze'\nimport type { Channels } from './analyze'\n\nexport const CRITERIA = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'] as const\nexport type CriterionId = (typeof CRITERIA)[number]\n\n/** The targets of the checklist, as numbers the harness compares with. */\nexport const CRITERIA_TARGETS = {\n /** C1: event to the first sample, and onset to the peak (one 60 fps frame). */\n syncMs: 20,\n peakAfterOnsetMs: 1000 / 60,\n /** C3: distances measured, metres. */\n distances: [1, 10, 50, 200] as readonly number[],\n /** C5: plays, distinct takes and the pitch range (fraction). */\n plays: 10,\n minTakes: 4,\n pitch: [0.03, 0.05] as const,\n /** C6: the highest peak, dBFS. */\n peakDb: -1,\n /** C8: the end of each file against its peak, dB. */\n endDropDb: -40,\n /** C9: a burst of rapid fire. */\n burst: 20,\n burstSpacing: 0.06,\n} as const\n\nexport type CriterionResult = {\n readonly id: CriterionId\n /** `null`: not decided by the harness (C10, the owner's ear). */\n readonly pass: boolean | null\n /** What was measured, short (the bench prints it). */\n readonly value: string\n readonly target: string\n readonly data?: Readonly<Record<string, unknown>>\n}\n\n/** One action of the game and the sound it must play (C2). */\nexport type ActionCheck = { readonly action: string; readonly play: string; readonly expect: string; readonly options?: PlayOptions }\n\nexport type MeasureOptions = {\n /** The sample sound measured. */\n readonly sound: string\n readonly banks: readonly SoundBank[]\n readonly loader: SampleLoader\n /** The mixing chain the game uses (default the engine's default). */\n readonly mix?: string | MixProfile\n readonly sampleRate?: number\n /** `new OfflineAudioContext(...)` by default. */\n readonly createOfflineContext?: (channels: number, length: number, sampleRate: number) => OfflineAudioContext\n /** The live context's `baseLatency` (s), added to the rendered delay for C1. */\n readonly baseLatency?: number\n /** The device's `outputLatency` (s), reported with C1 but not counted (it is the speakers', not the game's). */\n readonly outputLatency?: number\n /** C2: the actions to check (default the sound for itself). */\n readonly actions?: readonly ActionCheck[]\n /** C6: sound ids loudest first, the order the buses must keep (tiro > explosão > impacto > passo). */\n readonly loudnessOrder?: readonly string[]\n}\n\ntype Render = { readonly channels: Channels; readonly sampleRate: number; readonly events: readonly VoiceStartEvent[]; readonly handles: number }\n\nconst EVENT_AT = 0.2\n\nconst offlineFactory = (options: MeasureOptions) =>\n options.createOfflineContext ??\n ((channels: number, length: number, sampleRate: number): OfflineAudioContext => {\n const Constructor = (globalThis as { OfflineAudioContext?: new (channels: number, length: number, sampleRate: number) => OfflineAudioContext }).OfflineAudioContext\n if (!Constructor) throw new Error('no OfflineAudioContext here: the harness runs in a browser')\n return new Constructor(channels, length, sampleRate)\n })\n\n/** Renders what `act` plays on a fresh engine (files loaded first), `seconds` long. */\nasync function render(options: MeasureOptions, seconds: number, act: (engine: AudioEngine) => number, engineExtras: { occlusion?: () => number; environment?: SampleEnvironment } = {}): Promise<Render> {\n const sampleRate = options.sampleRate ?? 48000\n const context = offlineFactory(options)(2, Math.ceil(seconds * sampleRate), sampleRate)\n const events: VoiceStartEvent[] = []\n const engine = createAudioEngine({\n banks: options.banks,\n createContext: () => context as unknown as AudioContext,\n samples: { loader: options.loader, autoLoad: false },\n onVoiceStart: (event) => events.push(event),\n ...(options.mix ? { mix: options.mix } : {}),\n ...(engineExtras.occlusion ? { occlusion: engineExtras.occlusion } : {}),\n ...(engineExtras.environment ? { environment: engineExtras.environment } : {}),\n })\n const ids = [...new Set([options.sound, ...(options.actions ?? []).map((action) => action.play), ...(options.loudnessOrder ?? [])])].filter((id) => engine.registry.sample(id))\n const report = await engine.loadSamples(ids)\n if (report.failed.length > 0) throw new Error(`files did not load: ${report.failed.map((entry) => `${entry.url} (${entry.error})`).join(', ')}`)\n const handles = act(engine)\n const buffer = await context.startRendering()\n const channels = Array.from({ length: buffer.numberOfChannels }, (_, index) => buffer.getChannelData(index))\n return { channels, sampleRate, events, handles }\n}\n\nconst ms = (seconds: number): string => `${(seconds * 1000).toFixed(1)} ms`\nconst db = (value: number): string => (Number.isFinite(value) ? `${value.toFixed(1)} dB` : '−∞')\nconst decreasing = (values: readonly number[]): boolean => values.every((value, index) => index === 0 || value < (values[index - 1] as number))\n\nasync function c1(options: MeasureOptions): Promise<CriterionResult> {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { distance: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 0.001)\n const event = result.events.find((entry) => entry.id === options.sound)\n if (onset < 0 || !event) return { id: 'C1', pass: false, value: 'sem som', target: `≤ ${CRITERIA_TARGETS.syncMs} ms` }\n const delay = onset / result.sampleRate - EVENT_AT + (event.startAt - event.requestedAt - EVENT_AT) + (options.baseLatency ?? 0)\n const peak = peakIndex(result.channels, onset, onset + Math.round(result.sampleRate * 0.25))\n const toPeak = (peak - onset) / result.sampleRate\n const pass = delay <= CRITERIA_TARGETS.syncMs / 1000 && toPeak <= CRITERIA_TARGETS.peakAfterOnsetMs / 1000\n return {\n id: 'C1',\n pass,\n value: `${ms(delay)}, pico +${ms(toPeak)}`,\n target: `≤ ${CRITERIA_TARGETS.syncMs} ms; pico no quadro do contato`,\n data: { delay, toPeak, baseLatency: options.baseLatency ?? 0, outputLatency: options.outputLatency ?? 0 },\n }\n}\n\nasync function c2(options: MeasureOptions): Promise<CriterionResult> {\n const actions = options.actions ?? [{ action: options.sound, play: options.sound, expect: options.sound }]\n const result = await render(options, 0.5, (engine) => {\n let played = 0\n for (const action of actions) if (engine.play(action.play, { distance: 1, ...action.options })) played++\n return played\n })\n const wrong = actions.filter((action, index) => {\n const event = result.events[index]\n return !event || (event.fallbackOf ?? event.id) !== action.expect || event.kind !== 'sample'\n })\n return {\n id: 'C2',\n pass: wrong.length === 0,\n value: `${actions.length - wrong.length}/${actions.length} certas`,\n target: '100% das ações batem com a tabela (arquivo, não o substituto)',\n data: { wrong: wrong.map((action) => action.action), events: result.events.map((event) => `${event.kind}:${event.id}`) },\n }\n}\n\nasync function c3(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const levels: number[] = []\n const brightness: number[] = []\n for (const distance of CRITERIA_TARGETS.distances) {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { position: [0, 0, -distance], seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n levels.push(onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3))\n brightness.push(onset < 0 ? 0 : centroidHz(result.channels, result.sampleRate, onset))\n }\n const far = planSample(sound, { random: createRng(1), distance: CRITERIA_TARGETS.distances.at(-1) as number })\n const switched = (far?.farMix ?? 0) === 1 && (far?.layers.some((layer) => layer.role === 'far') ?? false)\n const pass = decreasing(levels) && decreasing(brightness) && switched\n return {\n id: 'C3',\n pass,\n value: `${levels.map((level) => db(level)).join(' › ')}; ${brightness.map((hz) => `${Math.round(hz)} Hz`).join(' › ')}${switched ? '; longe = far' : '; sem camada far'}`,\n target: 'cai e escurece com a distância; troca para a versão de longe depois de ~50 m',\n data: { distances: CRITERIA_TARGETS.distances, levels, brightness, switched },\n }\n}\n\nasync function c4(options: MeasureOptions): Promise<CriterionResult> {\n const side = async (x: number): Promise<number> => {\n const result = await render(options, 0.8, (engine) => (engine.play(options.sound, { position: [x, 0, -2], seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const [left, right] = result.channels as [Float32Array, Float32Array]\n return balanceOf(left, right, 0, left.length)\n }\n const right = await side(10)\n const left = await side(-10)\n const bright = async (occluded: boolean): Promise<number> => {\n const result = await render(options, 0.8, (engine) => (engine.play(options.sound, { position: [0, 0, -10], seed: 1, delay: EVENT_AT }) ? 1 : 0), occluded ? { occlusion: () => 1 } : {})\n const onset = onsetIndex(result.channels, 0, 1e-5)\n return onset < 0 ? 0 : centroidHz(result.channels, result.sampleRate, onset)\n }\n const clear = await bright(false)\n const wall = await bright(true)\n const pass = right > 0.2 && left < -0.2 && wall < clear * 0.7\n return {\n id: 'C4',\n pass,\n value: `dir ${right.toFixed(2)} esq ${left.toFixed(2)}; parede ${Math.round(wall)} Hz de ${Math.round(clear)} Hz`,\n target: 'lado certo; atrás da parede fica abafado',\n data: { right, left, clear, wall },\n }\n}\n\nasync function c5(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const result = await render(options, 0.3 * CRITERIA_TARGETS.plays + 1, (engine) => {\n let played = 0\n for (let index = 0; index < CRITERIA_TARGETS.plays; index++) if (engine.play(options.sound, { distance: 1, delay: 0.1 + index * 0.3 })) played++\n return played\n })\n const close = result.events.map((event) => event.layers?.find((layer) => layer.role === 'close'))\n const takes = close.map((layer) => layer?.url ?? '')\n const repeats = takes.filter((take, index) => index > 0 && take === takes[index - 1]).length\n const distinct = new Set(takes).size\n const rates = close.map((layer) => layer?.rate ?? 1)\n const spread = (Math.max(...rates) - Math.min(...rates)) / 2\n const pitch = sound.pitch ?? 0.04\n const pass = distinct >= CRITERIA_TARGETS.minTakes && repeats === 0 && pitch >= CRITERIA_TARGETS.pitch[0] && pitch <= CRITERIA_TARGETS.pitch[1] && spread > 0.01\n return {\n id: 'C5',\n pass,\n value: `${distinct} tomadas, ${repeats} repetições seguidas, tom ±${(pitch * 100).toFixed(0)}%`,\n target: `≥ ${CRITERIA_TARGETS.minTakes} variações, nunca a mesma duas vezes, tom ±3–5%`,\n data: { takes, rates },\n }\n}\n\nasync function c6(options: MeasureOptions): Promise<CriterionResult> {\n const peakAt = async (id: string): Promise<{ peak: number; rms: number }> => {\n const result = await render(options, 1.2, (engine) => (engine.play(id, { distance: 1, seed: 1, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n return { peak: dbOf(peakOf(result.channels)), rms: onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3) }\n }\n const own = await peakAt(options.sound)\n const order = options.loudnessOrder ?? []\n const loudness: number[] = []\n for (const id of order) loudness.push((await peakAt(id)).rms)\n const ordered = order.length < 2 || decreasing(loudness)\n const pass = own.peak <= CRITERIA_TARGETS.peakDb && ordered\n return {\n id: 'C6',\n pass,\n value: `pico ${db(own.peak)}, RMS ${db(own.rms)}${order.length > 1 ? `; ordem ${ordered ? 'ok' : 'errada'}` : ''}`,\n target: 'tiro > explosão > impacto > passo; pico ≤ −1 dBFS',\n data: { peak: own.peak, rms: own.rms, order, loudness },\n }\n}\n\nasync function c7(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n if (!sound.tiers || sound.tiers.length < 2) return { id: 'C7', pass: false, value: 'sem camadas leve/médio/forte', target: 'muda de camada, não só de volume' }\n const at = async (intensity: number): Promise<{ tier: string; rms: number; files: string }> => {\n const result = await render(options, 1.2, (engine) => (engine.play(options.sound, { distance: 1, seed: 1, intensity, delay: EVENT_AT }) ? 1 : 0))\n const onset = onsetIndex(result.channels, 0, 1e-5)\n const event = result.events[0]\n return { tier: event?.tier ?? '', rms: onset < 0 ? -Infinity : rmsDb(result.channels, onset, onset + result.sampleRate * 0.3), files: event?.layers?.find((layer) => layer.role === 'close')?.url ?? '' }\n }\n const light = await at(0.1)\n const heavy = await at(0.9)\n const pass = light.tier !== heavy.tier && light.files !== heavy.files && heavy.rms > light.rms\n return {\n id: 'C7',\n pass,\n value: `${light.tier} ${db(light.rms)} → ${heavy.tier} ${db(heavy.rms)}`,\n target: 'golpe fraco x forte troca a camada (leve/médio/forte), não só o volume',\n data: { light, heavy },\n }\n}\n\nasync function c8(options: MeasureOptions, sound: SampleSound): Promise<CriterionResult> {\n const sampleRate = options.sampleRate ?? 48000\n const decoder = offlineFactory(options)(1, sampleRate, sampleRate)\n const drops: { url: string; drop: number }[] = []\n for (const url of sampleUrls(sound)) {\n const buffer = await decoder.decodeAudioData(await options.loader(url))\n drops.push({ url, drop: endDropDb([buffer.getChannelData(0)], buffer.sampleRate) })\n }\n const worst = drops.reduce((max, entry) => Math.max(max, entry.drop), -Infinity)\n const ring = async (environment: SampleEnvironment): Promise<number> => {\n const result = await render(options, 3, (engine) => (engine.play(options.sound, { distance: 1, seed: 1, environment, delay: EVENT_AT }) ? 1 : 0))\n return ringSeconds(result.channels, result.sampleRate, Math.round(EVENT_AT * result.sampleRate))\n }\n const indoor = await ring('indoor')\n const outdoor = await ring('outdoor')\n const hasTails = Boolean(sound.tail?.indoor?.length && sound.tail?.outdoor?.length)\n const pass = worst <= CRITERIA_TARGETS.endDropDb && hasTails && outdoor > indoor\n return {\n id: 'C8',\n pass,\n value: `fim ${db(worst)}; cauda dentro ${indoor.toFixed(2)} s, fora ${outdoor.toFixed(2)} s${hasTails ? '' : ' (sem as duas caudas)'}`,\n target: 'não corta seco; cauda de interior x exterior coerente',\n data: { drops, indoor, outdoor },\n }\n}\n\nasync function c9(options: MeasureOptions): Promise<CriterionResult> {\n const { burst, burstSpacing } = CRITERIA_TARGETS\n const first = 0.1\n const result = await render(options, burst * burstSpacing + 1.5, (engine) => {\n let played = 0\n for (let index = 0; index < burst; index++) if (engine.play(options.sound, { distance: 1, delay: first + index * burstSpacing })) played++\n return played\n })\n const peak = dbOf(peakOf(result.channels))\n // C9 reads: no pile-up (the level does not build up shot after shot) and no shot that vanishes (every slot carries its shot). RMS of each shot's slot:\n const slots: number[] = []\n for (let index = 0; index < burst; index++) {\n const at = Math.round((first + index * burstSpacing) * result.sampleRate)\n slots.push(rmsDb(result.channels, at, at + Math.round(burstSpacing * result.sampleRate)))\n }\n const sorted = [...slots].sort((a, b) => a - b)\n const median = sorted[Math.floor(sorted.length / 2)] as number\n const vanished = slots.filter((level) => level < median - 6).length\n const buildUp = slots.slice(-5).reduce((sum, level) => sum + level, 0) / 5 - (slots[0] as number)\n const pass = result.handles === burst && vanished === 0 && buildUp <= 6 && peak <= CRITERIA_TARGETS.peakDb\n return {\n id: 'C9',\n pass,\n value: `${result.handles}/${burst} tocaram, ${vanished} sumiram, acúmulo ${buildUp >= 0 ? '+' : ''}${buildUp.toFixed(1)} dB, pico ${db(peak)}`,\n target: 'rajada sem amontoar (acúmulo ≤ 6 dB) nem sumir; pico ≤ −1 dBFS',\n data: { handles: result.handles, slots, vanished, buildUp, peak },\n }\n}\n\n/** Runs the criteria (all by default) and returns one result each, in order. C10 is always open: it is the owner's ear on a recording. */\nexport async function measureCriteria(options: MeasureOptions, only: readonly CriterionId[] = CRITERIA): Promise<CriterionResult[]> {\n const probe = createAudioEngine({ banks: options.banks, createContext: () => null })\n const sound = probe.registry.sample(options.sound)\n if (!sound) throw new Error(`${options.sound} is not a sample sound of these banks`)\n const results: CriterionResult[] = []\n for (const id of only) {\n if (id === 'C1') results.push(await c1(options))\n else if (id === 'C2') results.push(await c2(options))\n else if (id === 'C3') results.push(await c3(options, sound))\n else if (id === 'C4') results.push(await c4(options))\n else if (id === 'C5') results.push(await c5(options, sound))\n else if (id === 'C6') results.push(await c6(options))\n else if (id === 'C7') results.push(await c7(options, sound))\n else if (id === 'C8') results.push(await c8(options, sound))\n else if (id === 'C9') results.push(await c9(options))\n else results.push({ id: 'C10', pass: null, value: 'gravar e ouvir', target: 'aprovado pelo ouvido do dono (print + gravação na 4280)' })\n }\n return results\n}\n\n/**\n * Records what the engine outputs while `act` plays, `seconds` long (the C10 recording): a `MediaRecorder` on a stream tapped from the master. Returns\n * `null` where there is no recorder or no context.\n */\nexport async function recordOutput(engine: AudioEngine, seconds: number, act: () => void): Promise<Blob | null> {\n engine.unlock()\n const output = engine.output()\n const Recorder = (globalThis as { MediaRecorder?: typeof MediaRecorder }).MediaRecorder\n const context = output?.context as AudioContext | undefined\n if (!output || !Recorder || !context || typeof context.createMediaStreamDestination !== 'function') return null\n const tap = context.createMediaStreamDestination()\n output.connect(tap)\n const recorder = new Recorder(tap.stream)\n const chunks: Blob[] = []\n recorder.ondataavailable = (event) => chunks.push(event.data)\n const done = new Promise<void>((resolve) => {\n recorder.onstop = () => resolve()\n })\n recorder.start()\n act()\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000))\n recorder.stop()\n await done\n output.disconnect(tap)\n return new Blob(chunks, { type: recorder.mimeType || 'audio/webm' })\n}\n","/**\n * The sounds a game needs, by category, as the sound checklist lists them (generic, real-world names: a 9 mm pistol, a wooden door): the id a file\n * takes, its priority and the synthesized sound it replaces today (`current`, the A of an A/B). A sound is \"file\" once a bank registers a sample under\n * its id; \"synth\" while only `current` exists; \"missing\" when neither does. Data only: a game adds, renames or drops entries without touching the engine.\n */\n\nexport const SFX_CATEGORIES = ['armas', 'impactos', 'explosoes-fogo', 'personagem', 'veiculos', 'itens-portas', 'ambiente'] as const\nexport type SfxCategory = (typeof SFX_CATEGORIES)[number]\n\nexport type SfxPriority = 1 | 2 | 3\n\nexport type SfxEntry = {\n readonly id: string\n readonly category: SfxCategory\n readonly priority: SfxPriority\n /** The synthesized sound playing in its place today (a recipe id of some bank), if any. */\n readonly current?: string\n}\n\nconst entries = (category: SfxCategory, list: readonly (readonly [id: string, priority: SfxPriority, current?: string])[]): SfxEntry[] =>\n list.map(([id, priority, current]) => ({ id, category, priority, ...(current ? { current } : {}) }))\n\nexport const SFX_CATALOG: readonly SfxEntry[] = [\n ...entries('armas', [\n ['pistol_22lr', 2, 'sfx_pistol'],\n ['pistol_9mm', 1, 'sfx_pistol'],\n ['pistol_45', 1, 'sfx_pistol'],\n ['revolver_38_357', 2, 'sfx_pistol'],\n ['revolver_44_50ae', 3, 'sfx_pistol'],\n ['smg_9mm_auto', 1, 'sfx_pistol'],\n ['shotgun_12', 1, 'sfx_shotgun'],\n ['rifle_5_56', 1, 'sfx_rifle'],\n ['rifle_7_62x39', 1, 'sfx_rifle'],\n ['rifle_auto_burst', 1, 'sfx_rifle'],\n ['rifle_308_3006', 2, 'sfx_rifle'],\n ['sniper_338_300wm', 2, 'sfx_rifle'],\n ['antimateriel_50bmg', 3, 'sfx_rifle'],\n ['suppressed_pistol', 2],\n ['suppressed_rifle', 2],\n ['gunshot_far_pistol', 1],\n ['gunshot_far_rifle', 1],\n ['gunshot_far_shotgun', 1],\n ['gunshot_far_heavy', 2],\n ['gunshot_tail_indoor', 1],\n ['gunshot_tail_outdoor', 1],\n ['bullet_crack_by', 2],\n ['bullet_whiz', 2],\n ['ricochet_metal', 2, 'ping'],\n ['dry_fire', 1],\n ['mag_out', 1],\n ['mag_in', 1],\n ['slide_pull_release', 1],\n ['pump_cycle', 1],\n ['casing_drop_concreto_pistol', 1],\n ['casing_drop_concreto_rifle', 1],\n ['casing_drop_concreto_shell', 1],\n ['casing_drop_madeira_pistol', 1],\n ['casing_drop_madeira_rifle', 1],\n ['casing_drop_madeira_shell', 1],\n ['casing_drop_metal_pistol', 1],\n ['casing_drop_metal_rifle', 1],\n ['casing_drop_metal_shell', 1],\n ['casing_drop_terra_pistol', 1],\n ['casing_drop_terra_rifle', 1],\n ['casing_drop_terra_shell', 1],\n ['rocket_fire', 2],\n ['smg_45_auto', 2, 'sfx_pistol'],\n ['weapon_draw', 2],\n ['suppressor_attach', 3],\n ['suppressor_detach', 3],\n ]),\n ...entries('explosoes-fogo', [\n ['explosion_grenade', 1, 'boom'],\n ['explosion_big', 1, 'boom_big'],\n ['explosion_car', 2, 'boom_big'],\n ['explosion_far', 1],\n ['debris_rain_stone', 1],\n ['molotov_break_ignite', 1, 'glass_shatter'],\n ['fire_ignite', 1, 'hiss'],\n ['fire_loop_small', 1],\n ['fire_loop_large', 1],\n ['fire_extinguish', 2, 'hiss'],\n ['gas_leak_hiss', 2],\n ['structure_collapse', 2, 'crumble'],\n ['grenade_bounce', 1],\n ['c4_plant', 2],\n ['c4_beep', 2],\n ['c4_disarm', 2],\n ]),\n ...entries('personagem', [\n ['footstep_concrete_walk', 1, 'sfx_step'],\n ['footstep_wood_walk', 1, 'sfx_step'],\n ['footstep_dirt_walk', 1, 'sfx_step'],\n ['footstep_grass_walk', 1, 'sfx_step'],\n ['footstep_gravel_walk', 1, 'sfx_step'],\n ['land_concrete', 1, 'sfx_step'],\n ['punch_swing', 1],\n ['punch_hit_body', 1, 'sfx_flesh'],\n ['kick_hit', 1, 'sfx_flesh'],\n ['knife_stab', 1],\n ['blunt_hit', 1],\n ['bite', 1, 'sfx_flesh'],\n ['body_fall', 1],\n ['player_hurt', 2],\n ['footstep_tile_walk', 1, 'sfx_step'],\n ['footstep_water_walk', 1, 'sfx_step'],\n ['footstep_grate_walk', 2, 'sfx_step'],\n ['footstep_duct_walk', 3, 'sfx_step'],\n ['ladder_climb', 2],\n ['swim', 2],\n ['zombie_groan', 1],\n ['zombie_alert', 1],\n ['zombie_attack', 1],\n ['zombie_pain', 1],\n ['zombie_claw_hit', 1, 'sfx_flesh'],\n ['zombie_claw_miss', 2],\n ]),\n ...entries('veiculos', [\n ['engine_loop_car', 1],\n ['engine_start', 1],\n ['crash_light', 1, 'crash'],\n ['crash_heavy', 1, 'crash'],\n ['car_door_open', 1, 'latch'],\n ['car_door_close', 1, 'shut_metal'],\n ['horn_car', 2, 'horn'],\n ['tire_skid_asphalt', 2],\n ]),\n ...entries('itens-portas', [\n ['item_pickup_metal', 1],\n ['can_open', 1],\n ['can_crush', 1],\n ['door_wood_open', 1, 'latch'],\n ['door_wood_close', 1, 'shut_wood'],\n ['door_creak', 1, 'creak_wood'],\n ['door_locked_rattle', 1, 'rattle'],\n ['drawer_open', 2, 'slide'],\n ['fridge_close', 2, 'shut_metal'],\n ]),\n ...entries('ambiente', [\n ['rain_loop', 2],\n ['wind_loop', 2],\n ['thunder_near', 2],\n ['thunder_far', 2],\n ['water_splash', 2],\n ['helicopter_loop', 3],\n ]),\n]\n\n/** The materials of the impact matrix, with the group whose synthesized sound plays for them today. */\nexport const SFX_MATERIALS = [\n ['steel', 'metal'],\n ['aluminium', 'metal'],\n ['wood', 'wood'],\n ['plywood', 'wood'],\n ['mdf', 'wood'],\n ['glass', 'glass'],\n ['tempered_glass', 'glass'],\n ['ceramic', 'glass'],\n ['concrete', 'masonry'],\n ['brick', 'masonry'],\n ['plaster', 'masonry'],\n ['plastic', 'soft'],\n ['fabric', 'soft'],\n ['paper', 'soft'],\n ['foliage', 'soft'],\n ['soil', 'soft'],\n ['flesh', 'soft'],\n] as const satisfies readonly (readonly [string, string])[]\nexport type SfxMaterial = (typeof SFX_MATERIALS)[number][0]\n\nexport const SFX_BLOWS = ['bullet', 'blunt', 'blade', 'break', 'drag'] as const\nexport type SfxBlow = (typeof SFX_BLOWS)[number]\n\n// the destruction renderer's synthesized sounds by material group (art scene keys), the A side of the matrix\nconst CURRENT_BY_GROUP: Readonly<Record<string, Readonly<Partial<Record<SfxBlow, string>>>>> = {\n metal: { bullet: 'clang', blunt: 'clang', blade: 'clang', break: 'clang', drag: 'drag_metal' },\n wood: { bullet: 'wood_hit', blunt: 'wood_hit', blade: 'wood_hit', break: 'crack', drag: 'drag_wood' },\n glass: { bullet: 'ping', blunt: 'ping', break: 'glass_shatter', drag: 'drag_glass' },\n masonry: { bullet: 'chip', blunt: 'chip', blade: 'chip', break: 'crumble', drag: 'drag_masonry' },\n soft: { bullet: 'thud', blunt: 'thud', blade: 'thud', break: 'thud', drag: 'drag_soft' },\n}\n\n/** The id a file of the matrix takes: `impact_<material>_<blow>` (`impact_concrete_bullet`). */\nexport const impactSoundId = (material: SfxMaterial, blow: SfxBlow): string => `impact_${material}_${blow}`\n\n/** The impact matrix as entries (the `impactos` category of the catalogue). */\nexport const SFX_IMPACTS: readonly SfxEntry[] = SFX_MATERIALS.flatMap(([material, group]) =>\n SFX_BLOWS.map((blow) => {\n const current = CURRENT_BY_GROUP[group]?.[blow]\n return { id: impactSoundId(material, blow), category: 'impactos' as const, priority: (['steel', 'wood', 'glass', 'concrete', 'brick', 'soil', 'flesh'].includes(material) && blow === 'bullet' ? 1 : 2) as SfxPriority, ...(current ? { current } : {}) }\n }),\n)\n\n/** Where an entry stands in an engine: a file registered (`file`), only the synthesized sound (`synth`), or nothing (`missing`). */\nexport type SfxState = 'file' | 'synth' | 'missing'\n\nexport function sfxState(entry: SfxEntry, has: { sample(id: string): unknown; sound(id: string): unknown }): SfxState {\n if (has.sample(entry.id)) return 'file'\n if ((entry.current && has.sound(entry.current)) || has.sound(entry.id)) return 'synth'\n return 'missing'\n}\n","/**\n * The manifest the converter (`scripts/sfx-convert.mjs`) writes next to the converted files: every sound id with its takes per layer, the file\n * facts the criteria check (rate, channels, peak, length) and where each file came from. `sampleBankFromManifest` turns it into a `SoundBank`\n * of `SampleSound`s, with the bus and the numbers of each sound given by the caller.\n */\nimport type { BusId, Falloff, SoundBank } from './recipe'\nimport type { SampleCrossover, SampleRef, SampleSound } from './sample'\n\n/** Licences the SDK accepts (the files are redistributed on npm): public domain or attribution only. */\nexport const SDK_LICENSES = ['CC0', 'CC-BY'] as const\nexport type SdkLicense = (typeof SDK_LICENSES)[number]\n\nexport type SfxFileEntry = {\n /** Path from the manifest's folder: `armas/pistol_9mm_close_01.ogg`. */\n readonly file: string\n readonly sampleRate: number\n readonly channels: number\n /** dBFS. */\n readonly peak: number\n readonly seconds: number\n readonly source: string\n readonly author: string\n readonly license: SdkLicense\n}\n\n/** The layers a file name can end in: `<id>_<layer>_<nn>` (`pistol_9mm_close_01`); a name without one is a `close` take. */\nexport const SFX_LAYERS = ['close', 'far', 'tail_in', 'tail_out'] as const\nexport type SfxLayer = (typeof SFX_LAYERS)[number]\n\nexport type SfxManifestSound = {\n readonly id: string\n readonly category: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly SfxFileEntry[]>>>\n}\n\nexport type SfxManifest = {\n readonly version: 1\n readonly format: { readonly codec: 'vorbis'; readonly sampleRate: number; readonly channels: number; readonly peakDb: number }\n readonly sounds: readonly SfxManifestSound[]\n}\n\n/** The numbers of one sound that the files do not say (bus, curve, pitch...). */\nexport type SampleDefaults = {\n readonly bus: BusId\n readonly gain?: number\n readonly pitch?: number\n readonly crossover?: SampleCrossover\n readonly tailGain?: number\n readonly falloff?: Falloff\n readonly cutoffK?: number\n readonly group?: string\n readonly priority?: number\n readonly fallback?: string\n}\n\nexport type SampleBankOptions = {\n readonly id: string\n /** Prefix of every url (where the manifest's folder is served: `/sfx/`). Default ''. */\n readonly baseUrl?: string\n /** Numbers per sound id, or one function; a sound with neither is left out (it has no bus). */\n readonly sounds?: Readonly<Record<string, SampleDefaults>>\n readonly defaults?: (sound: { readonly id: string; readonly category: string }) => SampleDefaults | undefined\n}\n\n/** The strength suffixes of a sound id (`kick_hit_heavy`): takes of the tiers of `kick_hit`, from these intensities. */\nexport const SFX_TIERS: Readonly<Record<string, number>> = { light: 0, medium: 0.34, heavy: 0.67 }\n\n/** Splits a file name (no extension) into its sound id, layer and take number. */\nexport function parseSfxName(name: string): { readonly id: string; readonly layer: SfxLayer; readonly take: number } {\n const match = /^(.*?)(?:_(close|far|tail_in|tail_out))?(?:_(\\d+))?$/.exec(name)\n const id = match?.[1] || name\n const layer = (match?.[2] as SfxLayer | undefined) ?? 'close'\n const take = match?.[3] ? Number(match[3]) : 1\n return { id, layer, take }\n}\n\n/** The base id and tier of a sound id: `kick_hit_heavy` → `kick_hit`, `heavy`. */\nexport function splitTier(id: string): { readonly base: string; readonly tier?: string } {\n const match = /^(.*)_(light|medium|heavy)$/.exec(id)\n return match ? { base: match[1] as string, tier: match[2] as string } : { base: id }\n}\n\n/** What `sampleBankFromManifest` reads of a manifest: the sounds, their layers and where each file came from (any licence string). */\nexport type SfxManifestLike = {\n readonly sounds: readonly {\n readonly id: string\n readonly category: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly { readonly file: string; readonly source: string; readonly author: string; readonly license: string }[]>>>\n }[]\n}\n\nconst refsOf = (entries: readonly { readonly file: string }[] | undefined, baseUrl: string): SampleRef[] => (entries ?? []).map((entry) => ({ url: `${baseUrl}${entry.file}` }))\n\n/** A bank of sample sounds from a manifest. */\nexport function sampleBankFromManifest(manifest: SfxManifestLike, options: SampleBankOptions): SoundBank {\n const baseUrl = options.baseUrl ?? ''\n const samples: SampleSound[] = []\n // `<id>_light`, `_medium`, `_heavy` are the tiers of `<id>`, gathered under it\n type Sound = SfxManifestLike['sounds'][number]\n const tiersOf = new Map<string, Sound[]>()\n for (const sound of manifest.sounds) {\n const { base, tier } = splitTier(sound.id)\n if (tier) tiersOf.set(base, [...(tiersOf.get(base) ?? []), sound])\n }\n const bases = new Map<string, Sound>()\n for (const sound of manifest.sounds) {\n if (!splitTier(sound.id).tier) bases.set(sound.id, sound)\n }\n for (const [base, tiers] of tiersOf) {\n if (!bases.has(base)) bases.set(base, { id: base, category: tiers[0]?.category ?? '', layers: { close: tiers[0]?.layers.close ?? [] } })\n }\n for (const sound of bases.values()) {\n const numbers = options.sounds?.[sound.id] ?? options.defaults?.(sound)\n const close = refsOf(sound.layers.close, baseUrl)\n if (!numbers || close.length === 0) continue\n const tiers = (tiersOf.get(sound.id) ?? [])\n .map((tier) => {\n const name = splitTier(tier.id).tier as string\n const tierFar = refsOf(tier.layers.far, baseUrl)\n return { name, from: SFX_TIERS[name] ?? 0, close: refsOf(tier.layers.close, baseUrl), ...(tierFar.length > 0 ? { far: tierFar } : {}) }\n })\n .sort((a, b) => a.from - b.from)\n const far = refsOf(sound.layers.far, baseUrl)\n const indoor = refsOf(sound.layers.tail_in, baseUrl)\n const outdoor = refsOf(sound.layers.tail_out, baseUrl)\n const files = [sound, ...(tiersOf.get(sound.id) ?? [])].flatMap((entry) => Object.values(entry.layers).flatMap((entries) => entries ?? []))\n samples.push({\n id: sound.id,\n bus: numbers.bus,\n close,\n ...(far.length > 0 ? { far } : {}),\n ...(tiers.length > 0 ? { tiers } : {}),\n ...(numbers.crossover ? { crossover: numbers.crossover } : {}),\n ...(indoor.length > 0 || outdoor.length > 0\n ? { tail: { ...(indoor.length > 0 ? { indoor } : {}), ...(outdoor.length > 0 ? { outdoor } : {}), ...(numbers.tailGain === undefined ? {} : { gain: numbers.tailGain }) } }\n : {}),\n ...(numbers.pitch === undefined ? {} : { pitch: numbers.pitch }),\n ...(numbers.gain === undefined ? {} : { gain: numbers.gain }),\n ...(numbers.falloff ? { falloff: numbers.falloff } : {}),\n ...(numbers.cutoffK === undefined ? {} : { cutoffK: numbers.cutoffK }),\n ...(numbers.group ? { group: numbers.group } : {}),\n ...(numbers.priority === undefined ? {} : { priority: numbers.priority }),\n ...(numbers.fallback ? { fallback: numbers.fallback } : {}),\n sources: files.map((file) => `${file.file}: ${file.source} ${file.author} ${file.license}`),\n })\n }\n return { id: options.id, samples }\n}\n","/**\n * The kit's own recorded sounds: the files in `assets/sfx/` (CC0 / CC-BY, credited in `assets/sfx/CREDITOS.md`) and the numbers each one plays\n * with. `kitSampleBank` turns the converter's manifest into a bank; `KIT_SAMPLE_ALIASES` lets a recipe id the kit already plays (`shut_wood`,\n * `rattle`...) be answered by the takes of a file id (`door_wood_shut`), so a sound that was synthesized becomes the recording with no change where\n * it is played: the recipe of the same id plays while the files load, and wherever they cannot be fetched (`file://`). `loadKitSamples` fetches the\n * manifest from where the folder is served and registers the bank on an engine.\n */\nimport { sampleBankFromManifest } from './manifest'\nimport type { SampleDefaults, SfxManifest, SfxManifestSound } from './manifest'\nimport type { BusId, SoundBank } from './recipe'\n\n/** The bus of a manifest category (the folder the file sits in). */\nexport const KIT_CATEGORY_BUS: Readonly<Record<string, BusId>> = {\n armas: 'weapons',\n impactos: 'world',\n 'explosoes-fogo': 'world',\n personagem: 'world',\n veiculos: 'world',\n 'itens-portas': 'world',\n ambiente: 'ambience',\n}\n\n/** Voice sounds go on the voices bus whatever folder they are in. */\nconst VOICE_IDS = /^(player_(hurt|death|effort|breath)|scream|zombie_)/\n\n/**\n * Recipe id → file id. The recipe keeps playing until the takes of the file id load. Hand-worked leaves (doors, drawers) of `game-destruction-three`\n * and the hand sounds of items.\n */\nexport const KIT_SAMPLE_ALIASES: Readonly<Record<string, string>> = {\n // a house door: the latch giving, the hinge, the leaf meeting the frame, a locked one shaken; a drawer on its runners\n latch: 'metal_latch',\n creak_wood: 'door_creak',\n shut_wood: 'door_wood_shut',\n rattle: 'door_locked_rattle',\n // a drawer stays on its recipe: the recorded runs (1 to 1.9 s) outlast a drawer's pull\n // an item taken in the hand (game-destruction-three grab_* keys)\n grab_hard: 'item_pickup_generic',\n grab_soft: 'item_pickup_leather',\n}\n\n/** The numbers of a sound the files do not say: the bus of its folder, a little pitch spread. */\nexport function kitSampleDefaults(sound: { readonly id: string; readonly category: string }): SampleDefaults | undefined {\n const bus = VOICE_IDS.test(sound.id) ? 'voices' : KIT_CATEGORY_BUS[sound.category]\n if (!bus) return undefined\n return { bus, pitch: sound.category === 'ambiente' || /_loop/.test(sound.id) ? 0 : 0.04 }\n}\n\nexport type KitSampleBankOptions = {\n /** Where the `assets/sfx/` folder is served (`./sfx/`). */\n readonly baseUrl?: string\n /** Recipe id → file id (default `KIT_SAMPLE_ALIASES`); `{}` adds none. */\n readonly aliases?: Readonly<Record<string, string>>\n readonly id?: string\n}\n\n/** The manifest with each alias as one more sound, holding the takes of its file id. */\nexport function withAliases(manifest: SfxManifest, aliases: Readonly<Record<string, string>>): SfxManifest {\n const byId = new Map(manifest.sounds.map((sound) => [sound.id, sound]))\n const extra: SfxManifestSound[] = []\n for (const [alias, target] of Object.entries(aliases)) {\n const sound = byId.get(target)\n if (sound && !byId.has(alias)) extra.push({ ...sound, id: alias })\n }\n return { ...manifest, sounds: [...manifest.sounds, ...extra] }\n}\n\n/** The bank of the kit's files. */\nexport function kitSampleBank(manifest: SfxManifest, options: KitSampleBankOptions = {}): SoundBank {\n return sampleBankFromManifest(withAliases(manifest, options.aliases ?? KIT_SAMPLE_ALIASES), {\n id: options.id ?? 'kit_samples',\n baseUrl: options.baseUrl ?? '',\n defaults: kitSampleDefaults,\n })\n}\n\nexport type LoadKitSamplesOptions = KitSampleBankOptions & {\n /** Gets the manifest (default `fetch` of `<baseUrl>manifest.json`). */\n readonly fetchManifest?: (url: string) => Promise<SfxManifest>\n /** Ids to load right away instead of on their first play (the sounds of the first seconds, so they are not the recipe). */\n readonly preload?: readonly string[]\n}\n\ntype Registers = { register(bank: SoundBank): void; loadSamples?(ids?: readonly string[]): Promise<unknown> }\n\n/** True when `url`, read against the page, is a `file://` one: `fetch` refuses that scheme and the browser logs an error for each try. */\nconst isFileUrl = (url: string): boolean => {\n const page = (globalThis as { location?: { href?: string } }).location?.href\n try {\n return new URL(url, page).protocol === 'file:'\n } catch {\n return false\n }\n}\n\nconst fetchJson = async (url: string): Promise<SfxManifest> => {\n // a page opened from disk keeps the recipes without asking: the refused fetch would only put an error in the console\n if (isFileUrl(url)) throw new Error(`${url}: file:// is not fetched`)\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url}: ${response.status}`)\n return (await response.json()) as SfxManifest\n}\n\n/**\n * Fetches the manifest and registers the bank on the engine. Resolves to the bank, or `null` when the manifest cannot be had (a page opened from\n * `file://`, the folder not served): the recipes keep playing, so that is not an error.\n */\nexport async function loadKitSamples(engine: Registers, options: LoadKitSamplesOptions = {}): Promise<SoundBank | null> {\n const baseUrl = options.baseUrl ?? ''\n let manifest: SfxManifest\n try {\n manifest = await (options.fetchManifest ?? fetchJson)(`${baseUrl}manifest.json`)\n } catch {\n return null\n }\n const bank = kitSampleBank(manifest, options)\n engine.register(bank)\n if (options.preload && engine.loadSamples) void engine.loadSamples(options.preload).catch(() => undefined)\n return bank\n}\n","/**\n * The owner's own sounds, kept out of the kit. Files whose licence the kit cannot redistribute (game rips, paid libraries) never enter git or npm:\n * a list of picks (`user-sounds/picks.json`: sound id, the pack and the files in it) says which file answers which sound, the script `sfx:user`\n * converts those files from the owner's folder into `.sfx-local/` (ignored by git) with a manifest, and `loadUserSamples` registers them on an\n * engine from where that folder is served.\n *\n * Each pick has a role. `primary`: the kit has no recording of that sound, so the owner's file plays. `fallback`: the kit's recording plays first;\n * the owner's file is registered under the same id only when the kit has none loaded (its manifest could not be fetched). Every pick is also\n * registered under `user:<id>`, so a panel can play the owner's take next to the kit's.\n */\nimport { sampleBankFromManifest, splitTier } from './manifest'\nimport type { SfxLayer } from './manifest'\nimport { kitSampleDefaults } from './kit-samples'\nimport type { SoundBank } from './recipe'\n\nexport const USER_SAMPLES_BANK = 'user_samples'\nexport const KIT_SAMPLES_BANK = 'kit_samples'\n/** Prefix of the id each pick is also registered under. */\nexport const USER_SOUND_PREFIX = 'user:'\n\nexport type UserSoundRole = 'primary' | 'fallback'\n\n/** One sound the owner's files answer. */\nexport type UserSoundPick = {\n readonly id: string\n readonly role: UserSoundRole\n /** The kit category (`armas`, `personagem`...): the bus and the folder of the converted files. */\n readonly category: string\n readonly label: string\n /** The pack the files come from (a folder of the owner's sounds). */\n readonly pack: string\n /** Paths inside the pack (matched by their end, so the pack may be nested differently). */\n readonly files: readonly string[]\n /** 0–10: how well the files fit the sound (rate, clipping, band). */\n readonly score: number\n readonly loop?: boolean\n}\n\nexport type UserSoundPicks = {\n readonly version: 1\n readonly author: string\n readonly license: string\n readonly picks: readonly UserSoundPick[]\n}\n\n/** One converted file, as `sfx:user` writes it. */\nexport type UserSfxFile = {\n readonly file: string\n readonly sampleRate: number\n readonly channels: number\n readonly peak: number\n readonly seconds: number\n readonly source: string\n readonly author: string\n readonly license: string\n}\n\nexport type UserSfxSound = {\n readonly id: string\n readonly category: string\n readonly role: UserSoundRole\n readonly label: string\n readonly layers: Partial<Readonly<Record<SfxLayer, readonly UserSfxFile[]>>>\n}\n\n/** The manifest `sfx:user` writes in `.sfx-local/manifest.json`. */\nexport type UserSfxManifest = {\n readonly version: 1\n readonly sounds: readonly UserSfxSound[]\n}\n\n/** Where a voice came from: the kit's recording, the owner's file, or the synthesized recipe. */\nexport type SoundSource = 'sdk' | 'user' | 'synth'\n\n/** The source of a started voice, from its kind and the bank its id is registered in. */\nexport function soundSourceOf(event: { readonly kind: 'recipe' | 'sample'; readonly bank?: string }): SoundSource {\n if (event.kind === 'recipe') return 'synth'\n return event.bank === USER_SAMPLES_BANK ? 'user' : 'sdk'\n}\n\nexport type UserSampleBankOptions = {\n readonly baseUrl?: string\n /** True for an id the kit already plays from a file: a `fallback` pick is then only registered under `user:<id>`. */\n readonly kitHas?: (id: string) => boolean\n}\n\nexport type UserSampleBankResult = {\n readonly bank: SoundBank\n /** Ids the owner's files now answer (primary picks, and fallbacks the kit lacks). */\n readonly playing: readonly string[]\n /** Fallback ids the kit answers, kept under `user:<id>`. */\n readonly behindKit: readonly string[]\n}\n\n/** The bank of the owner's converted files. */\nexport function userSampleBank(manifest: UserSfxManifest, options: UserSampleBankOptions = {}): UserSampleBankResult {\n const playing: string[] = []\n const behindKit: string[] = []\n const sounds: UserSfxSound[] = []\n for (const picked of manifest.sounds) {\n // a strength tier (`mag_seat_medium`) answers its base id (`mag_seat`), the id the kit's tiers are played by\n const sound = { ...picked, id: splitTier(picked.id).base }\n sounds.push({ ...sound, id: `${USER_SOUND_PREFIX}${sound.id}` })\n if (sound.role === 'fallback' && options.kitHas?.(sound.id)) {\n behindKit.push(sound.id)\n continue\n }\n sounds.push(sound)\n playing.push(sound.id)\n }\n const bank = sampleBankFromManifest(\n { sounds },\n {\n id: USER_SAMPLES_BANK,\n baseUrl: options.baseUrl ?? '',\n defaults: (sound) => kitSampleDefaults({ id: sound.id.replace(USER_SOUND_PREFIX, ''), category: sound.category }),\n },\n )\n return { bank, playing, behindKit }\n}\n\nexport type LoadUserSamplesOptions = UserSampleBankOptions & {\n readonly fetchManifest?: (url: string) => Promise<UserSfxManifest>\n}\n\ntype Registers = { register(bank: SoundBank): void; readonly registry?: { sample(id: string): unknown } }\n\nconst fetchManifestJson = async (url: string): Promise<UserSfxManifest> => {\n const page = (globalThis as { location?: { href?: string } }).location?.href\n if (new URL(url, page ?? 'http://localhost/').protocol === 'file:') throw new Error(`${url}: file:// is not fetched`)\n const response = await fetch(url)\n if (!response.ok) throw new Error(`${url}: ${response.status}`)\n return (await response.json()) as UserSfxManifest\n}\n\n/**\n * Fetches `<baseUrl>manifest.json` (default `./sfx-local/`) and registers the owner's files. Call it after the kit's bank loaded, so a fallback\n * pick stays behind the kit's recording. Resolves to `null` when the folder is not there (a machine without the owner's sounds): nothing changes.\n */\nexport async function loadUserSamples(engine: Registers, options: LoadUserSamplesOptions = {}): Promise<UserSampleBankResult | null> {\n const baseUrl = options.baseUrl ?? './sfx-local/'\n let manifest: UserSfxManifest\n try {\n manifest = await (options.fetchManifest ?? fetchManifestJson)(`${baseUrl}manifest.json`)\n } catch {\n return null\n }\n const kitHas = options.kitHas ?? ((id: string): boolean => Boolean(engine.registry?.sample(id)))\n const result = userSampleBank(manifest, { baseUrl, kitHas })\n engine.register(result.bank)\n return result\n}\n","{\n \"sources\": [\"jogo:L62089-62107\"],\n \"note\": \"The game's sfx table P: [lowpass cutoff Hz, peak gain, seconds]. Played as a noise burst with the game's distance curve (falloff game_sfx) and a 0.05 s tail. Team names in `team`.\",\n \"classes\": [\n { \"id\": \"pistol\", \"team\": \"pistola\", \"bus\": \"weapons\", \"cutoff\": 1800, \"gain\": 0.9, \"seconds\": 0.18 },\n { \"id\": \"shotgun\", \"team\": \"escopeta\", \"bus\": \"weapons\", \"cutoff\": 900, \"gain\": 1.2, \"seconds\": 0.35 },\n { \"id\": \"rifle\", \"team\": \"fuzil\", \"bus\": \"weapons\", \"cutoff\": 1400, \"gain\": 1.1, \"seconds\": 0.28 },\n { \"id\": \"long_rifle\", \"team\": \"rifle\", \"bus\": \"weapons\", \"cutoff\": 1100, \"gain\": 1.3, \"seconds\": 0.45 },\n { \"id\": \"impact\", \"team\": \"impacto\", \"bus\": \"world\", \"cutoff\": 2500, \"gain\": 0.25, \"seconds\": 0.05 },\n { \"id\": \"flesh\", \"team\": \"carne\", \"bus\": \"world\", \"cutoff\": 600, \"gain\": 0.35, \"seconds\": 0.08 },\n { \"id\": \"step\", \"team\": \"passo\", \"bus\": \"world\", \"cutoff\": 400, \"gain\": 0.08, \"seconds\": 0.05 },\n { \"id\": \"glass\", \"team\": \"vidro\", \"bus\": \"world\", \"cutoff\": 5000, \"gain\": 0.5, \"seconds\": 0.3 },\n { \"id\": \"wood\", \"team\": \"madeira\", \"bus\": \"world\", \"cutoff\": 700, \"gain\": 0.5, \"seconds\": 0.2 },\n { \"id\": \"reload\", \"team\": \"recarga\", \"bus\": \"weapons\", \"cutoff\": 3000, \"gain\": 0.15, \"seconds\": 0.06 },\n { \"id\": \"empty\", \"team\": \"vazio\", \"bus\": \"weapons\", \"cutoff\": 4000, \"gain\": 0.12, \"seconds\": 0.03 },\n { \"id\": \"explosion\", \"team\": \"explosao\", \"bus\": \"world\", \"cutoff\": 200, \"gain\": 1.6, \"seconds\": 1.4 }\n ],\n \"fallback\": { \"id\": \"unknown\", \"team\": \"(any other name)\", \"bus\": \"world\", \"cutoff\": 1000, \"gain\": 0.5, \"seconds\": 0.1 }\n}\n","import { DISTANCE_CURVES } from '../falloff'\nimport type { BusId, SoundBank, SoundRecipe } from '../recipe'\nimport gameSfxJson from '../data/game-sfx.json'\n\n/** One row of the game's `sfx` table (jogo L62096–62100): lowpass cutoff, peak gain and seconds of a noise burst. */\nexport type NoiseClass = {\n readonly id: string\n /** The name in the team code (`pistola`, `vidro`...). */\n readonly team: string\n readonly bus: BusId\n readonly cutoff: number\n readonly gain: number\n readonly seconds: number\n}\n\ntype GameSfxTable = { readonly sources: readonly string[]; readonly classes: readonly NoiseClass[]; readonly fallback: NoiseClass }\n\nconst GAME_SFX = gameSfxJson as unknown as GameSfxTable\n\n/** The 12 game classes, in the table's order. */\nexport const GAME_SFX_CLASSES: readonly NoiseClass[] = GAME_SFX.classes\n/** What the game plays for a name it does not know: `[1000, 0.5, 0.1]`. */\nexport const GAME_SFX_FALLBACK: NoiseClass = GAME_SFX.fallback\n\n/**\n * A class as a recipe: noise from a random point, the class lowpass (muffled by distance), the peak set at once and an exponential fall to 0.001 over\n * the class seconds, stopped 0.05 s later; the game's distance curve, silent below 0.01. Built in the game's `sfx` order (`burst`).\n */\nexport function noiseClassRecipe(row: NoiseClass, id = `sfx_${row.id}`): SoundRecipe {\n return {\n id,\n bus: row.bus,\n order: 'burst',\n duration: row.seconds,\n tail: 0.05,\n layers: [\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: row.cutoff } }] },\n envelope: [\n [0, row.gain, 'set'],\n ['1d', 0.001, 'exp', 'fixed'],\n ],\n },\n ],\n falloff: DISTANCE_CURVES.game_sfx,\n sources: [...GAME_SFX.sources.map((source) => `${source} ${row.team}`)],\n }\n}\n\n/** The game's classes as a bank (`sfx_pistol`... and `sfx_unknown`). Subject banks pick their own classes from `GAME_SFX_CLASSES`. */\nexport const GAME_SFX_BANK: SoundBank = { id: 'game_sfx', sounds: [...GAME_SFX_CLASSES, GAME_SFX_FALLBACK].map((row) => noiseClassRecipe(row)) }\n","// The art scene's synthesis primitives (cena L1322-L1328) as recipe layers, shared by every subject bank that ports a `sfx.*` of the page: the\n// materials in `destruction-three`, the voices and wounds in `characters-three`. Each helper writes the layer the team routine builds, with its\n// fields in the order the routine draws its random numbers, so a recipe built from them leaves the trace of the team code.\nimport { DISTANCE_CURVES } from '../falloff'\nimport type { BusId, Envelope, Layer, ParamRef, Range, SoundRecipe } from '../recipe'\n\nconst ATTACK = 0.002\n\n/** A length in seconds: a number, a `[min, max]` range or a named number. */\nexport type SceneLength = number | readonly [number, number] | ParamRef\n\n// the layer is `attack + d` long (the art scene's gain rises over `a` and falls over `d`)\nfunction lengthOf(d: SceneLength, attack: number): Range {\n if (typeof d === 'number') return attack + d\n if (Array.isArray(d)) return [attack + d[0], attack + d[1]] as const\n return { ...(d as ParamRef), add: ((d as ParamRef).add ?? 0) + attack }\n}\n\nconst envelope = (attack: number): Envelope => [\n [0, 0.0001, 'set', 'fixed'],\n [attack, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n]\n\nexport type SceneNoise = {\n readonly type?: BiquadFilterType\n readonly f: Range\n /** The filter slides here over `d` (needs a fixed `d`). */\n readonly f2?: number\n readonly q?: number\n readonly a?: number\n readonly d: SceneLength\n readonly vol: Range\n readonly wet?: number\n readonly delay?: Range\n}\n\n/** `sNoise` (cena L1323): noise from a random point, a filter (default lowpass, Q 0.7), the gain rising over `a` and falling over `d`. */\nexport function sceneNoise(o: SceneNoise): Layer {\n const a = o.a ?? ATTACK\n const over = typeof o.d === 'number' ? o.d : 0\n return {\n filters: {\n mode: 'serial',\n bank: [{ type: o.type ?? 'lowpass', frequency: o.f2 === undefined ? { set: o.f } : { set: o.f, to: o.f2, curve: 'exp', over }, q: o.q ?? 0.7 }],\n },\n duration: lengthOf(o.d, a),\n gain: o.vol,\n ...(o.delay === undefined ? {} : { at: o.delay }),\n ...(o.wet === undefined ? {} : { wet: o.wet }),\n source: { kind: 'noise', offset: 'random', offsetScale: 1.5, loop: true },\n envelope: envelope(a),\n }\n}\n\nexport type SceneTone = { readonly wave?: OscillatorType; readonly f: Range; readonly f2?: number; readonly d: SceneLength; readonly vol: Range; readonly wet?: number; readonly delay?: Range }\n\n/** `sTone` (cena L1324): an oscillator sliding from `f` to `f2` (back to `f` when none), the gain rising over 0.002 s and falling over `d`. */\nexport function sceneTone(o: SceneTone): Layer {\n return {\n source: { kind: 'osc', wave: o.wave ?? 'sine', frequency: { from: o.f, to: o.f2 ?? 'from', curve: 'exp', over: 'duration' } },\n duration: lengthOf(o.d, ATTACK),\n gain: o.vol,\n ...(o.delay === undefined ? {} : { at: o.delay }),\n ...(o.wet === undefined ? {} : { wet: o.wet }),\n envelope: envelope(ATTACK),\n }\n}\n\nexport type SceneVoice = {\n /** Start and end frequency of the sweep (the page ramps linearly from `f0` to `f1` over the length). */\n readonly f0: Range\n readonly f1: Range\n /** Length in seconds. */\n readonly d: SceneLength\n /** Centre of the first and second formant (Q 4 and 6) and of the breath band (Q 1.1). */\n readonly fA: Range\n readonly fB: Range\n /** Level of the breath noise. */\n readonly noise: Range\n readonly vol: Range\n readonly wave?: OscillatorType\n}\n\n/**\n * `voice` (cena L1325): an oscillator swept from `f0` to `f1` with a vibrato of 4 to 10 Hz (depth 0.08 of `f0`) through two formant bands plus a band of\n * breath noise, summed and boosted 3.2 times, the gain rising over 0.1 s, held to 0.6 of the length and falling; reverb send 0.45. It is the one\n * layer the page builds with `voice(...)`, so a scream is two of them.\n */\nexport function sceneVoice(o: SceneVoice): Layer {\n return {\n duration: lengthOf(o.d, 0),\n gain: o.vol,\n wet: 0.45,\n source: {\n kind: 'formant_voice',\n wave: o.wave ?? 'sawtooth',\n frequency: { from: o.f0, to: o.f1, curve: 'linear', over: 'duration' },\n vibrato: { rate: [4, 10], depth: 0.08 },\n formants: [\n { frequency: o.fA, q: 4 },\n { frequency: o.fB, q: 6 },\n ],\n breath: { frequency: o.fB, q: 1.1, gain: o.noise },\n mix: 3.2,\n },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.1, 1, 'exp'],\n ['0.6d', 1, 'set'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n }\n}\n\n/** The layer played `count` times (a team `for` loop whose body draws numbers): each pass is its own layer, so the draws stay in the loop's order. */\nexport const sceneMany = (count: number, make: () => Layer): Layer[] => Array.from({ length: count }, make)\n\nexport type SceneRecipeOptions = {\n /** Named numbers drawn first (`PlayOptions.params` can override them). */\n readonly vars?: SoundRecipe['vars']\n readonly bus?: BusId\n readonly group?: string\n}\n\n/** A recipe in the art scene's mix: positional with the art scene's curve (`vol / (1 + d² × 0.008)`) and pan; `line` is the team code it comes from (`cena:<line>`). */\nexport function sceneRecipe(id: string, layers: readonly Layer[], line: string, options: SceneRecipeOptions = {}): SoundRecipe {\n return {\n id,\n bus: options.bus ?? 'world',\n pan: true,\n layers,\n falloff: DISTANCE_CURVES.art_scene,\n ...(options.vars ? { vars: options.vars } : {}),\n ...(options.group ? { group: options.group } : {}),\n sources: [`cena:${line}`],\n }\n}\n","{\n \"id\": \"crowd_rumble\",\n \"bus\": \"ambience\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"noise\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 160 } }] },\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\"jogo:L62116 horda: noise through a 160 Hz lowpass\", \"jogo:L70424 level min(0.16, near × 0.0016)\", \"temporary home until the crowd package (Q12)\"]\n}\n","{\n \"id\": \"engine_saw\",\n \"bus\": \"world\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"osc\", \"wave\": \"sawtooth\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 400 } }] },\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\n \"jogo:L62115 motor: sawtooth through a 400 Hz lowpass\",\n \"jogo:L70421 level 0.035 + speed × 0.003, frequency 38 + speed × 7 (the host drives `set`)\",\n \"temporary home until the vehicles package (Q12)\"\n ]\n}\n","{\n \"id\": \"horn\",\n \"bus\": \"world\",\n \"order\": \"chord\",\n \"duration\": 0.6,\n \"tail\": 0.02,\n \"layers\": [\n { \"source\": { \"kind\": \"osc\", \"wave\": \"square\", \"frequency\": { \"set\": 415 } }, \"envelope\": [[0, 0.08, \"set\"], [0.6, 0.0001, \"set\", \"fixed\"]] },\n { \"source\": { \"kind\": \"osc\", \"wave\": \"square\", \"frequency\": { \"set\": 523 } }, \"envelope\": [[0, 0.08, \"set\"], [0.6, 0.0001, \"set\", \"fixed\"]] }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"jogo:L70272-70276 buzina: squares at 415 and 523 Hz, 0.08 for 0.6 s\", \"temporary home until the vehicles package (Q12)\"]\n}\n","{\n \"id\": \"radio_static\",\n \"bus\": \"world\",\n \"order\": \"static\",\n \"duration\": 0.6,\n \"layers\": [\n {\n \"source\": { \"kind\": \"noise\", \"offset\": \"random\" },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"bandpass\", \"frequency\": { \"set\": 1800 }, \"q\": 0.8 }] },\n \"envelope\": [[0, 0.06, \"set\"], [\"1d\", 0.001, \"exp\", \"fixed\"]]\n }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"jogo:L69998-70004 chiado: noise through a 1800 Hz bandpass (Q 0.8), 0.06 falling over 0.6 s\", \"temporary home until the props or radio package (Q12)\"]\n}\n","{\n \"id\": \"rotor_blades\",\n \"bus\": \"world\",\n \"order\": \"game_loop\",\n \"source\": { \"kind\": \"noise\", \"loop\": true },\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 300 } }] },\n \"modulators\": [{ \"target\": \"gain\", \"rate\": 11, \"depth\": 0.5, \"base\": 0.5 }],\n \"smoothing\": { \"volume\": 0.15, \"frequency\": 0.08 },\n \"startAbove\": 0.002,\n \"sources\": [\n \"jogo:L62116-62120 rotor: noise through a 300 Hz lowpass, blade beat as an 11 Hz LFO of 0.5 on a 0.5 gain stage\",\n \"jogo:L70426 level min(0.5, 30 / (distance + 10))\",\n \"temporary home until the vehicles package (Q12)\"\n ]\n}\n","{\n \"id\": \"siren\",\n \"bus\": \"world\",\n \"order\": \"siren\",\n \"duration\": 9,\n \"tail\": 0.2,\n \"layers\": [\n {\n \"wet\": 1.5,\n \"source\": { \"kind\": \"osc\", \"wave\": \"sine\", \"frequency\": { \"set\": 850 } },\n \"modulators\": [{ \"target\": \"frequency\", \"rate\": 0.18, \"depth\": 280 }],\n \"filters\": { \"mode\": \"serial\", \"bank\": [{ \"type\": \"lowpass\", \"frequency\": { \"set\": 1400 } }] },\n \"envelope\": [[0, 0.0001, \"set\", \"fixed\"], [2, 0.035, \"exp\"], [6, 0.035, \"set\"], [9, 0.0001, \"exp\", \"fixed\"]]\n }\n ],\n \"falloff\": { \"model\": \"none\" },\n \"sources\": [\"cena:L1369 siren: 850 Hz sine swept ±280 Hz at 0.18 Hz, 1400 Hz lowpass, 0.035 for 9 s, reverb send 1.5\", \"temporary home until the vehicles package (Q12)\"]\n}\n","// Sounds whose subject has no package yet (Q12): they move to vehicles, crowd and props in Phases 7 and 8 and stay here as re-exports.\nimport type { LoopRecipe, SoundBank, SoundRecipe } from '../recipe'\nimport crowdRumble from './crowd_rumble.json'\nimport engineSaw from './engine_saw.json'\nimport horn from './horn.json'\nimport radioStatic from './radio_static.json'\nimport rotorBlades from './rotor_blades.json'\nimport siren from './siren.json'\n\nexport const LIBRARY_SOUNDS: readonly SoundRecipe[] = [horn, radioStatic, siren] as unknown as readonly SoundRecipe[]\nexport const LIBRARY_LOOPS: readonly LoopRecipe[] = [engineSaw, rotorBlades, crowdRumble] as unknown as readonly LoopRecipe[]\nexport const LIBRARY_BANK: SoundBank = { id: 'library', sounds: LIBRARY_SOUNDS, loops: LIBRARY_LOOPS }\n","// The sounds of a vehicle's cabin and body switches (the turn signal relay, the starter, the alarm, the wipers, the belt chime, the lock chirp). Like the\n// library's horn, they live here until the vehicles package has a bank of its own (Q12). Synthesized; no recording.\nimport type { SoundBank, SoundRecipe } from '../recipe'\n\nexport const CABIN_SOUNDS: readonly SoundRecipe[] = [\n {\n id: 'blinker_tick',\n bus: 'world',\n duration: 0.03,\n layers: [\n // the relay: a click of bright noise and a short low knock\n { source: { kind: 'noise', offset: 'random' }, filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 2600 } }] }, envelope: [[0, 0.22, 'set'], [0.025, 0.0001, 'exp', 'fixed']] },\n { source: { kind: 'osc', wave: 'triangle', frequency: { set: 180 } }, envelope: [[0, 0.12, 'set'], [0.03, 0.0001, 'exp', 'fixed']] },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'starter_crank',\n bus: 'world',\n duration: 0.9,\n layers: [\n // the starter motor turning the engine over: low noise chopped at the compression strokes\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 420 } }] },\n modulators: [{ target: 'gain', wave: 'square', rate: 11, depth: 0.08, base: 0.1 }],\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.05, 0.25, 'linear'], [0.8, 0.22, 'set'], [0.9, 0.0001, 'exp', 'fixed']],\n },\n { source: { kind: 'osc', wave: 'sawtooth', frequency: { set: 95, to: 120, curve: 'linear', over: 0.9 } }, filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 300 } }] }, envelope: [[0, 0.04, 'set'], [0.9, 0.0001, 'exp', 'fixed']] },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'car_alarm',\n bus: 'world',\n order: 'siren',\n duration: 3,\n tail: 0.1,\n layers: [\n // the whoop of a car alarm: a square swept up and down three times a second\n {\n source: { kind: 'osc', wave: 'square', frequency: { set: 1100 } },\n modulators: [{ target: 'frequency', wave: 'triangle', rate: 3, depth: 420 }],\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 2600 } }] },\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.05, 0.05, 'linear'], [2.9, 0.05, 'set'], [3, 0.0001, 'exp', 'fixed']],\n },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'alarm_chirp',\n bus: 'world',\n duration: 0.1,\n layers: [{ source: { kind: 'osc', wave: 'square', frequency: { set: 2300 } }, repeat: { count: 2, spacing: 0.16 }, envelope: [[0, 0.05, 'set'], [0.09, 0.0001, 'exp', 'fixed']] }],\n falloff: { model: 'none' },\n },\n {\n id: 'wiper_swish',\n bus: 'world',\n duration: 0.45,\n layers: [\n {\n source: { kind: 'noise', offset: 'random' },\n filters: { mode: 'serial', bank: [{ type: 'bandpass', frequency: { set: 700, to: 1100, curve: 'linear', over: 0.45 }, q: 1.2 }] },\n envelope: [[0, 0.0001, 'set', 'fixed'], [0.2, 0.06, 'linear'], [0.45, 0.0001, 'exp', 'fixed']],\n },\n ],\n falloff: { model: 'none' },\n },\n {\n id: 'seatbelt_chime',\n bus: 'world',\n duration: 0.5,\n layers: [{ source: { kind: 'osc', wave: 'sine', frequency: { set: 880 } }, repeat: { count: 3, spacing: 0.7 }, envelope: [[0, 0.06, 'set'], [0.5, 0.0001, 'exp', 'fixed']] }],\n falloff: { model: 'none' },\n },\n] as unknown as readonly SoundRecipe[]\n\nexport const CABIN_BANK: SoundBank = { id: 'vehicle_cabin', sounds: CABIN_SOUNDS, loops: [] }\n","// Foley of the hand: items picked up, opened, drunk and eaten, and the doors, lids and drawers of furniture and vehicles. Synthesised stand-ins under the\n// ids of the sound list (`sons/checklist-sons.md` 5.7 and the car doors of 5.6), so a recorded take filed under the same id replaces the recipe without\n// touching the code that plays it. Every recipe draws its numbers from ranges (pitch about ±4 %, timing and level), so no two plays are the same, and\n// falls off faster than a gunshot and loses its highs with distance: a latch is a near sound.\nimport type { Falloff, Layer, SoundBank, SoundRecipe } from '../recipe'\nimport { sceneMany as many, sceneNoise as noise, sceneTone as tone } from './scene'\n\n/** Small sounds of the hand: `vol / (1 + d² × 0.02)`, lowpass cutoffs `/ (1 + d × 0.04)`, silent below 0.004 (a latch at 10 m is a third, at 50 m gone). */\nexport const FOLEY_FALLOFF: Falloff = {\n model: 'inverse_square',\n k: 0.02,\n cutoffK: 0.04,\n minGain: 0.004,\n}\n\n/** ±`pct` around `f`: the range a recipe draws a frequency from. */\nconst vary = (f: number, pct = 0.04): readonly [number, number] => [Math.round(f * (1 - pct)), Math.round(f * (1 + pct))]\n\nconst foley = (id: string, layers: readonly Layer[], note: string): SoundRecipe => ({\n id,\n bus: 'world',\n pan: true,\n layers,\n falloff: FOLEY_FALLOFF,\n sources: [`sdk: ${note}`],\n})\n\n/** The click of a latch or a catch: a short band of noise and a tick of metal. */\nconst click = (f: number, vol: number, delay: readonly [number, number] | number = 0): Layer[] => [\n noise({\n type: 'bandpass',\n f: vary(f, 0.08),\n q: 4,\n d: [0.018, 0.03],\n vol: [vol * 0.85, vol * 1.1],\n delay,\n }),\n tone({\n f: vary(f * 0.8, 0.06),\n f2: Math.round(f * 0.62),\n d: [0.015, 0.025],\n vol: vol * 0.18,\n delay,\n }),\n]\n\n/** A leaf meeting its frame: the body (a falling tone), the board or panel (a band of noise) and the latch catching right after. */\nconst meet = (body: number, panel: number, vol: number, latch: number): Layer[] => [\n tone({\n f: vary(body),\n f2: Math.round(body * 0.5),\n d: [0.12, 0.16],\n vol: [vol * 0.9, vol * 1.1],\n }),\n noise({\n type: 'bandpass',\n f: vary(panel, 0.06),\n q: 1.2,\n d: [0.08, 0.12],\n vol: [vol * 0.9, vol * 1.1],\n wet: 0.25,\n }),\n ...click(latch, vol * 0.45, [0.012, 0.028]),\n]\n\n/** The doors and lids of furniture and vehicles, by what the leaf is (the room picks one from the item, else from the leaf's material). */\nexport const LEAF_FOLEY: readonly SoundRecipe[] = [\n // a wooden house door or wardrobe door: latch, a short creak, the leaf on the frame (the hard slam adds the frame rattling)\n foley('door_wood_open', click(2400, 0.4), 'the latch of a wooden door giving'),\n foley(\n 'door_creak',\n [\n tone({ f: [190, 240], f2: 310, d: [0.4, 0.55], vol: [0.04, 0.06] }),\n noise({\n type: 'bandpass',\n f: [480, 560],\n q: 6,\n a: 0.05,\n d: [0.35, 0.5],\n vol: [0.1, 0.14],\n }),\n ],\n 'a wooden hinge turning',\n ),\n foley('door_wood_close', meet(120, 600, 0.55, 2400), 'a wooden leaf meeting its frame'),\n foley(\n 'door_wood_slam',\n [\n ...meet(110, 560, 0.85, 2300),\n ...many(3, () =>\n noise({\n type: 'bandpass',\n f: [900, 1500],\n q: 3,\n d: 0.03,\n vol: [0.08, 0.14],\n delay: [0.05, 0.18],\n }),\n ),\n ],\n 'a wooden door slammed: the frame and the hinges rattle after the hit',\n ),\n // a metal door or gate: a hollow panel that rings a little\n foley('door_metal_open_close', [...meet(160, 900, 0.55, 2000), tone({ f: vary(1250), f2: 1150, d: [0.1, 0.16], vol: 0.06, wet: 0.3 })], 'a metal door or gate meeting its frame'),\n foley(\n 'door_creak_metal',\n [\n tone({ f: [620, 760], f2: 900, d: [0.3, 0.4], vol: [0.03, 0.045] }),\n noise({\n type: 'bandpass',\n f: [1300, 1500],\n q: 8,\n a: 0.04,\n d: [0.25, 0.35],\n vol: [0.07, 0.09],\n }),\n ],\n 'a metal hinge turning',\n ),\n // the handle of a locked door shaken: the latch knocking in its keeper, five to seven times in half a second\n foley(\n 'door_locked_rattle',\n [\n ...many(6, () =>\n noise({\n type: 'bandpass',\n f: [1600, 2600],\n q: 3,\n d: [0.025, 0.04],\n vol: [0.22, 0.34],\n delay: [0, 0.45],\n }),\n ),\n ...many(3, () =>\n tone({\n f: [170, 210],\n f2: 120,\n d: 0.05,\n vol: [0.12, 0.18],\n delay: [0.02, 0.4],\n }),\n ),\n ],\n 'the handle of a locked door shaken: latch knocks and the leaf thumping in its frame',\n ),\n // a fridge: the rubber seal lets go with a soft suck, the bottles in the door clink; closing it is a soft thump and the seal pulling shut\n foley(\n 'fridge_open',\n [\n noise({\n type: 'lowpass',\n f: [320, 380],\n a: 0.03,\n d: [0.14, 0.2],\n vol: [0.32, 0.4],\n }),\n noise({\n type: 'bandpass',\n f: [800, 950],\n f2: 1400,\n q: 2,\n a: 0.02,\n d: 0.12,\n vol: [0.08, 0.12],\n }),\n ...many(2, () =>\n tone({\n f: [2600, 4200],\n d: [0.04, 0.08],\n vol: [0.015, 0.03],\n delay: [0.08, 0.22],\n }),\n ),\n ],\n 'a fridge door: the seal letting go and the bottles in the door',\n ),\n foley(\n 'fridge_close',\n [\n tone({ f: vary(85), f2: 45, d: [0.1, 0.13], vol: [0.38, 0.46] }),\n noise({\n type: 'lowpass',\n f: [520, 620],\n d: [0.08, 0.12],\n vol: [0.3, 0.36],\n }),\n noise({\n type: 'lowpass',\n f: [260, 320],\n a: 0.02,\n d: 0.1,\n vol: [0.12, 0.18],\n delay: [0.04, 0.07],\n }),\n ...many(2, () =>\n tone({\n f: [2600, 4200],\n d: [0.04, 0.07],\n vol: [0.015, 0.03],\n delay: [0.03, 0.12],\n }),\n ),\n ],\n 'a fridge door shut: a soft thump, the seal pulling and the bottles',\n ),\n // a microwave: the spring catch of the door, plastic on plastic\n foley(\n 'microwave_open',\n [\n ...click(1800, 0.34),\n tone({\n f: [3000, 3400],\n f2: 2800,\n d: 0.05,\n vol: 0.025,\n delay: [0.01, 0.02],\n }),\n ],\n 'the spring catch of a microwave door',\n ),\n foley(\n 'microwave_close',\n [\n noise({\n type: 'bandpass',\n f: [1200, 1450],\n q: 2.5,\n d: [0.04, 0.06],\n vol: [0.36, 0.44],\n }),\n tone({ f: vary(180), f2: 120, d: 0.05, vol: [0.16, 0.22] }),\n ...click(2200, 0.2, [0.008, 0.016]),\n ],\n 'a microwave door clacking shut',\n ),\n foley('microwave_beep', [tone({ wave: 'square', f: 2000, d: 0.12, vol: 0.05 })], 'the beep of a microwave'),\n // drawers and sliding leaves: the runners, then the stop\n foley(\n 'drawer_open',\n [\n noise({\n type: 'bandpass',\n f: [620, 780],\n q: 2,\n a: 0.04,\n d: [0.28, 0.36],\n vol: [0.18, 0.24],\n }),\n noise({ type: 'bandpass', f: [2000, 2400], q: 5, d: 0.28, vol: 0.04 }),\n ...click(1400, 0.16, [0.28, 0.34]),\n ],\n 'a drawer on its runners and its stop',\n ),\n foley(\n 'drawer_close',\n [\n noise({\n type: 'bandpass',\n f: [620, 780],\n q: 2,\n a: 0.03,\n d: [0.2, 0.28],\n vol: [0.18, 0.24],\n }),\n tone({\n f: vary(150),\n f2: 90,\n d: 0.08,\n vol: [0.22, 0.3],\n delay: [0.2, 0.26],\n }),\n ],\n 'a drawer pushed home',\n ),\n]\n\n/** What the hand does with an item: picking it up by what it is made of, throwing it, and the uses (opening, drinking, eating, first aid). */\nexport const ITEM_FOLEY: readonly SoundRecipe[] = [\n // the hand closing on the item: a touch of skin and cloth, then the item's own small sound\n foley(\n 'item_pickup_metal',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n tone({\n f: [1900, 2600],\n f2: 1700,\n d: [0.05, 0.08],\n vol: [0.06, 0.09],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a metal thing',\n ),\n foley(\n 'item_pickup_plastic',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'bandpass',\n f: [1500, 1900],\n q: 3,\n d: 0.03,\n vol: [0.15, 0.21],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a plastic thing',\n ),\n foley(\n 'item_pickup_glass',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.15 }),\n tone({\n f: [3200, 4200],\n d: [0.05, 0.08],\n vol: [0.038, 0.06],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a glass thing',\n ),\n foley(\n 'item_pickup_paper',\n [\n noise({\n type: 'highpass',\n f: [2600, 3400],\n a: 0.01,\n d: [0.1, 0.14],\n vol: [0.12, 0.18],\n }),\n noise({ type: 'bandpass', f: [800, 1000], q: 1, d: 0.05, vol: 0.12 }),\n ],\n 'picking up paper or cardboard',\n ),\n foley(\n 'item_pickup_fabric',\n [\n noise({\n type: 'bandpass',\n f: [900, 1300],\n q: 0.8,\n a: 0.02,\n d: [0.12, 0.16],\n vol: [0.15, 0.21],\n }),\n ],\n 'picking up cloth',\n ),\n foley(\n 'item_pickup_wood',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'bandpass',\n f: [900, 1100],\n q: 2,\n d: 0.04,\n vol: [0.15, 0.21],\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up a wooden thing',\n ),\n foley(\n 'item_pickup_food',\n [\n noise({ type: 'bandpass', f: [700, 900], q: 1, d: 0.06, vol: 0.18 }),\n noise({\n type: 'lowpass',\n f: [500, 650],\n d: 0.05,\n vol: 0.12,\n delay: [0.01, 0.03],\n }),\n ],\n 'picking up food',\n ),\n foley(\n 'item_throw',\n [\n noise({\n type: 'bandpass',\n f: [450, 650],\n f2: 1400,\n q: 1.5,\n a: 0.05,\n d: 0.18,\n vol: [0.1, 0.14],\n }),\n ],\n 'the arm throwing something: air',\n ),\n // a can: the tab cracks, the gas hisses out; drinking is gulps; crushing it crumples the sheet\n foley(\n 'can_open',\n [\n ...click(3200, 0.36),\n noise({\n type: 'highpass',\n f: [3600, 4400],\n a: 0.005,\n d: [0.22, 0.3],\n vol: [0.16, 0.22],\n delay: [0.012, 0.02],\n }),\n ...many(5, () => tone({ f: [4000, 7000], d: 0.02, vol: 0.01, delay: [0.05, 0.4] })),\n ],\n 'the tab of a can and the gas hissing out',\n ),\n foley(\n 'can_crush',\n [\n noise({\n type: 'bandpass',\n f: [1600, 2200],\n q: 1.2,\n d: [0.18, 0.25],\n vol: [0.3, 0.38],\n }),\n ...many(6, () =>\n tone({\n f: [1200, 3400],\n f2: 900,\n d: 0.03,\n vol: [0.03, 0.06],\n delay: [0, 0.2],\n }),\n ),\n ],\n 'a can crushed in the hand',\n ),\n foley(\n 'can_puncture_spray',\n [\n noise({\n type: 'highpass',\n f: [2400, 3000],\n a: 0.005,\n d: [0.5, 0.7],\n vol: [0.2, 0.26],\n }),\n noise({ type: 'bandpass', f: [600, 800], q: 2, d: 0.4, vol: 0.06 }),\n ],\n 'a can holed: the jet hissing out',\n ),\n foley(\n 'bottle_open',\n [\n ...many(5, () =>\n noise({\n type: 'bandpass',\n f: [2200, 3000],\n q: 4,\n d: 0.008,\n vol: [0.1, 0.16],\n delay: [0, 0.18],\n }),\n ),\n noise({\n type: 'highpass',\n f: 3800,\n a: 0.005,\n d: 0.12,\n vol: [0.06, 0.1],\n delay: [0.18, 0.22],\n }),\n ],\n 'the screw cap of a bottle turning off',\n ),\n foley(\n 'drink_gulp',\n [\n noise({\n type: 'lowpass',\n f: [280, 360],\n a: 0.02,\n d: [0.1, 0.14],\n vol: [0.24, 0.3],\n }),\n tone({ f: [140, 170], f2: 85, d: [0.08, 0.11], vol: [0.12, 0.16] }),\n ],\n 'a gulp',\n ),\n foley(\n 'eat_crunch',\n [\n ...many(4, () =>\n noise({\n type: 'bandpass',\n f: [1800, 3200],\n q: 1.5,\n d: [0.02, 0.04],\n vol: [0.12, 0.2],\n delay: [0, 0.12],\n }),\n ),\n ],\n 'a bite of something crunchy',\n ),\n foley(\n 'eat_chew',\n [\n noise({\n type: 'lowpass',\n f: [450, 600],\n a: 0.03,\n d: [0.1, 0.14],\n vol: [0.12, 0.16],\n }),\n noise({\n type: 'bandpass',\n f: [1100, 1400],\n q: 2,\n d: 0.04,\n vol: 0.04,\n delay: [0.03, 0.06],\n }),\n ],\n 'chewing',\n ),\n foley(\n 'bandage_wrap',\n [\n noise({\n type: 'bandpass',\n f: [1400, 1800],\n f2: 2400,\n q: 1,\n a: 0.04,\n d: [0.3, 0.4],\n vol: [0.12, 0.16],\n }),\n ],\n 'a bandage unrolled round a limb',\n ),\n foley(\n 'pills_shake',\n [\n ...many(8, () =>\n tone({\n f: [2400, 3600],\n d: 0.015,\n vol: [0.03, 0.05],\n delay: [0, 0.25],\n }),\n ),\n noise({ type: 'bandpass', f: [1500, 1900], q: 2, d: 0.25, vol: 0.05 }),\n ],\n 'pills shaken in their bottle',\n ),\n foley(\n 'medkit_use',\n [\n ...click(1700, 0.24),\n noise({\n type: 'bandpass',\n f: [1000, 1400],\n q: 1,\n a: 0.03,\n d: [0.25, 0.32],\n vol: [0.08, 0.12],\n delay: [0.05, 0.08],\n }),\n ],\n 'a first aid kit opened and rummaged',\n ),\n foley('flashlight_click', click(2600, 0.3), 'the switch of a flashlight'),\n]\n\n/** The foley bank: register it in the engine (`engine.register(FOLEY_BANK)`). */\nexport const FOLEY_BANK: SoundBank = {\n id: 'foley',\n sounds: [...LEAF_FOLEY, ...ITEM_FOLEY],\n}\n\n/** What a picked-up item sounds like, by its heaviest material class. */\nexport const PICKUP_CLASSES = ['metal', 'plastic', 'glass', 'paper', 'fabric', 'wood', 'food'] as const\nexport type PickupClass = (typeof PICKUP_CLASSES)[number]\n\n/** The sound set of a leaf worked by hand: the ids it plays at the latch, while it turns, and as it meets the frame (gently, and slammed). */\nexport type LeafFoley = {\n readonly open: string\n readonly turn?: string\n readonly close: string\n readonly slam?: string\n readonly locked: string\n}\n\n/** The leaf sound sets the kit ships, by name; an item names one (`TestableItem.sounds.leaves`), else the room picks `wood_door` or `metal_door` by the leaf's material. */\nexport const LEAF_FOLEY_SETS: Readonly<Record<string, LeafFoley>> = {\n wood_door: {\n open: 'door_wood_open',\n turn: 'door_creak',\n close: 'door_wood_close',\n slam: 'door_wood_slam',\n locked: 'door_locked_rattle',\n },\n metal_door: {\n open: 'door_wood_open',\n turn: 'door_creak_metal',\n close: 'door_metal_open_close',\n locked: 'door_locked_rattle',\n },\n fridge: {\n open: 'fridge_open',\n close: 'fridge_close',\n locked: 'door_locked_rattle',\n },\n microwave: {\n open: 'microwave_open',\n close: 'microwave_close',\n locked: 'door_locked_rattle',\n },\n drawer: {\n open: 'drawer_open',\n close: 'drawer_close',\n locked: 'door_locked_rattle',\n },\n}\n","// The sounds of a body: footsteps by surface and gait, landings, the swing and the hit of each blow, hurt, bite and grab. Synthesised in the meantime\n// (the kit has no recorded take of these yet): each id is a set of four takes, with the numbers of each take apart, so the same action never\n// sounds twice the same. A recorded take replaces a variant by its id (`register` a bank with the same recipe id) without touching who plays it.\n//\n// How each one is built (what the ear picks first):\n// - a footstep is the heel (a low thump, how hollow the floor is) and then the roll to the toe (the surface's own texture: the grit of concrete,\n// the crunch of gravel, the ring of a metal sheet, the splash of water); a run hits harder, brighter and shorter, heel and toe almost together;\n// - a landing is the whole body's weight on the surface: a deeper thump, the surface texture longer, the clothes after;\n// - a swing is air: a band of noise sweeping up while the limb or the tool speeds up, loudest just before the contact, so it is started early\n// (`SWING_LEAD_SECONDS` of game-contracts) and the contact sound follows it;\n// - a hit on a body is skin (a slap), mass (a thud) and, for a blade, a wet tear; on an object it is only the striking part (knuckles, sole, steel)\n// and the material's own impact plays beside it.\nimport {\n BODY_SOUND_IDS,\n FOOTSTEP_SOUND_IDS,\n GAIT_IDS,\n LAND_SOUND_IDS,\n LANDING_IDS,\n SURFACE_IDS,\n SWING_LEAD_SECONDS,\n footstepSoundId,\n} from '@adatechnology/game-contracts'\nimport type { BlowId, BodySoundId, GaitId, LandingId, SurfaceId } from '@adatechnology/game-contracts'\n\nimport type { Falloff, Layer, SoundBank, SoundRecipe, SoundSet } from '../recipe'\nimport { sceneNoise, sceneTone, sceneVoice } from './scene'\n\n/** Takes per id. */\nexport const BODY_FOLEY_TAKES = 4\n\n/** How each take differs from the first: frequency factor, timing factor and level factor (fixed numbers, so takes are really apart). */\nconst TAKES: readonly { readonly f: number; readonly t: number; readonly v: number }[] = [\n { f: 1, t: 1, v: 1 },\n { f: 1.08, t: 0.9, v: 0.92 },\n { f: 0.93, t: 1.12, v: 1.05 },\n { f: 1.03, t: 1.05, v: 0.88 },\n]\n\n\n/** Footsteps fade fast with distance and lose their top: a step 10 m away is a quarter of the level, 30 m a few percent, and duller. */\nexport const FOOTSTEP_FALLOFF: Falloff = { model: 'inverse_square', k: 0.03, cutoffK: 0.03, minGain: 0.004 }\n/** Blows and body sounds carry further than a step. */\nexport const BODY_FALLOFF: Falloff = { model: 'inverse_square', k: 0.012, cutoffK: 0.015, minGain: 0.004 }\n\ntype Take = (typeof TAKES)[number]\n\n/** What a surface sounds like under a foot: the heel's thump and the texture of the roll. */\ntype SurfaceVoice = {\n /** The heel: thump pitch (Hz), its length (s) and level. */\n readonly heel: { readonly f: number; readonly d: number; readonly vol: number }\n /** The roll to the toe and the scuff: a filtered noise. */\n readonly roll: { readonly type: BiquadFilterType; readonly f: number; readonly q: number; readonly d: number; readonly vol: number }\n /** Grit, crunch or drips: short bursts spread after the heel. */\n readonly grains?: { readonly count: number; readonly f: number; readonly q: number; readonly spread: number; readonly vol: number }\n /** A ring of the floor itself (a hollow board, a metal sheet). */\n readonly ring?: readonly { readonly f: number; readonly d: number; readonly vol: number }[]\n /** Water: a sweep of the splash band. */\n readonly splash?: { readonly f: number; readonly f2: number; readonly d: number; readonly vol: number }\n}\n\nconst SURFACES: Readonly<Record<SurfaceId, SurfaceVoice>> = {\n concrete: { heel: { f: 95, d: 0.05, vol: 0.55 }, roll: { type: 'bandpass', f: 2300, q: 1.1, d: 0.05, vol: 0.38 }, grains: { count: 2, f: 4200, q: 2, spread: 0.04, vol: 0.08 } },\n asphalt: { heel: { f: 90, d: 0.05, vol: 0.5 }, roll: { type: 'bandpass', f: 1700, q: 0.9, d: 0.06, vol: 0.36 }, grains: { count: 4, f: 3600, q: 2.5, spread: 0.06, vol: 0.1 } },\n wood: { heel: { f: 130, d: 0.08, vol: 0.55 }, roll: { type: 'lowpass', f: 1300, q: 0.8, d: 0.06, vol: 0.3 }, ring: [{ f: 210, d: 0.1, vol: 0.18 }, { f: 470, d: 0.06, vol: 0.06 }] },\n tile: { heel: { f: 110, d: 0.04, vol: 0.45 }, roll: { type: 'bandpass', f: 3600, q: 2, d: 0.03, vol: 0.42 }, ring: [{ f: 1900, d: 0.03, vol: 0.05 }] },\n dirt: { heel: { f: 75, d: 0.06, vol: 0.45 }, roll: { type: 'lowpass', f: 750, q: 0.7, d: 0.09, vol: 0.4 }, grains: { count: 3, f: 1800, q: 1.5, spread: 0.07, vol: 0.06 } },\n grass: { heel: { f: 70, d: 0.05, vol: 0.32 }, roll: { type: 'highpass', f: 2600, q: 0.7, d: 0.13, vol: 0.28 }, grains: { count: 4, f: 5200, q: 1.2, spread: 0.1, vol: 0.07 } },\n gravel: { heel: { f: 80, d: 0.05, vol: 0.4 }, roll: { type: 'lowpass', f: 950, q: 0.8, d: 0.1, vol: 0.3 }, grains: { count: 8, f: 2600, q: 3, spread: 0.13, vol: 0.2 } },\n sand: { heel: { f: 65, d: 0.06, vol: 0.3 }, roll: { type: 'bandpass', f: 1500, q: 0.6, d: 0.16, vol: 0.3 }, grains: { count: 5, f: 4800, q: 1.5, spread: 0.12, vol: 0.05 } },\n metal: { heel: { f: 120, d: 0.05, vol: 0.5 }, roll: { type: 'bandpass', f: 2800, q: 1.5, d: 0.03, vol: 0.25 }, ring: [{ f: 420, d: 0.25, vol: 0.16 }, { f: 1130, d: 0.18, vol: 0.09 }, { f: 2470, d: 0.1, vol: 0.04 }] },\n water: { heel: { f: 70, d: 0.04, vol: 0.25 }, roll: { type: 'bandpass', f: 3000, q: 1.2, d: 0.1, vol: 0.18 }, splash: { f: 1100, f2: 380, d: 0.22, vol: 0.55 }, grains: { count: 4, f: 2400, q: 6, spread: 0.18, vol: 0.12 } },\n glass: { heel: { f: 90, d: 0.04, vol: 0.4 }, roll: { type: 'highpass', f: 4500, q: 0.8, d: 0.06, vol: 0.2 }, grains: { count: 9, f: 6200, q: 5, spread: 0.12, vol: 0.22 }, ring: [{ f: 3900, d: 0.04, vol: 0.04 }, { f: 5300, d: 0.03, vol: 0.03 }] },\n carpet: { heel: { f: 70, d: 0.05, vol: 0.32 }, roll: { type: 'lowpass', f: 420, q: 0.7, d: 0.07, vol: 0.3 } },\n}\n\nconst GAITS: Readonly<Record<GaitId, { readonly vol: number; readonly bright: number; readonly toe: number; readonly short: number }>> = {\n walk: { vol: 1, bright: 1, toe: 0.075, short: 1 },\n run: { vol: 1.35, bright: 1.25, toe: 0.035, short: 0.75 },\n}\n\nconst grainLayers = (g: NonNullable<SurfaceVoice['grains']>, take: Take, start: number, scale: number): Layer[] =>\n Array.from({ length: g.count }, (_, i) =>\n sceneNoise({ type: 'bandpass', f: [g.f * take.f * 0.85, g.f * take.f * 1.15], q: g.q, d: [0.008, 0.02], vol: g.vol * scale * take.v, delay: start + ((i + 0.5) / g.count) * g.spread * take.t }),\n )\n\nconst ringLayers = (rings: NonNullable<SurfaceVoice['ring']>, take: Take, scale: number, at = 0): Layer[] =>\n rings.map((r) => sceneTone({ f: r.f * take.f, d: r.d * take.t, vol: r.vol * scale * take.v, delay: at }))\n\n/** The layers of one foot on a surface: heel, roll to the toe, then grains, ring or splash. `weight` scales the heel (a landing is the whole body). */\nfunction footLayers(surface: SurfaceId, take: Take, gait: (typeof GAITS)[GaitId], weight = 1): Layer[] {\n const s = SURFACES[surface]\n const toe = gait.toe * take.t\n return [\n sceneTone({ f: s.heel.f * take.f * weight ** -0.3, f2: s.heel.f * take.f * 0.6, d: s.heel.d * gait.short * take.t * weight ** 0.5, vol: s.heel.vol * gait.vol * take.v * weight ** 0.5 }),\n sceneNoise({ type: 'lowpass', f: 500 * gait.bright, d: 0.02 * take.t, vol: 0.18 * gait.vol * take.v * weight ** 0.5 }),\n sceneNoise({ type: s.roll.type, f: [s.roll.f * take.f * gait.bright * 0.92, s.roll.f * take.f * gait.bright * 1.08], q: s.roll.q, d: s.roll.d * gait.short * take.t * weight ** 0.3, vol: s.roll.vol * gait.vol * take.v, delay: toe }),\n ...(s.grains ? grainLayers(s.grains, take, toe * 0.5, gait.vol * weight ** 0.5) : []),\n ...(s.ring ? ringLayers(s.ring, take, gait.vol * weight ** 0.5) : []),\n ...(s.splash ? [sceneNoise({ type: 'bandpass', f: s.splash.f * take.f, f2: s.splash.f2 * take.f, q: 1.4, d: s.splash.d * take.t * weight ** 0.4, vol: s.splash.vol * gait.vol * take.v * weight ** 0.5 })] : []),\n ]\n}\n\n/** The layers at `level` of their gain (a scene layer's gain is a number or a range). */\nconst quieter = (level: number, layers: readonly Layer[]): Layer[] =>\n layers.map((layer) => {\n const gain = layer.gain ?? 1\n if (typeof gain === 'number') return { ...layer, gain: gain * level }\n if (Array.isArray(gain)) return { ...layer, gain: [gain[0] * level, gain[1] * level] as const }\n return layer\n })\n\nconst recipe = (id: string, layers: readonly Layer[], falloff: Falloff, bus: SoundRecipe['bus'] = 'world'): SoundRecipe => ({ id, bus, pan: true, layers, falloff, sources: ['sdk'] })\n\nconst takeId = (id: string, index: number): string => `${id}_${String(index + 1).padStart(2, '0')}`\n\n/** The four takes of an id and the set that names them. */\nfunction takes(id: string, layersOf: (take: Take, index: number) => Layer[], falloff: Falloff, rate: readonly [number, number] = [0.96, 1.04], bus?: SoundRecipe['bus']): { sounds: SoundRecipe[]; set: SoundSet } {\n const sounds = TAKES.map((take, index) => recipe(takeId(id, index), layersOf(take, index), falloff, bus))\n return { sounds, set: { id, variants: sounds.map((sound) => sound.id), rate } }\n}\n\nconst footstep = (surface: SurfaceId, gait: GaitId) => takes(footstepSoundId(surface, gait), (take) => footLayers(surface, take, GAITS[gait]), FOOTSTEP_FALLOFF)\n\nconst LANDINGS: Readonly<Record<LandingId, { readonly weight: number; readonly cloth: number }>> = { light: { weight: 1.4, cloth: 0.12 }, heavy: { weight: 2.4, cloth: 0.22 } }\n\n/** A landing's layers are the feet's at the body's weight; this brings the whole of it under a blow on a body (C6). */\nconst LANDING_LEVEL = 0.65\n\nconst landing = (surface: SurfaceId, landing: LandingId) =>\n takes(\n `land_${surface}_${landing}`,\n (take) => quieter(LANDING_LEVEL, [\n // both feet, a hair apart, then the knees taking the weight (a low body thump) and the clothes settling\n ...footLayers(surface, take, GAITS.run, LANDINGS[landing].weight),\n ...footLayers(surface, { ...take, v: take.v * 0.6 }, GAITS.run, LANDINGS[landing].weight * 0.6).map((layer) => ({ ...layer, at: (typeof layer.at === 'number' ? layer.at : 0) + 0.018 * take.t })),\n sceneTone({ f: 60 * take.f, f2: 38, d: 0.14 * LANDINGS[landing].weight * take.t, vol: 0.22 * LANDINGS[landing].weight ** 0.7 * take.v, delay: 0.02 }),\n sceneNoise({ type: 'bandpass', f: [1800, 2600], q: 0.8, d: 0.18, vol: LANDINGS[landing].cloth * take.v, delay: 0.04 }),\n ]),\n FOOTSTEP_FALLOFF,\n )\n\nconst whoosh = (blow: BlowId, from: number, to: number, d: number, vol: number, q = 1.6): ((take: Take) => Layer[]) => (take) => [\n // the air: a band sweeping up as the limb speeds up; it peaks `SWING_LEAD_SECONDS` in, the moment before the contact, then dies away\n sceneNoise({ type: 'bandpass', f: from * take.f, f2: to * take.f, q, a: SWING_LEAD_SECONDS[blow], d: d * take.t, vol: vol * take.v }),\n sceneNoise({ type: 'lowpass', f: 600 * take.f, a: SWING_LEAD_SECONDS[blow], d: d * take.t * 0.8, vol: vol * 0.35 * take.v }),\n]\n\n/** Skin, mass and (optionally) bone: what a blow on a body is made of. */\nconst fleshHit = (o: { slap: number; slapF: number; thud: number; thudF: number; thudD: number; crack?: number; wet?: number }): ((take: Take) => Layer[]) => (take) => [\n sceneNoise({ type: 'bandpass', f: o.slapF * take.f, q: 1.2, d: 0.03 * take.t, vol: o.slap * take.v }),\n sceneNoise({ type: 'highpass', f: 3500 * take.f, d: 0.012, vol: o.slap * 0.4 * take.v }),\n sceneTone({ f: o.thudF * take.f, f2: o.thudF * 0.5, d: o.thudD * take.t, vol: o.thud * take.v }),\n sceneNoise({ type: 'lowpass', f: 600 * take.f, d: o.thudD * 1.2 * take.t, vol: o.thud * 0.5 * take.v }),\n ...(o.crack ? [sceneNoise({ type: 'highpass', f: 2500, d: 0.015, vol: o.crack * take.v, delay: 0.006 }), sceneTone({ wave: 'square', f: 900 * take.f, f2: 300, d: 0.02, vol: o.crack * 0.15 * take.v, delay: 0.006 })] : []),\n ...(o.wet ? [sceneNoise({ type: 'bandpass', f: 1400 * take.f, f2: 500, q: 2.5, d: 0.12 * take.t, vol: o.wet * take.v, delay: 0.01 })] : []),\n]\n\n/** What only the striking part sounds like on a hard thing (the material's impact plays beside it). */\nconst knock = (o: { clickF: number; click: number; tones: readonly (readonly [number, number, number])[] }): ((take: Take) => Layer[]) => (take) => [\n sceneNoise({ type: 'bandpass', f: o.clickF * take.f, q: 1.5, d: 0.018, vol: o.click * take.v }),\n ...o.tones.map(([f, d, vol]) => sceneTone({ f: f * take.f, d: d * take.t, vol: vol * take.v })),\n]\n\nconst voice = (o: { f0: number; f1: number; d: number; fA: number; fB: number; noise: number; vol: number }): ((take: Take) => Layer[]) => (take) => [\n sceneVoice({ f0: o.f0 * take.f, f1: o.f1 * take.f, d: o.d * take.t, fA: o.fA * take.f, fB: o.fB * take.f, noise: o.noise, vol: o.vol * take.v }),\n]\n\nconst BODY: Readonly<Record<BodySoundId, (take: Take) => Layer[]>> = {\n jump: (take) => [\n sceneNoise({ type: 'bandpass', f: 900 * take.f, f2: 1700 * take.f, q: 1, a: 0.03, d: 0.12, vol: 0.18 * take.v }),\n sceneNoise({ type: 'bandpass', f: 2200 * take.f, q: 0.8, d: 0.04, vol: 0.12 * take.v }),\n sceneTone({ f: 85 * take.f, f2: 60, d: 0.04, vol: 0.2 * take.v }),\n ],\n cloth_rustle: (take) => [\n { ...sceneNoise({ type: 'bandpass', f: 2400 * take.f, q: 0.8, a: 0.06, d: 0.22 * take.t, vol: 0.12 * take.v }), modulators: [{ target: 'gain', wave: 'triangle', rate: [9, 14], depth: 0.5 }] },\n ],\n body_fall: (take) => [\n sceneTone({ f: 58 * take.f, f2: 35, d: 0.28 * take.t, vol: 0.9 * take.v }),\n sceneNoise({ type: 'lowpass', f: 480 * take.f, d: 0.3 * take.t, vol: 0.55 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1300 * take.f, q: 1, d: 0.05, vol: 0.3 * take.v }),\n // the limbs a moment later, and the clothes\n sceneTone({ f: 75 * take.f, f2: 45, d: 0.12, vol: 0.4 * take.v, delay: 0.13 * take.t }),\n sceneNoise({ type: 'bandpass', f: 2200, q: 0.8, d: 0.2, vol: 0.12 * take.v, delay: 0.05 }),\n ],\n fall_damage: (take) => [\n ...BODY.body_fall(take),\n sceneNoise({ type: 'highpass', f: 2800, d: 0.02, vol: 0.35 * take.v, delay: 0.01 }),\n ...voice({ f0: 170, f1: 110, d: 0.32, fA: 650, fB: 1150, noise: 0.25, vol: 0.32 })(take).map((layer) => ({ ...layer, at: 0.08 })),\n ],\n player_hurt: voice({ f0: 150, f1: 105, d: 0.26, fA: 620, fB: 1100, noise: 0.3, vol: 0.35 }),\n player_breath_run: (take) => [\n sceneNoise({ type: 'bandpass', f: 1200 * take.f, q: 1, a: 0.08, d: 0.22 * take.t, vol: 0.25 * take.v }),\n sceneNoise({ type: 'bandpass', f: 900 * take.f, q: 1, a: 0.06, d: 0.26 * take.t, vol: 0.3 * take.v, delay: 0.3 * take.t }),\n ],\n player_death: voice({ f0: 135, f1: 68, d: 1, fA: 560, fB: 980, noise: 0.35, vol: 0.4 }),\n bite: (take) => [\n sceneNoise({ type: 'highpass', f: 2600, d: 0.015, vol: 0.4 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1600 * take.f, f2: 450, q: 2.2, d: 0.16 * take.t, vol: 0.55 * take.v, delay: 0.01 }),\n sceneNoise({ type: 'bandpass', f: 3200 * take.f, f2: 1800, q: 1.2, d: 0.22 * take.t, vol: 0.25 * take.v, delay: 0.09 }),\n sceneTone({ f: 120 * take.f, f2: 70, d: 0.06, vol: 0.3 * take.v }),\n ],\n grab: (take) => [\n sceneNoise({ type: 'bandpass', f: 1900 * take.f, q: 0.9, a: 0.004, d: 0.13 * take.t, vol: 0.32 * take.v }),\n sceneTone({ f: 95 * take.f, f2: 60, d: 0.07, vol: 0.3 * take.v }),\n sceneNoise({ type: 'lowpass', f: 700, d: 0.08, vol: 0.2 * take.v }),\n ],\n punch_swing: whoosh('punch', 450, 1500, 0.16, 0.9),\n punch_hit_body: fleshHit({ slap: 0.55, slapF: 1500, thud: 0.6, thudF: 115, thudD: 0.09 }),\n punch_hit_face: fleshHit({ slap: 0.75, slapF: 2300, thud: 0.45, thudF: 150, thudD: 0.07, crack: 0.25 }),\n punch_hit_object: knock({ clickF: 1800, click: 0.3, tones: [[210, 0.04, 0.25]] }),\n kick_swing: whoosh('kick', 280, 950, 0.22, 1, 1.3),\n kick_hit: fleshHit({ slap: 0.45, slapF: 1100, thud: 0.85, thudF: 82, thudD: 0.14 }),\n kick_hit_object: knock({ clickF: 1000, click: 0.3, tones: [[92, 0.08, 0.5]] }),\n shove_two_hands: (take) => [\n sceneNoise({ type: 'bandpass', f: 950 * take.f, q: 0.9, a: 0.01, d: 0.13 * take.t, vol: 0.38 * take.v }),\n sceneTone({ f: 100 * take.f, f2: 60, d: 0.1 * take.t, vol: 0.45 * take.v }),\n sceneNoise({ type: 'bandpass', f: 2300, q: 0.8, d: 0.16, vol: 0.12 * take.v, delay: 0.03 }),\n ],\n knife_swing: whoosh('blade', 1900, 4600, 0.12, 1.1, 2.2),\n knife_stab: fleshHit({ slap: 0.2, slapF: 1200, thud: 0.4, thudF: 160, thudD: 0.06, wet: 0.5 }),\n knife_slash: (take) => [\n sceneNoise({ type: 'highpass', f: 3200 * take.f, f2: 1800, d: 0.13 * take.t, vol: 0.35 * take.v }),\n sceneNoise({ type: 'bandpass', f: 1300 * take.f, f2: 600, q: 2.5, d: 0.12 * take.t, vol: 0.35 * take.v, delay: 0.02 }),\n ],\n knife_hit_object: knock({ clickF: 3200, click: 0.25, tones: [[2800, 0.08, 0.07], [4150, 0.06, 0.05]] }),\n blunt_swing: whoosh('blunt', 220, 760, 0.28, 1.1, 1.5),\n blunt_hit: fleshHit({ slap: 0.35, slapF: 900, thud: 1, thudF: 70, thudD: 0.18, crack: 0.3 }),\n blunt_hit_object: knock({ clickF: 1400, click: 0.35, tones: [[300, 0.12, 0.25], [760, 0.08, 0.12]] }),\n axe_swing: whoosh('chop', 190, 620, 0.3, 1.2, 1.4),\n axe_chop: fleshHit({ slap: 0.3, slapF: 1400, thud: 0.75, thudF: 140, thudD: 0.1, crack: 0.35, wet: 0.45 }),\n axe_hit_object: knock({ clickF: 2200, click: 0.4, tones: [[1500, 0.15, 0.1], [2300, 0.1, 0.06], [140, 0.1, 0.35]] }),\n}\n\nconst BODY_BUS: Partial<Record<BodySoundId, SoundRecipe['bus']>> = { player_hurt: 'voices', player_death: 'voices', player_breath_run: 'voices', fall_damage: 'voices' }\n\nconst built = [\n ...SURFACE_IDS.flatMap((surface) => GAIT_IDS.map((gait) => footstep(surface, gait))),\n ...SURFACE_IDS.flatMap((surface) => LANDING_IDS.map((l) => landing(surface, l))),\n ...BODY_SOUND_IDS.map((id) => takes(id, BODY[id], BODY_FALLOFF, id.endsWith('_swing') ? [0.94, 1.06] : [0.96, 1.04], BODY_BUS[id])),\n]\n\n/**\n * Every body sound of `game-contracts`' `BODY_FOLEY_IDS` as a set of four takes (`footstep_concrete_walk` plays `footstep_concrete_walk_01`..`_04`,\n * never the same twice in a row, at ±4% of rate). Register it in the engine the body plays on.\n */\nexport const BODY_FOLEY_BANK: SoundBank = {\n id: 'body_foley',\n sounds: built.flatMap((entry) => entry.sounds),\n sets: built.map((entry) => entry.set),\n}\n\n/** The ids the bank answers (the sets), in the contract's order. */\nexport const BODY_FOLEY_SET_IDS: readonly string[] = [...FOOTSTEP_SOUND_IDS, ...LAND_SOUND_IDS, ...BODY_SOUND_IDS]\n","import type { AudioListener, AudioSink, LoopHandle, SoundHandle, SoundRequest } from '@adatechnology/game-contracts'\n\nimport type { SoundBank } from '../recipe'\nimport type { AudioEngine, VoiceHandle } from './engine'\n\n/** An `AudioSink` (what a host lends its modules) that carries the engine behind it, so a module that wants more than `play` can use the engine. */\nexport type EngineSink = AudioSink & { readonly engine: AudioEngine }\n\n/** Lends an engine as the host's `audio`: sounds by key, loops, the listener, and banks registered into the same engine. */\nexport function createAudioSink(engine: AudioEngine): EngineSink {\n const playing = new Map<number, VoiceHandle>()\n return {\n engine,\n play(request: SoundRequest): SoundHandle | null {\n const handle = engine.play(request.sound, {\n ...(request.position ? { position: request.position } : {}),\n ...(request.volume === undefined ? {} : { volume: request.volume }),\n ...(request.params ? { params: request.params } : {}),\n ...(request.seed === undefined ? {} : { seed: request.seed }),\n ...(request.delay === undefined ? {} : { delay: request.delay }),\n ...(request.urgent ? { urgent: true } : {}),\n })\n if (!handle) return null\n playing.set(handle.id, handle)\n return { id: handle.id }\n },\n stop(handle) {\n playing.get(handle.id)?.stop()\n playing.delete(handle.id)\n },\n loop(sound, options): LoopHandle {\n const loop = engine.loop(sound)\n // the loop's place comes with the first set; `params.cutoff` drives the first filter\n let position = options?.position\n return {\n set: (state) => {\n position = state.position ?? position\n const cutoff = state.params?.['cutoff']\n loop.set({\n ...(state.volume === undefined ? {} : { volume: state.volume }),\n ...(state.frequency === undefined ? {} : { frequency: state.frequency }),\n ...(position ? { position } : {}),\n ...(cutoff === undefined ? {} : { cutoff }),\n })\n },\n stop: () => loop.stop(),\n }\n },\n setListener(listener: AudioListener) {\n engine.setListener(listener)\n },\n register(bank: unknown) {\n engine.register(bank as SoundBank)\n },\n }\n}\n","export type AudioBenchText = {\n readonly group: string\n readonly name: string\n readonly probe: string\n readonly controls: Readonly<Record<'sound' | 'distance' | 'bearing' | 'volume' | 'mix' | 'seed' | 'play' | 'voice_storm' | 'loop' | 'loop_level' | 'loop_pitch' | 'source', string>>\n readonly hints: Readonly<Record<'distance' | 'bearing' | 'mix' | 'seed' | 'voice_storm' | 'loop_pitch' | 'source', string>>\n readonly options: Readonly<Record<'none' | 'bench' | 'probe', string>>\n readonly layers: Readonly<Record<'reverb' | 'compressor' | 'panning' | 'muffling', string>>\n readonly metrics: Readonly<Record<'voices' | 'peak' | 'dropped' | 'loops' | 'context' | 'plan_length' | 'plan_level' | 'plan_pan' | 'level_weapons' | 'level_voices' | 'level_world' | 'level_ambience' | 'level_weather' | 'level_ui', string>>\n readonly scenarios: Readonly<Record<'panning' | 'distance' | 'determinism' | 'limiter', string>>\n readonly mixes: Readonly<Record<string, string>>\n /** Text of a sound or loop id when the game has one; the bench falls back to the id. */\n readonly sheet: Readonly<Record<'title' | 'level' | 'distance' | 'pan' | 'length' | 'silent' | 'layer' | 'none', string>>\n}\n\nconst EN: AudioBenchText = {\n group: 'Sound',\n name: 'Sound area',\n probe: 'Sound probe',\n controls: {\n sound: 'Sound',\n distance: 'Distance',\n bearing: 'Bearing',\n volume: 'Volume',\n mix: 'Mixing chain',\n seed: 'Seed',\n play: 'Play',\n voice_storm: 'Voice storm',\n loop: 'Loop',\n loop_level: 'Loop level',\n loop_pitch: 'Loop pitch',\n source: 'Source',\n },\n hints: {\n distance: 'Metres from the listener: the level falls and the sound is muffled with it.',\n bearing: 'Degrees from straight ahead, positive to the right: shows the panning.',\n mix: 'The game chain (master only) or the art scene chain (compressor and reverb).',\n seed: 'The same seed gives the same sound.',\n voice_storm: 'Twenty of the chosen sound at once: the voice limiter drops what its group and the global cap refuse.',\n loop_pitch: 'Frequency of an oscillator loop, in hertz (0 leaves it where it is).',\n source: 'Where the sound comes from: the distance and bearing set here, or the probe standing in the area.',\n },\n options: { none: 'None', bench: 'Bench settings', probe: 'The probe' },\n layers: { reverb: 'Reverb', compressor: 'Compressor', panning: 'Panning', muffling: 'Muffling by distance' },\n metrics: {\n voices: 'Voices playing',\n peak: 'Most voices at once',\n dropped: 'Voices dropped',\n loops: 'Loops running',\n context: 'Audio context',\n plan_length: 'Chosen sound: length',\n plan_level: 'Chosen sound: level',\n plan_pan: 'Chosen sound: pan',\n level_weapons: 'Level: weapons',\n level_voices: 'Level: voices',\n level_world: 'Level: world',\n level_ambience: 'Level: ambience',\n level_weather: 'Level: weather',\n level_ui: 'Level: interface',\n },\n scenarios: {\n panning: 'A sound to the right is heard on the right, one to the left on the left, one ahead in the middle',\n distance: 'The farther a sound, the quieter, until it is not played',\n determinism: 'The same seed gives the same sound plan, another seed another one',\n limiter: 'The voice limiter holds a storm of voices to its group rule and its global cap',\n },\n mixes: { game: 'Game', art_scene: 'Art scene', kit: 'Kit (art scene + limiter)' },\n sheet: { title: 'Sound plan', level: 'level', distance: 'distance', pan: 'pan', length: 'seconds', silent: 'too far to be heard', layer: 'layer', none: 'no sound chosen' },\n}\n\nconst PT_BR: AudioBenchText = {\n group: 'Som',\n name: 'Área de som',\n probe: 'Sonda de som',\n controls: {\n sound: 'Som',\n distance: 'Distância',\n bearing: 'Direção',\n volume: 'Volume',\n mix: 'Cadeia de mixagem',\n seed: 'Semente',\n play: 'Tocar',\n voice_storm: 'Tempestade de vozes',\n loop: 'Laço',\n loop_level: 'Nível do laço',\n loop_pitch: 'Altura do laço',\n source: 'Origem',\n },\n hints: {\n distance: 'Metros até o ouvinte: o nível cai e o som abafa junto.',\n bearing: 'Graus a partir da frente, positivo para a direita: mostra o pan.',\n mix: 'A cadeia do jogo (só o master) ou a da Cena de Arte (compressor e reverb).',\n seed: 'A mesma semente dá o mesmo som.',\n voice_storm: 'Vinte do som escolhido de uma vez: o limite de vozes derruba o que a regra do grupo e o teto global recusam.',\n loop_pitch: 'Frequência de um laço de oscilador, em hertz (0 deixa onde está).',\n source: 'De onde vem o som: a distância e a direção daqui, ou a sonda que está na área.',\n },\n options: { none: 'Nenhum', bench: 'Ajustes da bancada', probe: 'A sonda' },\n layers: { reverb: 'Reverb', compressor: 'Compressor', panning: 'Pan', muffling: 'Abafamento pela distância' },\n metrics: {\n voices: 'Vozes tocando',\n peak: 'Mais vozes de uma vez',\n dropped: 'Vozes derrubadas',\n loops: 'Laços ligados',\n context: 'Contexto de áudio',\n plan_length: 'Som escolhido: duração',\n plan_level: 'Som escolhido: nível',\n plan_pan: 'Som escolhido: pan',\n level_weapons: 'Nível: armas',\n level_voices: 'Nível: vozes',\n level_world: 'Nível: mundo',\n level_ambience: 'Nível: ambiente',\n level_weather: 'Nível: clima',\n level_ui: 'Nível: interface',\n },\n scenarios: {\n panning: 'Um som à direita sai à direita, à esquerda sai à esquerda, à frente sai no meio',\n distance: 'Quanto mais longe, mais baixo, até não tocar',\n determinism: 'A mesma semente dá o mesmo plano de som, outra semente dá outro',\n limiter: 'O limite de vozes segura uma tempestade de vozes na regra do grupo e no teto global',\n },\n mixes: { game: 'Jogo', art_scene: 'Cena de Arte', kit: 'Kit (Cena de Arte + limitador)' },\n sheet: { title: 'Plano do som', level: 'nível', distance: 'distância', pan: 'pan', length: 'segundos', silent: 'longe demais para ouvir', layer: 'camada', none: 'nenhum som escolhido' },\n}\n\nexport const audioBenchTextOf = (locale: string): AudioBenchText => (locale === 'en' ? EN : PT_BR)\n","import type { AreaPlacement, BenchChange, ChoiceOption, ModuleControl, ModuleHost, ModuleLayer, ModuleMetric, ModuleScenario, TestableItem, TestableModule, Vec3 } from '@adatechnology/game-contracts'\n\nimport { GAME_SFX_BANK } from '../recipes/noise-class'\nimport { LIBRARY_BANK } from '../library'\nimport { DISTANCE_CURVES } from '../falloff'\nimport { DEFAULT_MIX, MIX_PROFILES } from '../mix'\nimport type { MixProfile } from '../mix'\nimport { BUS_IDS } from '../recipe'\nimport type { BusId, Layer, SoundBank } from '../recipe'\nimport type { SoundPlan } from '../plan'\nimport { createVoiceManager } from '../voices'\nimport { createAudioEngine } from '../webaudio/engine'\nimport type { AudioEngine, VoiceHandle } from '../webaudio/engine'\nimport type { EngineSink } from '../webaudio/sink'\nimport type { AudioLoopHandle } from '../webaudio/engine-loop'\nimport { audioBenchTextOf } from './locale'\nimport type { AudioBenchText } from './locale'\n\n/**\n * Two probe sounds of the bench itself (a ping and a hiss), so panning, distance and the seed can be heard on something that has no subject. They are\n * made by the kit, not delivered by any team (`sdk` in the sources).\n */\nexport const BENCH_BANK: SoundBank = {\n id: 'audio_bench',\n sounds: [\n {\n id: 'bench_ping',\n bus: 'ui',\n pan: true,\n duration: 0.25,\n layers: [\n {\n gain: 0.5,\n wet: 0.3,\n source: { kind: 'osc', wave: 'sine', frequency: { from: 880 } },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.002, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n } satisfies Layer,\n ],\n falloff: DISTANCE_CURVES.art_scene,\n sources: ['sdk: bench probe, a 880 Hz ping through the art scene output stage'],\n },\n {\n id: 'bench_hiss',\n bus: 'ui',\n pan: true,\n duration: [0.3, 0.9],\n layers: [\n {\n gain: 0.4,\n source: { kind: 'noise', offset: 'random', offsetScale: 1.5, loop: true },\n filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 3000 }, q: 0.7 }] },\n envelope: [\n [0, 0.0001, 'set', 'fixed'],\n [0.002, 1, 'exp'],\n ['1d', 0.0001, 'exp', 'fixed'],\n ],\n } satisfies Layer,\n ],\n falloff: DISTANCE_CURVES.art_scene,\n sources: ['sdk: bench probe, a highpass hiss of random length'],\n },\n ],\n}\n\nexport type AudioTestModuleOptions = {\n /** The engine to test (default: the one the host lends in `host.audio`, else a new one of the module's own). */\n engine?: AudioEngine\n /** Banks registered in the engine besides the bench's probes (default the game's noise classes and the library). */\n banks?: readonly SoundBank[]\n locale?: string\n /** Text of a sound or loop id (`sound.glass`) in the game's words; without it the bench shows the bank and the id. */\n translate?: (key: string, locale: string) => string | undefined\n seed?: number\n /** First sound chosen (default `bench_ping`). */\n sound?: string\n /**\n * Draws the thing the probe stands for, where the sound comes from with the `probe` source (for example a portable radio of `game-items-three`). The module\n * draws nothing of its own: without it the area has no probe and the sounds come from the bench settings.\n */\n probe?: (THREE: unknown) => unknown\n}\n\n/** What the scenarios use of the context the test room passes. */\nexport interface AudioScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type AudioTestModule = TestableModule<AudioScenarioLike> & {\n /** The engine in use: the host's when it lent one, the module's own otherwise. */\n readonly engine: AudioEngine\n /** The resolved plan of the chosen sound as text (the S3 view: every number decided). */\n sheet(): string\n /** Plays the chosen sound as the bench is set. */\n play(): VoiceHandle | null\n}\n\nconst DISTANCES = [0, 10, 40, 60, 120, 160] as const\nconst STORM = 20\nconst PROBE_ID = 'audio_probe'\nconst PROBE_AT: Vec3 = [0, 0, -10]\nconst NONE = 'none'\nconst DEFAULT_SOUND = 'bench_ping'\n\ntype Camera = { readonly position: { readonly x: number; readonly y: number; readonly z: number }; getWorldDirection(target: unknown): { readonly x: number; readonly z: number } }\ntype ThreeLike = { Vector3: new () => unknown }\ntype ProbeObject = { userData?: Record<string, unknown>; getWorldPosition(target: unknown): { readonly x: number; readonly y: number; readonly z: number }; traverse(visit: (object: ProbeObject) => void): void }\n\nconst variantOf = (profile: MixProfile, reverb: boolean, compressor: boolean): MixProfile => {\n const { reverb: wet, compressor: chain, ...rest } = profile\n return { ...rest, id: `${profile.id}${reverb ? '' : '+dry'}${compressor ? '' : '+open'}`, ...(wet && reverb ? { reverb: wet } : {}), ...(chain && compressor ? { compressor: chain } : {}) }\n}\n\n/**\n * The sound area of a test room, written against the generic contracts only: it plays any sound of an engine at a distance and bearing from the listener\n * (or from a probe standing in the area), runs loops, throws a storm of voices at the limiter, switches the mixing chain and its parts, reads the\n * level of each bus and prints the resolved plan. The engine is the host's (`host.audio`) when lent, else the module's own.\n */\nexport function createAudioTestModule(options: AudioTestModuleOptions = {}): AudioTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text: AudioBenchText = audioBenchTextOf(locale)\n const banks = [BENCH_BANK, ...(options.banks ?? [GAME_SFX_BANK, LIBRARY_BANK])]\n let engine: AudioEngine = options.engine ?? createAudioEngine({ seed: options.seed ?? 1, banks })\n for (const bank of banks) engine.register(bank)\n let host: ModuleHost | null = null\n let loop: AudioLoopHandle | undefined\n const state = {\n sound: options.sound ?? DEFAULT_SOUND,\n distance: 10,\n bearing: 0,\n volume: 1,\n mix: DEFAULT_MIX,\n seed: options.seed ?? 1,\n source: 'bench',\n loop: NONE,\n loopLevel: 0.1,\n loopPitch: 0,\n reverb: true,\n compressor: true,\n panning: true,\n muffling: true,\n }\n\n const nameOf = (id: string): string => {\n const translated = options.translate?.(`sound.${id}`, locale)\n if (translated) return translated\n const bank = engine.registry.bankOf(id)\n return bank ? `${bank} / ${id}` : id\n }\n const soundOptions = (): ChoiceOption[] => engine.registry.soundIds().map((id) => ({ id, name: nameOf(id) }))\n const loopOptions = (): ChoiceOption[] => [{ id: NONE, name: text.options.none }, ...engine.registry.loopIds().map((id) => ({ id, name: nameOf(id) }))]\n\n // the listener is the host camera; without a host (a test) it stands at the origin looking along -z\n const listener = (): { position: Vec3; yaw: number } => {\n const camera = host?.camera as Camera | undefined\n const three = host?.THREE as ThreeLike | undefined\n if (typeof camera?.getWorldDirection !== 'function' || typeof three?.Vector3 !== 'function' || !camera.position) return { position: [0, 0, 0], yaw: 0 }\n const direction = camera.getWorldDirection(new three.Vector3())\n return { position: [camera.position.x, camera.position.y, camera.position.z], yaw: Math.atan2(-direction.x, -direction.z) }\n }\n\n const probePosition = (): Vec3 | undefined => {\n const scene = host?.scene as ProbeObject | undefined\n const three = host?.THREE as ThreeLike | undefined\n if (typeof scene?.traverse !== 'function' || typeof three?.Vector3 !== 'function') return undefined\n let found: Vec3 | undefined\n scene.traverse((object) => {\n if (found || object.userData?.[PROBE_ID] !== true) return\n const at = object.getWorldPosition(new three.Vector3())\n found = [at.x, at.y, at.z]\n })\n return found\n }\n\n // `bearing` is degrees to the right of straight ahead\n const sourceAt = (ears: { position: Vec3; yaw: number }): Vec3 => {\n const probe = state.source === 'probe' ? probePosition() : undefined\n if (probe) return probe\n const bearing = (state.bearing * Math.PI) / 180\n const forward = [-Math.sin(ears.yaw), -Math.cos(ears.yaw)] as const\n const right = [Math.cos(ears.yaw), -Math.sin(ears.yaw)] as const\n return [ears.position[0] + state.distance * (forward[0] * Math.cos(bearing) + right[0] * Math.sin(bearing)), ears.position[1], ears.position[2] + state.distance * (forward[1] * Math.cos(bearing) + right[1] * Math.sin(bearing))]\n }\n\n const playOptions = (): { position?: Vec3; distance?: number; volume: number; seed: number } => {\n const ears = listener()\n engine.setListener(ears)\n const at = sourceAt(ears)\n const distance = Math.hypot(at[0] - ears.position[0], at[2] - ears.position[2])\n return { ...(state.panning ? { position: at } : { distance }), volume: state.volume, seed: state.seed }\n }\n\n // no muffling: the recipe's cutoff divisor is switched off for the one call\n const withMuffling = <T>(id: string, run: () => T): T => {\n const falloff = engine.registry.sound(id)?.falloff\n if (state.muffling || !falloff || falloff.model !== 'inverse_square' || falloff.cutoffK === undefined) return run()\n engine.registry.patch(id, { falloff: { cutoffK: 0 } })\n try {\n return run()\n } finally {\n engine.registry.patch(id, { falloff: { cutoffK: falloff.cutoffK } })\n }\n }\n\n const play = (): VoiceHandle | null => {\n engine.unlock()\n const chosen = state.sound\n return withMuffling(chosen, () => engine.play(chosen, playOptions()))\n }\n\n const plan = (): SoundPlan | null => {\n const chosen = state.sound\n return withMuffling(chosen, () => engine.plan(chosen, playOptions()))\n }\n\n const sheet = (): string => {\n const planned = plan()\n if (!planned) return `${text.sheet.title}: ${engine.registry.sound(state.sound) ? text.sheet.silent : text.sheet.none}`\n const head = `${text.sheet.title}: ${planned.id} (${planned.bus}) ${text.sheet.level} ${planned.level.toFixed(4)} ${text.sheet.distance} ${planned.distance.toFixed(1)} m` + `${planned.pan === undefined ? '' : ` ${text.sheet.pan} ${planned.pan.toFixed(3)}`} ${planned.length.toFixed(3)} ${text.sheet.length}`\n const layers = planned.layers.map((layer, index) => {\n const source = layer.source.kind === 'noise' ? `noise@${layer.source.offset.toFixed(4)}` : layer.source.kind === 'osc' ? `${layer.source.wave}@${layer.source.frequency.value ?? layer.source.frequency.from}` : layer.source.kind\n const filters = (layer.filters?.bank ?? []).map((filter) => `${filter.type}@${(filter.frequency.value ?? filter.frequency.from ?? 0).toFixed(1)}`).join(' ')\n const envelope = layer.envelope.map((point) => `${point.time.toFixed(3)}:${point.value.toPrecision(3)}`).join(' ')\n return ` ${text.sheet.layer} ${index + 1}: ${source} at ${layer.at.toFixed(3)} for ${layer.duration.toFixed(3)} ${filters} [${envelope}]`\n })\n return [head, ...layers].join('\\n')\n }\n\n const applyMix = (): void => {\n const profile = engine && MIX_PROFILES[state.mix]\n if (profile) engine.setMix(variantOf(profile, state.reverb, state.compressor))\n }\n\n const setLoop = (): void => {\n loop?.stop()\n loop = undefined\n if (state.loop === NONE) return\n engine.unlock()\n loop = engine.loop(state.loop)\n loop.set({ volume: state.loopLevel, ...(state.loopPitch > 0 ? { frequency: state.loopPitch } : {}) })\n }\n\n const storm = (): void => {\n engine.unlock()\n const base = playOptions()\n const chosen = state.sound\n for (let index = 0; index < STORM; index++) {\n const spread = base.position ? { position: [base.position[0] + (index - STORM / 2), base.position[1], base.position[2]] as Vec3 } : {}\n withMuffling(chosen, () => engine.play(chosen, { ...base, ...spread, seed: state.seed + index }))\n }\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'layer') {\n if (change.id === 'reverb' || change.id === 'compressor') {\n state[change.id] = change.on\n applyMix()\n } else if (change.id === 'panning' || change.id === 'muffling') state[change.id] = change.on\n return\n }\n if (change.kind === 'action') {\n if (change.id === 'play') play()\n else if (change.id === 'voice_storm') storm()\n return\n }\n const { id, value } = change\n if (id === 'sound' && typeof value === 'string') state.sound = value\n else if (id === 'distance' && typeof value === 'string') state.distance = Number(value)\n else if (id === 'bearing' && typeof value === 'number') state.bearing = value\n else if (id === 'volume' && typeof value === 'number') state.volume = value\n else if (id === 'seed' && typeof value === 'number') state.seed = value\n else if (id === 'source' && typeof value === 'string') state.source = value\n else if (id === 'mix' && typeof value === 'string') {\n state.mix = value\n applyMix()\n } else if (id === 'loop' && typeof value === 'string') {\n state.loop = value\n setLoop()\n } else if (id === 'loop_level' && typeof value === 'number') {\n state.loopLevel = value\n loop?.set({ volume: value })\n } else if (id === 'loop_pitch' && typeof value === 'number') {\n state.loopPitch = value\n if (value > 0) loop?.set({ frequency: value })\n }\n }\n\n const items = (): TestableItem[] => {\n const probe = options.probe\n if (!probe) return []\n return [\n {\n id: PROBE_ID,\n name: text.probe,\n movable: false,\n build: (THREE) => {\n const root = probe(THREE) as { userData?: Record<string, unknown> }\n root.userData = root.userData ?? {}\n root.userData[PROBE_ID] = true\n return root\n },\n },\n ]\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'choice', id: 'sound', name: text.controls.sound, options: soundOptions(), default: state.sound },\n { kind: 'choice', id: 'source', name: text.controls.source, hint: text.hints.source, options: [{ id: 'bench', name: text.options.bench }, { id: 'probe', name: text.options.probe }], default: state.source },\n { kind: 'choice', id: 'distance', name: text.controls.distance, hint: text.hints.distance, options: DISTANCES.map((meters) => ({ id: String(meters), name: `${meters} m` })), default: String(state.distance) },\n { kind: 'number', id: 'bearing', name: text.controls.bearing, hint: text.hints.bearing, unit: '°', min: -180, max: 180, step: 15, default: state.bearing },\n { kind: 'number', id: 'volume', name: text.controls.volume, min: 0, max: 1, step: 0.05, default: state.volume },\n { kind: 'choice', id: 'mix', name: text.controls.mix, hint: text.hints.mix, options: Object.keys(MIX_PROFILES).map((id) => ({ id, name: text.mixes[id] ?? id })), default: state.mix },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: state.seed },\n { kind: 'action', id: 'play', name: text.controls.play },\n { kind: 'action', id: 'voice_storm', name: text.controls.voice_storm, hint: text.hints.voice_storm },\n { kind: 'choice', id: 'loop', name: text.controls.loop, options: loopOptions(), default: state.loop },\n { kind: 'number', id: 'loop_level', name: text.controls.loop_level, min: 0, max: 0.6, step: 0.01, default: state.loopLevel },\n { kind: 'number', id: 'loop_pitch', name: text.controls.loop_pitch, hint: text.hints.loop_pitch, unit: 'Hz', min: 0, max: 400, step: 5, default: state.loopPitch },\n ]\n\n const layers = (): ModuleLayer[] => (['reverb', 'compressor', 'panning', 'muffling'] as const).map((id) => ({ id, name: text.layers[id] }))\n\n const metrics = (): ModuleMetric[] => [\n { id: 'voices', name: text.metrics.voices, digits: 0, read: () => engine.stats().voices },\n { id: 'peak', name: text.metrics.peak, digits: 0, max: engine.stats().maxVoices > 0 && Number.isFinite(engine.stats().maxVoices) ? engine.stats().maxVoices : undefined, read: () => engine.stats().peak },\n { id: 'dropped', name: text.metrics.dropped, digits: 0, read: () => engine.stats().dropped },\n { id: 'loops', name: text.metrics.loops, digits: 0, read: () => engine.stats().loops },\n { id: 'context', name: text.metrics.context, read: () => engine.stats().context },\n { id: 'plan_length', name: text.metrics.plan_length, unit: 's', digits: 2, read: () => plan()?.length ?? 0 },\n { id: 'plan_level', name: text.metrics.plan_level, digits: 3, read: () => plan()?.level ?? 0 },\n { id: 'plan_pan', name: text.metrics.plan_pan, digits: 2, read: () => plan()?.pan ?? 0 },\n ...BUS_IDS.map((bus) => ({ id: `level_${bus}`, name: text.metrics[`level_${bus}` as keyof AudioBenchText['metrics']], digits: 3, read: () => engine.level(bus as BusId) })),\n ]\n\n const scenarios = (): Array<ModuleScenario<AudioScenarioLike>> => [\n {\n id: 'panning',\n name: text.scenarios.panning,\n run: ({ expect }) => {\n engine.setListener({ position: [0, 0, 0], yaw: 0 })\n const pan = (at: Vec3): number => engine.plan('bench_ping', { position: at })?.pan ?? Number.NaN\n expect(pan([10, 0, 0]) > 0.3, 'a sound to the right pans right', { pan: pan([10, 0, 0]) })\n expect(pan([-10, 0, 0]) < -0.3, 'a sound to the left pans left', { pan: pan([-10, 0, 0]) })\n expect(Math.abs(pan([0, 0, -10])) < 0.05, 'a sound ahead stays in the middle', { pan: pan([0, 0, -10]) })\n engine.setListener({ position: [0, 0, 0], yaw: Math.PI / 2 })\n expect(pan([0, 0, -10]) > 0.3, 'turning the listener left puts what was ahead on the right', { pan: pan([0, 0, -10]) })\n engine.setListener(listener())\n },\n },\n {\n id: 'distance',\n name: text.scenarios.distance,\n run: ({ expect }) => {\n const levels = [0, 10, 40, 100].map((meters) => engine.plan('bench_ping', { distance: meters })?.level ?? Number.NaN)\n expect(levels.every((level, index) => index === 0 || level < (levels[index - 1] as number)), 'the level falls with the distance', { levels })\n const far = engine.registry.sound('sfx_pistol') ? engine.plan('sfx_pistol', { distance: 400 }) : null\n expect(far === null, 'a game noise class is not played too far to be heard')\n },\n },\n {\n id: 'determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const a = engine.plan('bench_hiss', { seed: 5 })\n const b = engine.plan('bench_hiss', { seed: 5 })\n const c = engine.plan('bench_hiss', { seed: 6 })\n expect(JSON.stringify(a) === JSON.stringify(b), 'the same seed gives the same plan')\n expect(JSON.stringify(a) !== JSON.stringify(c), 'another seed gives another plan')\n },\n },\n {\n id: 'limiter',\n name: text.scenarios.limiter,\n run: ({ expect }) => {\n const voices = createVoiceManager({ maxVoices: 8 })\n const request = (group?: string) => voices.request({ ...(group ? { group } : {}), priority: 3, gain: 0.5, distance: 5, length: 1 })\n const grouped = Array.from({ length: STORM }, () => request('undead_voice')).filter((decision) => decision.accepted).length\n expect(grouped === 1, 'the group cooldown lets one voice of a storm through', { accepted: grouped })\n const plain = Array.from({ length: STORM }, () => request()).filter((decision) => decision.accepted).length\n expect(plain <= 8, 'the global cap holds the rest', { accepted: plain })\n },\n },\n ]\n\n const area = (): { placements: AreaPlacement[]; view: { eye: Vec3; target: Vec3 } } => ({\n placements: options.probe ? [{ item: PROBE_ID, position: PROBE_AT, asleep: true }] : [],\n view: { eye: [0, 1.7, 3], target: [0, 1.4, -10] },\n })\n\n const module: AudioTestModule = {\n id: 'audio_area',\n name: text.name,\n ground: { surface: 'concrete_slab' },\n group: text.group,\n get engine() {\n return engine\n },\n items: () => items(),\n area: () => area(),\n controls: () => controls(),\n layers: () => layers(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n sheet,\n play,\n attach(lent) {\n host = lent\n const shared = (lent.audio as EngineSink | undefined)?.engine\n if (shared && shared !== engine) {\n for (const bank of banks) shared.register(bank)\n engine = shared\n }\n // buses get their nodes now, so the level meters see every sound\n for (const bus of BUS_IDS) {\n engine.setBus(bus, {})\n engine.level(bus)\n }\n lent.bench?.patch('sound', { options: soundOptions() })\n lent.bench?.patch('loop', { options: loopOptions() })\n const off = lent.bench?.onChange(onChange)\n const offFrame = lent.onFrame(() => {\n if (!shared) engine.setListener(listener())\n })\n return () => {\n off?.()\n offFrame()\n loop?.stop()\n loop = undefined\n host = null\n }\n },\n }\n return module\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,wBAAAA;AAAA,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAO;AAAA,MACrB,SAAS,MAAM,QAAQ;AAAA,MACvB,WAAW,MAAM,UAAU;AAAA,MAC3B;AAAA,MACA;AAAA,MACA,OAAO,MAAM;AACX,eAAO;AACP,cAAM,SAAU,KAAK,OAAkC;AACvD,YAAI,UAAU,WAAW,QAAQ;AAC/B,qBAAW,QAAQ,MAAO,QAAO,SAAS,IAAI;AAC9C,mBAAS;AAAA,QACX;AAEA,mBAAW,OAAO,SAAS;AACzB,iBAAO,OAAO,KAAK,CAAC,CAAC;AACrB,iBAAO,MAAM,GAAG;AAAA,QAClB;AACA,aAAK,OAAO,MAAM,SAAS,EAAE,SAAS,aAAa,EAAE,CAAC;AACtD,aAAK,OAAO,MAAM,QAAQ,EAAE,SAAS,YAAY,EAAE,CAAC;AACpD,cAAM,MAAM,KAAK,OAAO,SAAS,QAAQ;AACzC,cAAM,WAAW,KAAK,QAAQ,MAAM;AAClC,cAAI,CAAC,OAAQ,QAAO,YAAY,SAAS,CAAC;AAAA,QAC5C,CAAC;AACD,eAAO,MAAM;AACX,gBAAM;AACN,mBAAS;AACT,gBAAM,KAAK;AACX,iBAAO;AACP,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;","names":["limiterCurve","level","voice","voice","envelope","fixed","recipe","envelope","url","recipe","recipe","recipe","ramp","takes","end","landing","envelope","end","outputStage","envelope","envelope","url","voice","limiterCurve","recipe","url","built","listener","end","envelope","left","right","takes","url","entries","url","url","TAKES","landing","layers","envelope"]}