@adatechnology/game-weather 0.2.1 → 0.2.3

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/blend.ts","../src/daylight.ts","../src/heat.ts","../src/effects.ts","../src/rng.ts","../src/lightning.ts","../src/data/climates.json","../src/data/states.json","../src/registry.ts","../src/scheduler.ts","../src/wetness.ts","../src/weather.ts","../../game-audio/src/rng.ts","../../game-audio/src/recipe.ts","../../game-audio/src/falloff.ts","../../game-audio/src/listener.ts","../../game-audio/src/data/voice-groups.json","../../game-audio/src/voices.ts","../../game-audio/src/plan.ts","../../game-audio/src/loops.ts","../../game-audio/src/data/mix-profiles.json","../../game-audio/src/mix.ts","../../game-audio/src/bank.ts","../../game-audio/src/data/game-sfx.json","../../game-audio/src/recipes/noise-class.ts","../../game-audio/src/recipes/scene.ts","../../game-audio/src/library/crowd_rumble.json","../../game-audio/src/library/engine_saw.json","../../game-audio/src/library/horn.json","../../game-audio/src/library/radio_static.json","../../game-audio/src/library/rotor_blades.json","../../game-audio/src/library/siren.json","../../game-audio/src/library/index.ts","../../game-audio/src/webaudio/noise.ts","../../game-audio/src/webaudio/chain.ts","../../game-audio/src/webaudio/context.ts","../../game-audio/src/webaudio/nodes.ts","../../game-audio/src/webaudio/realize-loop.ts","../../game-audio/src/webaudio/engine-loop.ts","../../game-audio/src/webaudio/engine-noise.ts","../../game-audio/src/webaudio/realize-game.ts","../../game-audio/src/webaudio/realize-layered.ts","../../game-audio/src/webaudio/realize-weapon.ts","../../game-audio/src/webaudio/realize.ts","../../game-audio/src/webaudio/engine.ts","../../game-audio/src/webaudio/sink.ts","../../game-audio/src/bench/locale.ts","../../game-audio/src/bench/module.ts","../src/audio/recipes.ts","../src/audio/sound.ts","../src/bridges.ts","../src/bench/locale.ts","../src/bench/module.ts"],"sourcesContent":["/**\n * @adatechnology/game-weather: pure, seeded weather. States (clear to typhoon) with the numbers of the teams' pages, climates that move between\n * them in game time (2 to 6 hours each, fronts from the west), lightning with the thunder delay, ground wetness, what the weather means for\n * sight, hearing and footsteps, the heat index and the day-night formula, plus the bridges that push it to fluids, interactables, vegetation, vfx, the environment bus and the sound (rain, wind and thunder recipes of game-audio). No three.js, no game content: renderers read it.\n */\nexport { createWeather, createTimeline, DEFAULT_START_HOUR } from './weather'\nexport type { TimelineOptions, Weather, WeatherOptions, WeatherTimeline } from './weather'\nexport { CLIMATES, WEATHER_STATES, createWeatherRegistry } from './registry'\nexport type { RegistryOptions, WeatherRegistry } from './registry'\nexport { blendValues, STATE_VALUE_KEYS, valuesOf } from './blend'\nexport { createScheduler } from './scheduler'\nexport type { Scheduler } from './scheduler'\nexport { FLASH_END_SECONDS, SPEED_OF_SOUND, createLightningStream, flashIntensity, thunderDelay } from './lightning'\nexport type { LightningStream } from './lightning'\nexport { DEFAULT_DRY_OUT_SECONDS, DEFAULT_WET_RISE_SECONDS, createWetness } from './wetness'\nexport type { Wetness, WetnessOptions } from './wetness'\nexport { DRY_VISIBILITY_METERS, NIGHT_SIGHT_LOSS, deriveEffects } from './effects'\nexport type { EffectsInput } from './effects'\nexport { heatIndexC, heatStress } from './heat'\nexport { DAY_REAL_SECONDS, DEFAULT_TIME_SCALE, GAME_DAY_SECONDS, dayFractionAt, daylight } from './daylight'\nexport type { Daylight } from './daylight'\nexport { createRng, createStream, streamSeed } from './rng'\nexport type {\n Climate,\n DeepPartial,\n LightningConfig,\n StateValueKey,\n StateValues,\n Strike,\n WeatherEffects,\n WeatherEventMap,\n WeatherSample,\n WeatherState,\n} from './types'\n\nexport { createWeatherBridges, environmentOf, DEFAULT_BRIDGE_RULES } from './bridges'\nexport type { FilmTarget, InteractablesTarget, VegetationTarget, VfxTarget, WeatherBridgeOptions, WeatherBridgeRules, WeatherBridges, WeatherTargets } from './bridges'\nexport { RAIN_HISS_GAME, RAIN_LOOP, THUNDER, WEATHER_BANK, WEATHER_LOOPS, WEATHER_SOUNDS, WIND_LOOP } from './audio/recipes'\nexport { DEFAULT_RAIN_SOUND, DEFAULT_WIND_SOUND, createWeatherSound, rainVolume, strikePosition, windVolume } from './audio/sound'\nexport type { WeatherSound, WeatherSoundOptions, WeatherSoundStyle } from './audio/sound'\n\nexport { createWeatherTestModule } from './bench/module'\nexport type { WeatherScenarioLike, WeatherTestModule, WeatherTestModuleOptions, WeatherVisual, WeatherVisualContext, WeatherVisualFactory } from './bench/module'\nexport { weatherBenchTextOf } from './bench/locale'\nexport type { WeatherBenchText } from './bench/locale'\n","import type { StateValueKey, StateValues, WeatherState } from './types'\n\nexport const STATE_VALUE_KEYS: readonly StateValueKey[] = [\n 'rain',\n 'drops',\n 'sheets',\n 'windX',\n 'windZ',\n 'gust',\n 'fogFar',\n 'fogDensity',\n 'skyScale',\n 'visibility',\n 'humidity',\n 'temperatureDeltaC',\n 'wetness',\n 'hearingScale',\n 'footstepScale',\n 'dryingScale',\n 'debrisPush',\n 'haze',\n 'mistPerSecond',\n 'ashPerSecond',\n]\n\nexport function valuesOf(state: WeatherState): StateValues {\n const values: Record<string, number> = {}\n for (const key of STATE_VALUE_KEYS) values[key] = state[key]\n return values as unknown as StateValues\n}\n\n/** Every number between two states: `progress` 0 is `from`, 1 is `to`. */\nexport function blendValues(from: StateValues, to: StateValues, progress: number): StateValues {\n const amount = Math.min(1, Math.max(0, progress))\n const blended: Record<string, number> = {}\n for (const key of STATE_VALUE_KEYS) blended[key] = from[key] + (to[key] - from[key]) * amount\n return blended as unknown as StateValues\n}\n","/** A game day lasts 20 real minutes in the slice (jogo.js L69127: `dayT + dt / 1200`). */\nexport const DAY_REAL_SECONDS = 1200\nexport const GAME_DAY_SECONDS = 86400\n/** Game seconds per real second of the 20-minute day. */\nexport const DEFAULT_TIME_SCALE = GAME_DAY_SECONDS / DAY_REAL_SECONDS\n\nconst NIGHT_SPAN = 2.2\n\nconst clamp = (value: number, low: number, high: number): number => (value < low ? low : value > high ? high : value)\n\nexport type Daylight = {\n /** Sun height 0..1 (`s` of the game). */\n readonly sun: number\n /** 0 in full daylight, 1 in the darkest night. */\n readonly nightFactor: number\n}\n\n/** jogo.js L69128-L69130: `s = clamp(sin(dayT·2π − π/2)·0.5 + 0.5, 0, 1)`, `nightF = 1 − clamp(s·2.2, 0, 1)`. `dayFraction` 0 is midnight. */\nexport function daylight(dayFraction: number): Daylight {\n const sun = clamp(Math.sin(dayFraction * Math.PI * 2 - Math.PI / 2) * 0.5 + 0.5, 0, 1)\n return { sun, nightFactor: 1 - clamp(sun * NIGHT_SPAN, 0, 1) }\n}\n\n/** The fraction of the day after `gameSeconds` from `startHour`. */\nexport function dayFractionAt(startHour: number, gameSeconds: number): number {\n const fraction = (startHour / 24 + gameSeconds / GAME_DAY_SECONDS) % 1\n return fraction < 0 ? fraction + 1 : fraction\n}\n","const HEAT_STRESS_BANDS: ReadonlyArray<readonly [indexC: number, stress: number]> = [\n [27, 0],\n [32, 1 / 3],\n [41, 2 / 3],\n [54, 1],\n]\nconst NOAA_REGRESSION_FROM_F = 80\n\nconst toFahrenheit = (celsius: number): number => (celsius * 9) / 5 + 32\nconst toCelsius = (fahrenheit: number): number => ((fahrenheit - 32) * 5) / 9\n\n/**\n * NOAA heat index in °C: the Steadman estimate averaged with the temperature, and from 80 °F up the Rothfusz regression with the low-humidity and\n * high-humidity adjustments. Built from + - * / and `sqrt` only, so it is the same on every engine.\n */\nexport function heatIndexC(temperatureC: number, relativeHumidityPercent: number): number {\n const t = toFahrenheit(temperatureC)\n const r = relativeHumidityPercent\n const steadman = 0.5 * (t + 61 + (t - 68) * 1.2 + r * 0.094)\n const simple = (steadman + t) / 2\n if (simple < NOAA_REGRESSION_FROM_F) return toCelsius(simple)\n let index =\n -42.379 +\n 2.04901523 * t +\n 10.14333127 * r -\n 0.22475541 * t * r -\n 0.00683783 * t * t -\n 0.05481717 * r * r +\n 0.00122874 * t * t * r +\n 0.00085282 * t * r * r -\n 0.00000199 * t * t * r * r\n if (r < 13 && t >= 80 && t <= 112) index -= ((13 - r) / 4) * Math.sqrt((17 - Math.abs(t - 95)) / 17)\n else if (r > 85 && t >= 80 && t <= 87) index += ((r - 85) / 10) * ((87 - t) / 5)\n return toCelsius(index)\n}\n\n/** 0..1 across the NOAA bands (caution 27, extreme caution 32, danger 41, extreme danger 54 °C), linear between them. */\nexport function heatStress(heatIndex: number): number {\n const first = HEAT_STRESS_BANDS[0]!\n const last = HEAT_STRESS_BANDS[HEAT_STRESS_BANDS.length - 1]!\n if (heatIndex <= first[0]) return first[1]\n if (heatIndex >= last[0]) return last[1]\n for (let index = 1; index < HEAT_STRESS_BANDS.length; index++) {\n const [upperC, upperStress] = HEAT_STRESS_BANDS[index]!\n const [lowerC, lowerStress] = HEAT_STRESS_BANDS[index - 1]!\n if (heatIndex <= upperC) return lowerStress + ((heatIndex - lowerC) / (upperC - lowerC)) * (upperStress - lowerStress)\n }\n return last[1]\n}\n","import { heatIndexC, heatStress } from './heat'\nimport type { StateValues, WeatherEffects } from './types'\n\n/** Gameplay visibility of a dry day (the game's dry fog far, jogo.js L69141): `sightScale` is the visibility against it. */\nexport const DRY_VISIBILITY_METERS = 220\n/** jogo.js L66872: sight is `perc[0] × (1 − 0.4 × nightF)`. */\nexport const NIGHT_SIGHT_LOSS = 0.4\n\nexport type EffectsInput = {\n readonly values: StateValues\n readonly nightFactor: number\n readonly temperatureC: number\n readonly humidityPercent: number\n readonly lightningReveal: number\n}\n\n/** What the weather means for gameplay, as numbers for whoever has eyes, ears or feet in the world (perception, footsteps, heat). */\nexport function deriveEffects(input: EffectsInput): WeatherEffects {\n const { values, nightFactor } = input\n const weatherSight = Math.min(1, Math.max(0, values.visibility / DRY_VISIBILITY_METERS))\n const heatIndex = heatIndexC(input.temperatureC, input.humidityPercent)\n return {\n visibility: values.visibility,\n sightScale: weatherSight * (1 - NIGHT_SIGHT_LOSS * nightFactor),\n hearingScale: values.hearingScale,\n footstepScale: values.footstepScale,\n heatIndexC: heatIndex,\n heatStress: heatStress(heatIndex),\n lightningReveal: input.lightningReveal,\n dryingScale: values.dryingScale,\n debrisPush: values.debrisPush,\n }\n}\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; returns floats in [0, 1). */\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/** A seed for the stream called `name`: the same seed gives each name its own sequence, so lightning never shifts the schedule. */\nexport function streamSeed(seed: number, name: string): number {\n let hash = FNV_OFFSET\n for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function createStream(seed: number, name: string): () => number {\n return createRng(streamSeed(seed, name))\n}\n\nexport function drawBetween(rng: () => number, range: readonly [min: number, max: number]): number {\n return range[0] + rng() * (range[1] - range[0])\n}\n","import { createStream, drawBetween } from './rng'\nimport type { LightningConfig } from './types'\n\n/** Speed of sound in air, m/s: a physical constant, so it is not configurable. */\nexport const SPEED_OF_SOUND = 343\n\n/** Seconds a flash goes on after a strike before the scene is back to normal (Workshop W1068: `k > .4`). */\nexport const FLASH_END_SECONDS = 0.4\n\n/** Seconds from the flash to the thunder for a strike `distance` metres away. */\nexport function thunderDelay(distance: number): number {\n return distance / SPEED_OF_SOUND\n}\n\n/** The Workshop double flash (W1068): full for 0.08 s, 0.2 until 0.16 s, 0.8 until 0.26 s, then dark. `elapsed` is seconds since the strike. */\nexport function flashIntensity(elapsed: number): number {\n if (elapsed < 0 || elapsed >= FLASH_END_SECONDS) return 0\n if (elapsed < 0.08) return 1\n if (elapsed < 0.16) return 0.2\n if (elapsed < 0.26) return 0.8\n return 0\n}\n\nexport type LightningStream = {\n /** Seconds from entering a state with lightning to its first strike. */\n first(config: LightningConfig): number\n /** Seconds from a strike to the next one. */\n interval(config: LightningConfig): number\n /** Where a strike lands: metres and degrees clockwise from north. Draws the distance, then the bearing. */\n place(config: LightningConfig): { readonly distance: number; readonly bearing: number }\n}\n\n/** The lightning's own seeded stream, apart from the scheduler's: the server can send the seed and every client sees the same strikes. */\nexport function createLightningStream(seed: number): LightningStream {\n const rng = createStream(seed, 'lightning')\n return {\n first: (config) => drawBetween(rng, config.first),\n interval: (config) => drawBetween(rng, config.interval),\n place(config) {\n const distance = drawBetween(rng, config.distance)\n return { distance, bearing: rng() * 360 }\n },\n }\n}\n","[\n {\n \"id\": \"temperate\",\n \"sources\": [\"galeria-vale-cinzento:L1393 (changes every 2-6 h, arrives from the west)\", \"design:T6 3.2 kit default: mostly clear and overcast, no extremes\"],\n \"start\": \"clear\",\n \"dwellHours\": [2, 6],\n \"blendMinutes\": 10,\n \"frontDirection\": [1, 0],\n \"temperatureC\": { \"mean\": 16, \"swing\": 6 },\n \"humidityOffset\": 0,\n \"transitions\": {\n \"clear\": { \"overcast\": 4, \"windy\": 1, \"fog\": 1, \"light_rain\": 1 },\n \"overcast\": { \"clear\": 3, \"light_rain\": 3, \"heavy_rain\": 1, \"fog\": 1, \"windy\": 1 },\n \"light_rain\": { \"overcast\": 3, \"clear\": 2, \"heavy_rain\": 2 },\n \"heavy_rain\": { \"light_rain\": 3, \"overcast\": 2, \"storm\": 1 },\n \"storm\": { \"heavy_rain\": 3, \"light_rain\": 2, \"overcast\": 1 },\n \"fog\": { \"clear\": 3, \"overcast\": 2 },\n \"windy\": { \"clear\": 3, \"overcast\": 3, \"light_rain\": 1 }\n }\n },\n {\n \"id\": \"tropical\",\n \"sources\": [\"galeria-vale-cinzento:L1393 (changes every 2-6 h, arrives from the west)\", \"design:T6 3.2 and Q3: extremes rare and enabled\"],\n \"start\": \"clear\",\n \"dwellHours\": [2, 6],\n \"blendMinutes\": 10,\n \"frontDirection\": [1, 0],\n \"temperatureC\": { \"mean\": 29, \"swing\": 3 },\n \"humidityOffset\": 0.1,\n \"transitions\": {\n \"clear\": { \"overcast\": 3, \"light_rain\": 2, \"windy\": 1, \"extreme_heat\": 0.8 },\n \"overcast\": { \"clear\": 3, \"light_rain\": 3, \"heavy_rain\": 2, \"fog\": 0.5 },\n \"light_rain\": { \"overcast\": 3, \"clear\": 2, \"heavy_rain\": 2 },\n \"heavy_rain\": { \"light_rain\": 3, \"overcast\": 2, \"storm\": 1.5 },\n \"storm\": { \"heavy_rain\": 3, \"light_rain\": 2, \"overcast\": 1, \"cyclone\": 0.5 },\n \"fog\": { \"clear\": 3, \"overcast\": 2 },\n \"windy\": { \"clear\": 3, \"overcast\": 2, \"light_rain\": 1, \"storm\": 0.5 },\n \"extreme_heat\": { \"clear\": 4, \"overcast\": 2, \"storm\": 0.8 },\n \"cyclone\": { \"storm\": 3, \"heavy_rain\": 2, \"typhoon\": 0.5 },\n \"typhoon\": { \"cyclone\": 3, \"storm\": 2 }\n }\n }\n]\n","[\n {\n \"id\": \"clear\",\n \"sources\": [\"jogo:L69141 (fog far 220 dry)\", \"showroom.js:L1693-1710 (breeze 3.5, 1.5 m/s)\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 3.5, \"windZ\": 1.5, \"gust\": 5,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 220,\n \"humidity\": 0.5, \"temperatureDeltaC\": 0, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"overcast\",\n \"sources\": [\"cena-de-arte:L413 (wind .35, .12)\", \"cena-de-arte:L36 (FogExp2 .03)\", \"design:T6 sky x0.9\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.35, \"windZ\": 0.12, \"gust\": 0.6,\n \"fogFar\": 220, \"fogDensity\": 0.03, \"skyScale\": 0.9, \"visibility\": 200,\n \"humidity\": 0.65, \"temperatureDeltaC\": -1, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"light_rain\",\n \"sources\": [\"oficina-vfx:W1065 (Garoa: 900 drops, slant .3)\", \"jogo:L70416-70427 (rain level .035)\", \"design:T6 2.5 mm/h, wetness .35, visibility 160, hearing x0.8 (Q4)\"],\n \"rain\": 2.5, \"drops\": 900, \"sheets\": 0,\n \"windX\": 0.3, \"windZ\": 0, \"gust\": 0.6,\n \"fogFar\": 180, \"fogDensity\": 0, \"skyScale\": 0.9, \"visibility\": 160,\n \"humidity\": 0.85, \"temperatureDeltaC\": -2, \"wetness\": 0.35,\n \"hearingScale\": 0.8, \"footstepScale\": 0.85, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"heavy_rain\",\n \"sources\": [\"oficina-vfx:W1065 (Chuva: 2200 drops, slant 1.2)\", \"cena-de-arte:L1314 (rain gain .06)\", \"jogo:L69141 (fog far 140, sky x0.8)\", \"galeria-vale-cinzento:L1393 (vision 120 m, quieter steps)\", \"design:T6 15 mm/h, hearing x0.6 (Q4)\"],\n \"rain\": 15, \"drops\": 2200, \"sheets\": 0,\n \"windX\": 1.2, \"windZ\": 0, \"gust\": 2,\n \"fogFar\": 140, \"fogDensity\": 0, \"skyScale\": 0.8, \"visibility\": 120,\n \"humidity\": 0.9, \"temperatureDeltaC\": -4, \"wetness\": 0.8,\n \"hearingScale\": 0.6, \"footstepScale\": 0.7, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"storm\",\n \"sources\": [\"oficina-vfx:W1065-1069 (Temporal: 4000 drops, slant 4.5, lightning 3.5-6 s, first at 2-4 s, sheets)\", \"showroom.js (60 mm/h)\", \"design:T6 hearing x0.5 (Q4)\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 4.5, \"windZ\": 0, \"gust\": 6,\n \"fogFar\": 110, \"fogDensity\": 0, \"skyScale\": 0.7, \"visibility\": 100,\n \"humidity\": 0.92, \"temperatureDeltaC\": -5, \"wetness\": 1,\n \"hearingScale\": 0.5, \"footstepScale\": 0.6, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"fog\",\n \"sources\": [\"oficina-vfx:W1073-1080 (density .075, ground mist 5/s, ash 14/s)\", \"jogo:L69101 (zone fog far 60)\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.3, \"windZ\": 0.1, \"gust\": 0.5,\n \"fogFar\": 60, \"fogDensity\": 0.075, \"skyScale\": 0.85, \"visibility\": 40,\n \"humidity\": 0.95, \"temperatureDeltaC\": -3, \"wetness\": 0.15,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 5, \"ashPerSecond\": 14\n },\n {\n \"id\": \"windy\",\n \"sources\": [\"cena-de-arte:L1315 (wind loop)\", \"design:T6 Q3 8 m/s, gust 12\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 8, \"windZ\": 0, \"gust\": 12,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 220,\n \"humidity\": 0.45, \"temperatureDeltaC\": -1, \"wetness\": 0,\n \"hearingScale\": 0.85, \"footstepScale\": 0.9, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"cyclone\",\n \"sources\": [\"design:T6 Q3 physics preset, no team source: tropical cyclone 33 m/s sustained, gust x1.3, storm rain, debris push\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 33, \"windZ\": 0, \"gust\": 42.9,\n \"fogFar\": 80, \"fogDensity\": 0, \"skyScale\": 0.6, \"visibility\": 60,\n \"humidity\": 0.9, \"temperatureDeltaC\": 0, \"wetness\": 1,\n \"hearingScale\": 0.3, \"footstepScale\": 0.5, \"dryingScale\": 1, \"debrisPush\": 8,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"typhoon\",\n \"sources\": [\"design:T6 Q3 physics preset, no team source: typhoon 50 m/s sustained, gust x1.3, storm rain, debris push\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 50, \"windZ\": 0, \"gust\": 65,\n \"fogFar\": 60, \"fogDensity\": 0, \"skyScale\": 0.5, \"visibility\": 40,\n \"humidity\": 0.9, \"temperatureDeltaC\": 0, \"wetness\": 1,\n \"hearingScale\": 0.25, \"footstepScale\": 0.4, \"dryingScale\": 1, \"debrisPush\": 18,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"extreme_heat\",\n \"sources\": [\"design:T6 Q3 no team source: 38 C at the tropical noon (+6 over the climate), 60 % humidity, haze, drying x2\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.8, \"windZ\": 0.3, \"gust\": 1.5,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 200,\n \"humidity\": 0.6, \"temperatureDeltaC\": 6, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 2, \"debrisPush\": 0,\n \"haze\": 1, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n }\n]\n","import climatesJson from './data/climates.json'\nimport statesJson from './data/states.json'\nimport type { Climate, DeepPartial, WeatherState } from './types'\n\nexport const WEATHER_STATES: readonly WeatherState[] = statesJson as unknown as readonly WeatherState[]\nexport const CLIMATES: readonly Climate[] = climatesJson as unknown as readonly Climate[]\n\nexport type RegistryOptions = {\n /** Added to the shipped states or, when the id exists, replacing it. */\n readonly states?: readonly WeatherState[]\n readonly climates?: readonly Climate[]\n /** Merged into a shipped or added entry by id; a patch for an id that does not exist is ignored. */\n readonly patch?: {\n readonly states?: Readonly<Record<string, DeepPartial<WeatherState>>>\n readonly climates?: Readonly<Record<string, DeepPartial<Climate>>>\n }\n readonly remove?: { readonly states?: readonly string[]; readonly climates?: readonly string[] }\n}\n\nexport type WeatherRegistry = {\n state(id: string): WeatherState | undefined\n climate(id: string): Climate | undefined\n stateIds(): string[]\n climateIds(): string[]\n registerState(state: WeatherState): void\n registerClimate(climate: Climate): void\n patchState(id: string, patch: DeepPartial<WeatherState>): void\n patchClimate(id: string, patch: DeepPartial<Climate>): void\n removeState(id: string): void\n removeClimate(id: string): void\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\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\nfunction deepMerge<TValue>(base: TValue, patch: DeepPartial<TValue>): TValue {\n return mergeRecords(base as Record<string, unknown>, patch as Record<string, unknown>) as TValue\n}\n\ntype Entry = { readonly id: string }\n\nfunction createTable<TEntry extends Entry>(shipped: readonly TEntry[]): Map<string, TEntry> {\n return new Map(shipped.map((entry) => [entry.id, entry]))\n}\n\nfunction patchEntry<TEntry extends Entry>(table: Map<string, TEntry>, id: string, patch: DeepPartial<TEntry>): void {\n const entry = table.get(id)\n if (entry) table.set(id, deepMerge(entry, patch))\n}\n\n/** The shipped states and climates with yours added, patched or removed; change it later with the same verbs. */\nexport function createWeatherRegistry(options: RegistryOptions = {}): WeatherRegistry {\n const states = createTable(WEATHER_STATES)\n const climates = createTable(CLIMATES)\n for (const state of options.states ?? []) states.set(state.id, state)\n for (const climate of options.climates ?? []) climates.set(climate.id, climate)\n for (const [id, patch] of Object.entries(options.patch?.states ?? {})) patchEntry(states, id, patch)\n for (const [id, patch] of Object.entries(options.patch?.climates ?? {})) patchEntry(climates, id, patch)\n for (const id of options.remove?.states ?? []) states.delete(id)\n for (const id of options.remove?.climates ?? []) climates.delete(id)\n return {\n state: (id) => states.get(id),\n climate: (id) => climates.get(id),\n stateIds: () => [...states.keys()],\n climateIds: () => [...climates.keys()],\n registerState: (state) => void states.set(state.id, state),\n registerClimate: (climate) => void climates.set(climate.id, climate),\n patchState: (id, patch) => patchEntry(states, id, patch),\n patchClimate: (id, patch) => patchEntry(climates, id, patch),\n removeState: (id) => void states.delete(id),\n removeClimate: (id) => void climates.delete(id),\n }\n}\n","import { createStream, drawBetween } from './rng'\nimport type { Climate } from './types'\n\nconst SECONDS_PER_HOUR = 3600\n/** A state lasts at least this long, so a climate patched to a zero dwell cannot stall the clock. */\nconst MIN_DWELL_SECONDS = 1\n\nexport type Scheduler = {\n /** Game seconds at which the current state ends. */\n nextChangeAt(): number\n /** Picks the state after `current`, then draws how long it lasts from `at`. Returns the new state's id. */\n next(current: string, at: number): string\n /** Draws a new duration from `at` (after a forced change). */\n restart(at: number): void\n}\n\n/**\n * A seeded Markov chain in game time. Draw order, fixed so the timeline repeats: at start one dwell; at each change the next state first\n * (one draw, over the weights in the climate's order), then its dwell. States `isKnown` rejects are left out of the weights.\n */\nexport function createScheduler(climate: Climate, seed: number, isKnown: (id: string) => boolean): Scheduler {\n const rng = createStream(seed, 'schedule')\n let changeAt = 0\n const drawDwell = (from: number): number => from + Math.max(MIN_DWELL_SECONDS, drawBetween(rng, climate.dwellHours) * SECONDS_PER_HOUR)\n changeAt = drawDwell(0)\n return {\n nextChangeAt: () => changeAt,\n next(current, at) {\n const options = Object.entries(climate.transitions[current] ?? {}).filter(([id, weight]) => weight > 0 && isKnown(id))\n const total = options.reduce((sum, [, weight]) => sum + weight, 0)\n let chosen = current\n if (total > 0) {\n let pick = rng() * total\n chosen = options[options.length - 1]![0]\n for (const [id, weight] of options) {\n if (pick < weight) {\n chosen = id\n break\n }\n pick -= weight\n }\n }\n changeAt = drawDwell(at)\n return chosen\n },\n restart(at) {\n changeAt = drawDwell(at)\n },\n }\n}\n","export const DEFAULT_WET_RISE_SECONDS = 120\n/** The Workshop sheet: the water goes back to the colour of the ground 3 minutes after the rain stops. */\nexport const DEFAULT_DRY_OUT_SECONDS = 180\n\nexport type WetnessOptions = {\n /** Seconds of rain to wet the ground fully. */\n readonly riseSeconds?: number\n /** Seconds from the end of the rain until the ground is dry. */\n readonly dryOutSeconds?: number\n}\n\nexport type Wetness = {\n value(): number\n /** Moves `seconds` toward `target` (the wetness the weather asks for); `dryingScale` speeds the dry-out up. Returns the new value. */\n update(seconds: number, target: number, dryingScale?: number): number\n reset(value?: number): void\n}\n\n/** Ground wetness: rises while the weather asks for more, then falls in a straight line that ends `dryOutSeconds` after the start of the fall. */\nexport function createWetness(options: WetnessOptions = {}): Wetness {\n const riseSeconds = options.riseSeconds ?? DEFAULT_WET_RISE_SECONDS\n const dryOutSeconds = options.dryOutSeconds ?? DEFAULT_DRY_OUT_SECONDS\n let current = 0\n let peak = 0\n let isDrying = false\n return {\n value: () => current,\n update(seconds, target, dryingScale = 1) {\n if (target > current) {\n isDrying = false\n current = Math.min(target, current + seconds / riseSeconds)\n } else if (target < current) {\n if (!isDrying) {\n isDrying = true\n peak = current\n }\n current = Math.max(target, current - (peak * seconds * dryingScale) / dryOutSeconds)\n } else isDrying = false\n return current\n },\n reset(value = 0) {\n current = value\n peak = value\n isDrying = false\n },\n }\n}\n","import { blendValues, valuesOf } from './blend'\nimport { DEFAULT_TIME_SCALE, daylight, dayFractionAt } from './daylight'\nimport { deriveEffects } from './effects'\nimport { createLightningStream, flashIntensity, thunderDelay } from './lightning'\nimport { createWeatherRegistry } from './registry'\nimport type { RegistryOptions, WeatherRegistry } from './registry'\nimport { createScheduler } from './scheduler'\nimport type { Climate, StateValues, Strike, WeatherEventMap, WeatherSample, WeatherState } from './types'\nimport { createWetness } from './wetness'\nimport type { WetnessOptions } from './wetness'\n\nexport const DEFAULT_START_HOUR = 8\nconst SECONDS_PER_MINUTE = 60\nconst WETNESS_STEP_SECONDS = 1\n\nexport type WeatherOptions = RegistryOptions & {\n /** Seed of the schedule and of the lightning (each has its own stream). Default 1. */\n readonly seed?: number\n /** Climate id. Default `temperate`. */\n readonly climate?: string\n /** First state; default the climate's `start`, which is `clear`: the normal world comes first. */\n readonly start?: string\n /** Game seconds per real second. Default 72 (the 20-minute day). */\n readonly timeScale?: number\n /** Hour of the day the world starts at. Default 8. */\n readonly startHour?: number\n /** `false` keeps the state until `force` changes it. Default true. */\n readonly autoSchedule?: boolean\n readonly wetness?: WetnessOptions\n /** An existing registry, instead of building one from the registry options. */\n readonly registry?: WeatherRegistry\n}\n\nexport type WeatherTimeline = {\n readonly seed: number\n readonly climate: string\n readonly start: string\n readonly hours: number\n readonly sampleMinutes: number\n readonly transitions: ReadonlyArray<{ readonly gameSeconds: number; readonly from: string; readonly to: string }>\n readonly strikes: readonly Strike[]\n readonly samples: ReadonlyArray<Readonly<Record<string, number | string>>>\n}\n\nexport type Weather = {\n readonly registry: WeatherRegistry\n /** Moves the world forward by `dt` real seconds (game time moves `timeScale` times as fast). Events fire in order as they are crossed. */\n advance(dt: number): void\n sample(): WeatherSample\n /** The state being blended to, or settled in. */\n state(): string\n /** Changes state now, blending over `blendSeconds` real seconds (0 is at once); the new state then lasts a normal dwell. */\n force(id: string, blendSeconds?: number): void\n setTimeScale(timeScale: number): void\n setAutoSchedule(isOn: boolean): void\n /** What a fresh world with these options does over `hours` game hours; the live world is not touched. */\n timeline(hours: number, sampleMinutes?: number): WeatherTimeline\n on<TEvent extends keyof WeatherEventMap>(event: TEvent, listener: (payload: WeatherEventMap[TEvent]) => void): () => void\n}\n\ntype Blend = { startedAt: number; duration: number }\n\nconst clamp01 = (value: number): number => Math.min(1, Math.max(0, value))\n\nfunction requireClimate(registry: WeatherRegistry, id: string): Climate {\n const climate = registry.climate(id)\n if (!climate) throw new Error(`game-weather: unknown climate \"${id}\"`)\n return climate\n}\n\nfunction requireState(registry: WeatherRegistry, id: string): WeatherState {\n const state = registry.state(id)\n if (!state) throw new Error(`game-weather: unknown state \"${id}\"`)\n return state\n}\n\nexport function createWeather(options: WeatherOptions = {}): Weather {\n const registry = options.registry ?? createWeatherRegistry(options)\n const seed = options.seed ?? 1\n const climateId = options.climate ?? 'temperate'\n const startClimate = requireClimate(registry, climateId)\n const startState = requireState(registry, options.start ?? startClimate.start)\n const startHour = options.startHour ?? DEFAULT_START_HOUR\n const scheduler = createScheduler(startClimate, seed, (id) => registry.state(id) !== undefined)\n const lightning = createLightningStream(seed)\n const wetness = createWetness(options.wetness)\n const listeners = new Map<keyof WeatherEventMap, Set<(payload: never) => void>>()\n\n let timeScale = options.timeScale ?? DEFAULT_TIME_SCALE\n let isAutoSchedule = options.autoSchedule ?? true\n let gameSeconds = 0\n let simSeconds = 0\n let target = startState\n let targetValues = valuesOf(startState)\n let fromValues: StateValues = targetValues\n let previousId: string | undefined\n let blend: Blend = { startedAt: 0, duration: 0 }\n let nextStrikeAt: number | undefined\n let strikeCount = 0\n let lastStrike: Strike | undefined\n const pendingThunder: Strike[] = []\n\n const climate = (): Climate => registry.climate(climateId) ?? startClimate\n\n const emit = <TEvent extends keyof WeatherEventMap>(event: TEvent, payload: WeatherEventMap[TEvent]): void => {\n for (const listener of [...(listeners.get(event) ?? [])]) (listener as (value: WeatherEventMap[TEvent]) => void)(payload)\n }\n\n const progressAt = (at: number): number => (blend.duration <= 0 ? 1 : clamp01((at - blend.startedAt) / blend.duration))\n const valuesAt = (at: number): StateValues => blendValues(fromValues, targetValues, progressAt(at))\n\n const scheduleFirstStrike = (atSim: number): void => {\n nextStrikeAt = target.lightning ? atSim + lightning.first(target.lightning) : undefined\n }\n\n const enter = (id: string, atGame: number, atSim: number, blendGameSeconds: number): void => {\n const next = requireState(registry, id)\n fromValues = valuesAt(atGame)\n previousId = target.id\n target = next\n targetValues = valuesOf(next)\n blend = { startedAt: atGame, duration: blendGameSeconds }\n scheduleFirstStrike(atSim)\n emit('transition', { from: previousId, to: id, gameSeconds: atGame })\n }\n\n const strikeAt = (atSim: number, startGame: number, startSim: number): void => {\n const config = target.lightning!\n const place = lightning.place(config)\n const strike: Strike = {\n id: strikeCount++,\n time: atSim,\n gameSeconds: startGame + (atSim - startSim) * timeScale,\n distance: place.distance,\n bearing: place.bearing,\n thunderDelay: thunderDelay(place.distance),\n }\n lastStrike = strike\n pendingThunder.push(strike)\n pendingThunder.sort((a, b) => a.time + a.thunderDelay - (b.time + b.thunderDelay))\n nextStrikeAt = atSim + lightning.interval(config)\n emit('strike', strike)\n }\n\n scheduleFirstStrike(0)\n\n const runEvents = (startGame: number, startSim: number, endSim: number): void => {\n for (;;) {\n const changeSim = isAutoSchedule ? Math.max(startSim, startSim + (scheduler.nextChangeAt() - startGame) / timeScale) : Infinity\n const strikeSim = nextStrikeAt ?? Infinity\n const thunder = pendingThunder[0]\n const thunderSim = thunder ? thunder.time + thunder.thunderDelay : Infinity\n const earliest = Math.min(changeSim, strikeSim, thunderSim)\n if (earliest > endSim) return\n if (earliest === changeSim) {\n const atGame = Math.max(startGame, scheduler.nextChangeAt())\n const next = scheduler.next(target.id, atGame)\n enter(next, atGame, changeSim, climate().blendMinutes * SECONDS_PER_MINUTE)\n } else if (earliest === strikeSim) strikeAt(strikeSim, startGame, startSim)\n else emit('thunder', pendingThunder.shift()!)\n }\n }\n\n const wet = (startGame: number, endGame: number, seconds: number): void => {\n const steps = Math.max(1, Math.ceil(seconds / WETNESS_STEP_SECONDS))\n for (let step = 1; step <= steps; step++) {\n const values = valuesAt(startGame + ((endGame - startGame) * step) / steps)\n wetness.update(seconds / steps, values.wetness, values.dryingScale)\n }\n }\n\n const api: Weather = {\n registry,\n advance(dt) {\n if (!(dt > 0)) return\n const startGame = gameSeconds\n const startSim = simSeconds\n const endGame = startGame + dt * timeScale\n runEvents(startGame, startSim, startSim + dt)\n gameSeconds = endGame\n simSeconds = startSim + dt\n wet(startGame, endGame, dt)\n },\n sample() {\n const values = valuesAt(gameSeconds)\n const dayFraction = dayFractionAt(startHour, gameSeconds)\n const { sun, nightFactor } = daylight(dayFraction)\n const current = climate()\n const temperatureC = current.temperatureC.mean + current.temperatureC.swing * (2 * sun - 1) + values.temperatureDeltaC\n const humidityPercent = clamp01(values.humidity + current.humidityOffset) * 100\n const progress = progressAt(gameSeconds)\n return {\n ...values,\n gameSeconds,\n dayFraction,\n hour: dayFraction * 24,\n nightFactor,\n sun,\n state: target.id,\n previous: progress < 1 ? previousId : undefined,\n blend: progress,\n front: { direction: current.frontDirection, progress },\n windSpeed: Math.sqrt(values.windX * values.windX + values.windZ * values.windZ),\n temperatureC,\n humidityPercent,\n groundWetness: wetness.value(),\n flash: lastStrike ? flashIntensity(simSeconds - lastStrike.time) : 0,\n effects: deriveEffects({ values, nightFactor, temperatureC, humidityPercent, lightningReveal: target.lightning?.reveal ?? 0 }),\n }\n },\n state: () => target.id,\n force(id, blendSeconds = 0) {\n enter(id, gameSeconds, simSeconds, blendSeconds * timeScale)\n scheduler.restart(gameSeconds)\n },\n setTimeScale(next) {\n if (!(next > 0)) throw new Error('game-weather: timeScale must be above 0')\n timeScale = next\n },\n setAutoSchedule(isOn) {\n if (isOn && !isAutoSchedule) scheduler.restart(gameSeconds)\n isAutoSchedule = isOn\n },\n timeline: (hours, sampleMinutes) => createTimeline({ ...options, registry, hours, ...(sampleMinutes === undefined ? {} : { sampleMinutes }) }),\n on(event, listener) {\n const set = listeners.get(event) ?? new Set()\n set.add(listener as (payload: never) => void)\n listeners.set(event, set)\n return () => void set.delete(listener as (payload: never) => void)\n },\n }\n return api\n}\n\nexport type TimelineOptions = WeatherOptions & {\n readonly hours: number\n /** Game minutes between samples. Default 10. */\n readonly sampleMinutes?: number\n}\n\nconst TIMELINE_DECIMALS = 6\nconst round = (value: number): number => Math.round(value * 10 ** TIMELINE_DECIMALS) / 10 ** TIMELINE_DECIMALS + 0\n\n/**\n * What a fresh world does over `hours` game hours, stepping one game minute at a time: the state changes, the strikes (time, distance, bearing) and\n * a sample every `sampleMinutes`. Plain JSON, rounded to 6 decimals, so it can be a golden.\n */\nexport function createTimeline(options: TimelineOptions): WeatherTimeline {\n const weather = createWeather(options)\n const timeScale = options.timeScale ?? DEFAULT_TIME_SCALE\n const sampleMinutes = options.sampleMinutes ?? 10\n const transitions: Array<{ gameSeconds: number; from: string; to: string }> = []\n const strikes: Strike[] = []\n weather.on('transition', (event) => transitions.push({ gameSeconds: round(event.gameSeconds), from: event.from, to: event.to }))\n weather.on('strike', (strike) =>\n strikes.push({ id: strike.id, time: round(strike.time), gameSeconds: round(strike.gameSeconds), distance: round(strike.distance), bearing: round(strike.bearing), thunderDelay: round(strike.thunderDelay) }),\n )\n const samples: Array<Record<string, number | string>> = []\n const record = (minute: number): void => {\n const sample = weather.sample()\n samples.push({\n at: minute * SECONDS_PER_MINUTE,\n hour: round(sample.hour),\n state: sample.state,\n blend: round(sample.blend),\n rain: round(sample.rain),\n windSpeed: round(sample.windSpeed),\n gust: round(sample.gust),\n visibility: round(sample.effects.visibility),\n sightScale: round(sample.effects.sightScale),\n hearingScale: round(sample.effects.hearingScale),\n temperatureC: round(sample.temperatureC),\n heatIndexC: round(sample.effects.heatIndexC),\n heatStress: round(sample.effects.heatStress),\n wetness: round(sample.groundWetness),\n nightFactor: round(sample.nightFactor),\n })\n }\n record(0)\n const minutes = Math.round(options.hours * 60)\n for (let minute = 1; minute <= minutes; minute++) {\n weather.advance(SECONDS_PER_MINUTE / timeScale)\n if (minute % sampleMinutes === 0) record(minute)\n }\n return {\n seed: options.seed ?? 1,\n climate: options.climate ?? 'temperate',\n start: options.start ?? weather.registry.climate(options.climate ?? 'temperate')!.start,\n hours: options.hours,\n sampleMinutes,\n transitions,\n strikes,\n samples,\n }\n}\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 readonly sources: readonly string[]\n}\n\nexport type SoundBank = {\n readonly id: string\n readonly sounds?: readonly SoundRecipe[]\n readonly loops?: readonly LoopRecipe[]\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}\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","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","[\n {\n \"id\": \"game\",\n \"master\": 0.5,\n \"noise\": { \"seconds\": 1.5, \"create\": \"lazy\" },\n \"sources\": [\"jogo:L62077-62081 master 0.5 to the output\", \"jogo:L62082-62088 noise 1.5 s made by the first sound that needs it\"]\n },\n {\n \"id\": \"art_scene\",\n \"master\": 0.85,\n \"compressor\": { \"threshold\": -12, \"ratio\": 5 },\n \"reverb\": { \"seconds\": 2.2, \"decay\": 3.4, \"wet\": 0.4 },\n \"noise\": { \"seconds\": 2, \"create\": \"eager\" },\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","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) → 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 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); `mix: 'game'` reverts. */\nexport const DEFAULT_MIX = 'art_scene'\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","import type { LoopRecipe, SoundBank, SoundRecipe } from './recipe'\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>): void\n remove(id: string): void\n sound(id: string): SoundRecipe | undefined\n loop(id: string): LoopRecipe | undefined\n soundIds(): string[]\n loopIds(): 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 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 },\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 },\n remove(id) {\n sounds.delete(id)\n loops.delete(id)\n owners.delete(id)\n },\n sound: (id) => sounds.get(id),\n loop: (id) => loops.get(id),\n soundIds: () => [...sounds.keys()],\n loopIds: () => [...loops.keys()],\n bankOf: (id) => owners.get(id),\n }\n for (const bank of banks) registry.register(bank)\n return registry\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","/** `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\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 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(context.destination)\n }\n const master = context.createGain()\n master.gain.value = profile.master\n master.connect(compressor ?? context.destination)\n if (!profile.reverb) {\n return {\n master,\n disconnect: () => {\n master.disconnect()\n compressor?.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 },\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 if (context.state === 'suspended') void context.resume()\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 readonly source: AudioScheduledSourceNode\n readonly frequency?: AudioParam\n stop(): void\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 gain.connect(target.output)\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, source, ...(frequency ? { 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 gain.connect(target.output)\n source.start()\n for (const lfo of lfos) lfo.start()\n return { gain, source, ...(frequency ? { frequency } : {}), stop: stopAll([source, ...lfos]) }\n}\n","import { 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/** A continuous sound: `set` glides the volume and, for an oscillator, the frequency; `stop` tears the nodes down. */\nexport type AudioLoopHandle = {\n set(state: { readonly volume?: number; readonly frequency?: number }): 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}\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?.gain.disconnect()\n nodes?.gain.connect(host.output(loopRecipe.bus))\n },\n stop() {\n nodes?.stop()\n nodes?.gain.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 return {\n set(next) {\n if (isChain && !nodes) open()\n const context = host.ready()\n if (!context) return\n const action = state.set(next)\n if (!action) return\n nodes ??= create(context, 0)\n nodes.gain.gain.setTargetAtTime(action.volume, context.currentTime, smoothing.volume)\n if (action.frequency !== undefined && nodes.frequency) nodes.frequency.setTargetAtTime(action.frequency, context.currentTime, smoothing.frequency)\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","// 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 { 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 { createNoiseStore, noiseBuffer, prepareNoise } from './engine-noise'\nimport type { NoiseStore } from './engine-noise'\nimport type { RealizedVoice } from './nodes'\nimport { realize } from './realize'\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 /** A named stream of the engine (`streamFor(seed, name)`), so one subject never shifts another's sounds. */\n readonly channel?: string\n}\n\nexport type VoiceHandle = { readonly id: number; readonly plan: SoundPlan; stop(): void }\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}\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 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 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 dispose(): void\n}\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\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 start = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay = 0): VoiceHandle | null => {\n const audio = context as AudioContext\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: audio.currentTime + delay,\n })\n if (voiceId === undefined) return null\n voices.setLength(voiceId, plan.length + delay)\n active.set(voiceId, realized)\n return {\n id: voiceId,\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const admit = (recipe: SoundRecipe, 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 const playWith = (id: string, playOptions: PlayOptions, random: () => number, store: NoiseStore): VoiceHandle | null => {\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, playOptions.seed === undefined ? random : createRng(playOptions.seed)))\n return plan ? start(plan, store, voiceId, playOptions.delay) : 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 const planWith = (id: string, playOptions: PlayOptions, random: () => number): SoundPlan | null => {\n const recipe = registry.sound(id)\n return recipe ? planSound(recipe, inputFor(recipe, playOptions, random)) : 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 }\n\n return {\n registry,\n register: (bank) => registry.register(bank),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\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 = {}) => createLoopHandle(registry.loop(id), loopHost, loopOptions.volume),\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 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 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 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 },\n }\n}\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 })\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): LoopHandle {\n const loop = engine.loop(sound)\n return { set: (state) => loop.set({ ...(state.volume === undefined ? {} : { volume: state.volume }), ...(state.frequency === undefined ? {} : { frequency: state.frequency }) }), stop: () => loop.stop() }\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' },\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' },\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 { 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\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: 'art_scene',\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 {\n id: PROBE_ID,\n name: text.probe,\n movable: false,\n build: (THREE) => {\n const T = THREE as { Group: new () => { add(...objects: unknown[]): void; userData: Record<string, unknown> }; Mesh: new (geometry: unknown, material: unknown) => { position: { set(x: number, y: number, z: number): void } }; CylinderGeometry: new (top: number, bottom: number, height: number, segments: number) => unknown; BoxGeometry: new (x: number, y: number, z: number) => unknown; MeshStandardMaterial: new (parameters: Record<string, unknown>) => unknown }\n const group = new T.Group()\n const post = new T.Mesh(new T.CylinderGeometry(0.04, 0.05, 1.5, 10), new T.MeshStandardMaterial({ color: 0x4a4f55 }))\n post.position.set(0, 0.75, 0)\n const speaker = new T.Mesh(new T.BoxGeometry(0.32, 0.4, 0.26), new T.MeshStandardMaterial({ color: 0x1d2024 }))\n speaker.position.set(0, 1.5, 0)\n group.add(post, speaker)\n group.userData[PROBE_ID] = true\n return group\n },\n spec: { parts: [{ id: 'post', material: 'steel', shape: { kind: 'box', size: [0.12, 1.7, 0.3] }, position: [0, 0.85, 0], mass: 25, hp: 400 }] },\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: [{ 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 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","// Rain, wind and thunder as recipes of @adatechnology/game-audio. The loops are the teams' (the art scene's `initAudio`, cena L1314-L1315, and the game's\n// `chuva` loop, jogo L62116); the thunder is the game's `boom` (jogo L68278, a sine from 70 to 28 Hz) with a low rumble under it, the kit's choice.\nimport { sceneNoise, sceneTone } from '@adatechnology/game-audio'\nimport type { LoopRecipe, SoundBank, SoundRecipe } from '@adatechnology/game-audio'\n\n/** Rain of the art scene: noise through a highpass at 600 Hz and a lowpass at 6000 Hz (cena L1314), opened at its volume. */\nexport const RAIN_LOOP: LoopRecipe = {\n id: 'rain_loop',\n bus: 'weather',\n order: 'chain_loop',\n source: { kind: 'noise', loop: true },\n filters: {\n mode: 'serial',\n bank: [\n { type: 'highpass', frequency: { set: 600 } },\n { type: 'lowpass', frequency: { set: 6000 } },\n ],\n },\n sources: ['cena:L1314'],\n}\n\n/** Wind of the art scene: noise through a lowpass at 320 Hz whose gain swings 0.035 at 0.07 Hz (cena L1315). */\nexport const WIND_LOOP: LoopRecipe = {\n id: 'wind_loop',\n bus: 'weather',\n order: 'chain_loop',\n source: { kind: 'noise', loop: true },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 320 } }] },\n modulators: [{ target: 'gain', rate: 0.07, depth: 0.035 }],\n sources: ['cena:L1315'],\n}\n\n/** Rain of the game: noise through a highpass at 2500 Hz, created when the volume first passes 0.002 (jogo L62116 `chuva`). */\nexport const RAIN_HISS_GAME: LoopRecipe = {\n id: 'rain_hiss_game',\n bus: 'weather',\n order: 'game_loop',\n source: { kind: 'noise', loop: true },\n filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 2500 } }] },\n sources: ['jogo:L62116 chuva'],\n}\n\n/**\n * Thunder. The thump is the game's boom (a sine from 70 to 28 Hz over 1.2 s); the rumble is a lowpassed noise that slides from 260 to 50 Hz over 3.2 s\n * with a reverb send, the kit's choice (no team has a thunder). It carries much farther than a blast: `k` is 0.00001, so a strike 1 km away is still at\n * 0.13 and one 4 km away (the farthest the weather places) at 0.009.\n */\nexport const THUNDER: SoundRecipe = {\n id: 'thunder',\n bus: 'weather',\n pan: true,\n layers: [sceneTone({ f: 70, f2: 28, d: 1.2, vol: 1 }), sceneNoise({ f: 260, f2: 50, d: 3.2, vol: 0.9, wet: 0.8 })],\n falloff: { model: 'inverse_square', k: 0.00001, scale: 1.4 },\n sources: ['jogo:L68278-68285 boom', 'sdk: rumble and falloff'],\n}\n\nexport const WEATHER_BANK: SoundBank = { id: 'weather', sounds: [THUNDER], loops: [RAIN_LOOP, WIND_LOOP, RAIN_HISS_GAME] }\nexport const WEATHER_SOUNDS: readonly SoundRecipe[] = WEATHER_BANK.sounds ?? []\nexport const WEATHER_LOOPS: readonly LoopRecipe[] = WEATHER_BANK.loops ?? []\n","import type { AudioSink, LoopHandle, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { Strike, WeatherSample } from '../types'\nimport { WEATHER_BANK } from './recipes'\n\nexport type WeatherSoundStyle = 'art_scene' | 'game'\n\nexport type WeatherSoundOptions = {\n /** Which team's rain: `art_scene` (default, the kit mix) or `game` (a highpass hiss). The wind and the thunder are the same. */\n readonly style?: WeatherSoundStyle\n /**\n * Level of the rain loop. It is `light` at `lightAt` mm/h (the game's rain, 0.035) and `heavy` from `heavyAt` mm/h (the art scene's, 0.06), a straight\n * line between, and 0 when it does not rain.\n */\n readonly rain?: { readonly light?: number; readonly heavy?: number; readonly lightAt?: number; readonly heavyAt?: number }\n /** Level of the wind loop: `base` (the art scene's 0.05) at `referenceSpeed` m/s, in proportion to the speed, at most `max`. */\n readonly wind?: { readonly base?: number; readonly referenceSpeed?: number; readonly max?: number }\n /** Where the listener is, to place the thunder around it (default the origin). */\n readonly listener?: () => Vec3\n /** Level of the thunder (default 1). */\n readonly thunderVolume?: number\n /** `false` keeps the sink's bank as it is (the host registered `WEATHER_BANK` itself). */\n readonly register?: boolean\n}\n\nexport const DEFAULT_RAIN_SOUND = { light: 0.035, heavy: 0.06, lightAt: 2.5, heavyAt: 15 } as const\n/** The art scene opens its wind at 0.05 with the breeze of its day (3.8 m/s, the `clear` state's wind): the level follows the speed from there. */\nexport const DEFAULT_WIND_SOUND = { base: 0.05, referenceSpeed: 3.8, max: 0.12 } as const\n\n/** The level of the rain loop for `rain` mm/h. */\nexport function rainVolume(rain: number, options: WeatherSoundOptions['rain'] = {}): number {\n if (!(rain > 0)) return 0\n const { light, heavy, lightAt, heavyAt } = { ...DEFAULT_RAIN_SOUND, ...options }\n if (heavyAt <= lightAt) return rain >= heavyAt ? heavy : light\n const t = Math.min(1, Math.max(0, (rain - lightAt) / (heavyAt - lightAt)))\n return light + (heavy - light) * t\n}\n\n/** The level of the wind loop for a wind of `speed` m/s. */\nexport function windVolume(speed: number, options: WeatherSoundOptions['wind'] = {}): number {\n const { base, referenceSpeed, max } = { ...DEFAULT_WIND_SOUND, ...options }\n return Math.min(max, (base * Math.max(0, speed)) / referenceSpeed)\n}\n\n/** Where a strike is, around `origin`: `bearing` is degrees clockwise from north, and north is -z. */\nexport function strikePosition(strike: Pick<Strike, 'distance' | 'bearing'>, origin: Vec3 = [0, 0, 0]): Vec3 {\n const angle = (strike.bearing * Math.PI) / 180\n return [origin[0] + Math.sin(angle) * strike.distance, origin[1], origin[2] - Math.cos(angle) * strike.distance]\n}\n\nexport type WeatherSound = {\n /** Sets the level of the loops from the weather of now (opens a loop the first time it is above 0). */\n update(sample: Pick<WeatherSample, 'rain' | 'windSpeed'>): void\n /** Plays a clap of thunder at the strike (call it when the thunder arrives: the weather delays it by `distance / 343`). */\n thunder(strike: Pick<Strike, 'distance' | 'bearing'>): void\n dispose(): void\n}\n\n/** The sound of the weather on the host's `audio`: the rain loop, the wind loop and the thunder. Without a sink (or one without loops) it does nothing. */\nexport function createWeatherSound(sink: AudioSink | undefined, options: WeatherSoundOptions = {}): WeatherSound {\n if (sink && options.register !== false) sink.register?.(WEATHER_BANK)\n const rainSound = options.style === 'game' ? 'rain_hiss_game' : 'rain_loop'\n const loops = new Map<string, LoopHandle>()\n const set = (id: string, volume: number): void => {\n let loop = loops.get(id)\n if (!loop) {\n if (!(volume > 0) || !sink?.loop) return\n loop = sink.loop(id)\n loops.set(id, loop)\n }\n loop.set({ volume })\n }\n return {\n update(sample) {\n set(rainSound, rainVolume(sample.rain, options.rain))\n set('wind_loop', windVolume(sample.windSpeed, options.wind))\n },\n thunder(strike) {\n sink?.play({ sound: 'thunder', position: strikePosition(strike, options.listener?.()), ...(options.thunderVolume === undefined ? {} : { volume: options.thunderVolume }) })\n },\n dispose() {\n for (const loop of loops.values()) loop.stop()\n loops.clear()\n },\n }\n}\n","import type { AudioSink, EnvironmentBus, EnvironmentState } from '@adatechnology/game-contracts'\n\nimport { createWeatherSound } from './audio/sound'\nimport type { WeatherSound, WeatherSoundOptions } from './audio/sound'\nimport type { Strike, WeatherSample } from './types'\nimport type { Weather } from './weather'\n\n/** The shape of the film of `game-fluids-three` (`FilmBridge`) this needs: no import, so the weather does not depend on it. */\nexport type FilmTarget = {\n setWeather(weather: { rain: number; drying?: number }): void\n wash?(maxDryness?: number): number\n}\n/** The interactables world (`game-interactables`): its water takes the rain, the soft volumes the wind. */\nexport type InteractablesTarget = { water: { setRain(mmPerHour: number): void }; setWind(x: number, z: number): void }\n/** The vegetation renderer (`game-vegetation`). `direction` is normalised by the renderer, `strength` and `gust` are 0..1. */\nexport type VegetationTarget = { setWind(wind: { direction?: [number, number]; strength?: number; gust?: number }): void }\n/** The effects world (`game-vfx`'s `VfxWorld`): smoke and dust drift with its wind. */\nexport type VfxTarget = { setWind(wind: readonly [number, number, number]): void }\n\nexport type WeatherTargets = {\n readonly film?: FilmTarget\n readonly interactables?: InteractablesTarget\n readonly vegetation?: VegetationTarget\n readonly vfx?: VfxTarget\n /** The host's environment bus (`ModuleHost.environment`). */\n readonly environment?: Pick<EnvironmentBus, 'set'>\n /** The host's sound (`ModuleHost.audio`): the rain and wind loops, and the thunder. */\n readonly audio?: AudioSink\n}\n\n/** The rules the bridges apply; every number can be replaced. */\nexport type WeatherBridgeRules = {\n /** Rain in mm/h at which the film counts as fully rained on (it stops drying, spreads 1.5 times faster). Default 2.5, the light rain. */\n readonly filmRainFullAt?: number\n /** Rain in mm/h from which the rain washes the fresh stain (Workshop and visor: heavy rain and stronger). Default 15; light rain does not wash. */\n readonly washFrom?: number\n /** Stains less dry than this are washed (visor L13494). Default 0.5. */\n readonly washBelow?: number\n /** Seconds between two washes while it pours. Default 1. */\n readonly washEvery?: number\n /** Wind speed in m/s that is 1 for the vegetation (`strength = min(1, speed / this)`). Default 20. */\n readonly windFull?: number\n}\n\nexport type WeatherBridgeOptions = WeatherBridgeRules & {\n readonly sound?: WeatherSoundOptions | false\n}\n\nexport const DEFAULT_BRIDGE_RULES = { filmRainFullAt: 2.5, washFrom: 15, washBelow: 0.5, washEvery: 1, windFull: 20 } as const\n\n/** The weather as the environment bus holds it. */\nexport function environmentOf(sample: WeatherSample): Partial<EnvironmentState> {\n return {\n rain: sample.rain,\n windX: sample.windX,\n windZ: sample.windZ,\n windSpeed: sample.windSpeed,\n gust: sample.gust,\n fogFar: sample.fogFar,\n visibility: sample.effects.visibility,\n nightFactor: sample.nightFactor,\n temperatureC: sample.temperatureC,\n wetness: sample.groundWetness,\n }\n}\n\nexport type WeatherBridges = {\n /** Follows this weather (the one before is let go) and pushes its values at once. */\n bind(weather: Weather): void\n /** Pushes the weather of now to every target; call it each frame after `weather.advance(dt)`. */\n update(dt: number): void\n dispose(): void\n}\n\n/**\n * Pushes one weather to the packages that react to it, each through a small interface of its own, so the weather depends on none of them and every\n * target is optional:\n * - fluids film: `setWeather({ rain: min(1, rain / filmRainFullAt), drying: dryingScale })`, and `wash()` every `washEvery` seconds while the rain is at\n * `washFrom` or stronger (light rain stops the drying and does not wash);\n * - interactables: `water.setRain(mm/h)` and `setWind(x, z)`;\n * - vegetation: `setWind({ direction: [x, z], strength: min(1, speed / windFull), gust: min(1, gust / windFull) })`;\n * - vfx: `setWind([x, 0, z])`;\n * - the environment bus: every value of `environmentOf`;\n * - sound: the rain and wind loops follow the weather, and each thunder that arrives plays at its bearing.\n */\nexport function createWeatherBridges(targets: WeatherTargets, options: WeatherBridgeOptions = {}): WeatherBridges {\n const rules = { ...DEFAULT_BRIDGE_RULES, ...options }\n const sound: WeatherSound | undefined = options.sound === false || !targets.audio ? undefined : createWeatherSound(targets.audio, options.sound ?? {})\n let weather: Weather | undefined\n let offThunder: (() => void) | undefined\n let sinceWash = 0\n let last: { rain?: number; windX?: number; windZ?: number; filmRain?: number; drying?: number } = {}\n\n const push = (): void => {\n if (!weather) return\n const sample = weather.sample()\n const { film, interactables, vegetation, vfx, environment } = targets\n environment?.set(environmentOf(sample))\n if (film) {\n const rain = Math.min(1, Math.max(0, sample.rain / rules.filmRainFullAt))\n const drying = sample.effects.dryingScale\n if (rain !== last.filmRain || drying !== last.drying) film.setWeather({ rain, drying })\n last.filmRain = rain\n last.drying = drying\n }\n if (interactables && sample.rain !== last.rain) interactables.water.setRain(sample.rain)\n const windChanged = sample.windX !== last.windX || sample.windZ !== last.windZ\n if (windChanged) {\n interactables?.setWind(sample.windX, sample.windZ)\n vfx?.setWind([sample.windX, 0, sample.windZ])\n if (vegetation) {\n const wind = { strength: Math.min(1, sample.windSpeed / rules.windFull), gust: Math.min(1, sample.gust / rules.windFull) }\n vegetation.setWind(sample.windSpeed > 1e-6 ? { direction: [sample.windX, sample.windZ], ...wind } : wind)\n }\n }\n last = { ...last, rain: sample.rain, windX: sample.windX, windZ: sample.windZ }\n sound?.update(sample)\n }\n\n const onThunder = (strike: Strike): void => sound?.thunder(strike)\n\n return {\n bind(next) {\n offThunder?.()\n weather = next\n offThunder = next.on('thunder', onThunder)\n last = {}\n sinceWash = 0\n push()\n },\n update(dt) {\n push()\n if (!weather || !targets.film?.wash) return\n if (weather.sample().rain < rules.washFrom) {\n sinceWash = 0\n return\n }\n sinceWash += dt\n if (sinceWash >= rules.washEvery) {\n sinceWash = 0\n targets.film.wash(rules.washBelow)\n }\n },\n dispose() {\n offThunder?.()\n offThunder = undefined\n weather = undefined\n sound?.dispose()\n },\n }\n}\n","export type WeatherBenchText = {\n readonly group: string\n readonly name: string\n readonly controls: Readonly<Record<'state' | 'transition' | 'time_of_day' | 'auto_schedule' | 'seed', string>>\n readonly hints: Readonly<Record<'transition' | 'time_of_day' | 'auto_schedule' | 'seed', string>>\n readonly options: Readonly<Record<'instant' | 'ten_seconds', string>>\n readonly layers: Readonly<Record<'environment' | 'fog', string>>\n readonly metrics: Readonly<Record<'state' | 'hour' | 'rain' | 'visibility' | 'sight' | 'hearing' | 'wind' | 'heat_index' | 'wetness' | 'strikes' | 'blend' | 'temperature', string>>\n readonly scenarios: Readonly<Record<'storm' | 'blend' | 'determinism' | 'dry_ground', string>>\n /** Names of the states and climates by id; the bench falls back to the id. */\n readonly states: Readonly<Record<string, string>>\n}\n\nconst EN: WeatherBenchText = {\n group: 'Weather',\n name: 'Weather area',\n controls: { state: 'Weather', transition: 'Transition', time_of_day: 'Time of day', auto_schedule: 'Automatic schedule', seed: 'Seed' },\n hints: {\n transition: 'How long the change to the chosen weather takes, in real seconds.',\n time_of_day: 'Hour of the day (the world restarts the clock there and keeps the weather).',\n auto_schedule: 'On: the climate changes the weather by itself and the clock runs 600 times faster than real time. Off: the weather stays until you change it.',\n seed: 'The same seed gives the same schedule and the same lightning.',\n },\n options: { instant: 'At once', ten_seconds: '10 seconds' },\n layers: { environment: 'Write host environment', fog: 'Fog in the scene' },\n metrics: {\n state: 'Weather',\n hour: 'Hour',\n rain: 'Rain',\n visibility: 'Visibility',\n sight: 'Sight scale',\n hearing: 'Hearing scale',\n wind: 'Wind',\n heat_index: 'Heat index',\n wetness: 'Ground wetness',\n strikes: 'Lightning strikes',\n blend: 'Blend',\n temperature: 'Temperature',\n },\n scenarios: {\n storm: 'A storm sees less and is heard less than a clear day, and strikes lightning',\n blend: 'A change blends over its time and settles in the new weather',\n determinism: 'The same seed gives the same day, another seed another one',\n dry_ground: 'Rain wets the ground and it dries after the rain stops',\n },\n states: {\n clear: 'Clear',\n overcast: 'Overcast',\n light_rain: 'Light rain',\n heavy_rain: 'Heavy rain',\n storm: 'Storm',\n fog: 'Fog',\n windy: 'Windy',\n cyclone: 'Cyclone',\n typhoon: 'Typhoon',\n extreme_heat: 'Extreme heat',\n },\n}\n\nconst PT_BR: WeatherBenchText = {\n group: 'Clima',\n name: 'Área de clima',\n controls: { state: 'Clima', transition: 'Transição', time_of_day: 'Hora do dia', auto_schedule: 'Sorteio automático', seed: 'Semente' },\n hints: {\n transition: 'Quanto demora a mudança para o clima escolhido, em segundos reais.',\n time_of_day: 'Hora do dia (o mundo reinicia o relógio nela e mantém o clima).',\n auto_schedule: 'Ligado: o clima do lugar muda sozinho e o relógio corre 600 vezes mais rápido que o real. Desligado: o clima fica até você trocar.',\n seed: 'A mesma semente dá o mesmo sorteio e os mesmos raios.',\n },\n options: { instant: 'De uma vez', ten_seconds: '10 segundos' },\n layers: { environment: 'Escrever no ambiente do host', fog: 'Névoa na cena' },\n metrics: {\n state: 'Clima',\n hour: 'Hora',\n rain: 'Chuva',\n visibility: 'Visibilidade',\n sight: 'Escala de visão',\n hearing: 'Escala de audição',\n wind: 'Vento',\n heat_index: 'Índice de calor',\n wetness: 'Chão molhado',\n strikes: 'Raios',\n blend: 'Mistura',\n temperature: 'Temperatura',\n },\n scenarios: {\n storm: 'Tempestade enxerga e é ouvida menos que um dia limpo, e solta raios',\n blend: 'Uma mudança se mistura no tempo dela e assenta no clima novo',\n determinism: 'A mesma semente dá o mesmo dia, outra semente dá outro',\n dry_ground: 'A chuva molha o chão e ele seca depois que a chuva para',\n },\n states: {\n clear: 'Limpo',\n overcast: 'Nublado',\n light_rain: 'Chuva fraca',\n heavy_rain: 'Chuva forte',\n storm: 'Tempestade',\n fog: 'Neblina',\n windy: 'Ventania',\n cyclone: 'Ciclone',\n typhoon: 'Tufão',\n extreme_heat: 'Calor extremo',\n },\n}\n\nexport const weatherBenchTextOf = (locale: string): WeatherBenchText => (locale === 'en' ? EN : PT_BR)\n","import type { BenchChange, ModuleControl, ModuleHost, ModuleLayer, ModuleMetric, ModuleScenario, TestableModule } from '@adatechnology/game-contracts'\n\nimport { createWeatherBridges, environmentOf } from '../bridges'\nimport type { WeatherBridges, WeatherTargets } from '../bridges'\nimport type { WeatherSoundOptions } from '../audio/sound'\nimport { createWeather } from '../weather'\nimport type { Weather, WeatherOptions } from '../weather'\nimport type { Strike, WeatherSample } from '../types'\nimport { weatherBenchTextOf } from './locale'\nimport type { WeatherBenchText } from './locale'\n\n/** What a renderer of the weather (game-weather-three) gives the bench: its layers, a step per frame and the switch of each layer. */\nexport type WeatherVisual = {\n update(dt: number): void\n setLayer(id: string, on: boolean): void\n dispose(): void\n}\n\n/** The bench hands a visual the weather it shows (always the live one, even after the bench restarts it) and what the room lends. */\nexport type WeatherVisualContext = { readonly host: ModuleHost; readonly locale: string; readonly weather: { sample(): WeatherSample } }\n\n/** The bench declares its layers before the room lends anything, so the factory tells them first (`fog` is the bench's own layer and reaches the visual through `setLayer` too). */\nexport type WeatherVisualFactory = {\n layers(locale: string): readonly ModuleLayer[]\n create(context: WeatherVisualContext): WeatherVisual\n}\n\nexport type WeatherTestModuleOptions = WeatherOptions & {\n locale?: string\n /** Text of a state id in the game's words; without it the bench uses its own names, then the id. */\n translate?: (key: string, locale: string) => string | undefined\n /** The weather to test (default a new one built from the other options). */\n weather?: Weather\n /** Whether the scene fog follows the weather at first (default true; the layer can be switched either way). A room that is not about weather starts it off. */\n fog?: boolean\n /** The packages the weather drives besides the host's environment bus and sound (fluids film, interactables, vegetation, vfx), from the example. */\n targets?: Omit<WeatherTargets, 'environment' | 'audio'>\n /** The rain, wind and thunder on the host's `audio`; `false` keeps the area silent. */\n sound?: WeatherSoundOptions | false\n /** The picture of the weather (rain, fog, sky, lightning, headlights, haze), from `@adatechnology/game-weather-three`. With it the bench leaves the scene fog to the visual. */\n visual?: WeatherVisualFactory\n}\n\n/** What the scenarios use of the context the test room passes. */\nexport interface WeatherScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type WeatherTestModule = TestableModule<WeatherScenarioLike> & {\n /** The weather in use (replaced when the bench changes the seed or the hour). */\n readonly weather: Weather\n}\n\nconst FAST_SCALE = 600\nconst NORMAL_SCALE = 72\nconst BLEND_SECONDS = 10\nconst HOURS_PER_DAY = 24\nconst FOG_NEAR = 1\n\ntype FogLike = new (color: number, near: number, far: number) => { far: number }\ntype SceneLike = { fog?: unknown }\ntype ThreeLike = { Fog?: FogLike }\n\n/**\n * The weather area of a test room, written against the generic contracts only: it drives a `createWeather` world, writes the result into the host's\n * environment bus (`host.environment`) every frame and shows the numbers a game reads from it. It also sets the scene fog from the weather's render fog.\n * Pure: no three.js beyond the host's own `Fog`, and the sky, rain, lightning and sound wait for the packages that draw and play them.\n */\nexport function createWeatherTestModule(options: WeatherTestModuleOptions = {}): WeatherTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text: WeatherBenchText = weatherBenchTextOf(locale)\n const { locale: _locale, translate, weather: given, fog: _fog, targets: _targets, sound: _sound, visual: _visual, ...weatherOptions } = options\n void _locale\n void _fog\n void _targets\n void _sound\n void _visual\n const state = {\n seed: options.seed ?? 1,\n hour: options.startHour ?? 8,\n transition: 0,\n auto: options.autoSchedule ?? false,\n environment: true,\n fog: options.fog ?? true,\n }\n let host: ModuleHost | null = null\n let strikes = 0\n let offStrike: (() => void) | undefined\n let bridges: WeatherBridges | undefined\n let visual: WeatherVisual | undefined\n let weather: Weather = given ?? createWeather({ ...weatherOptions, autoSchedule: state.auto, ...(state.auto ? { timeScale: FAST_SCALE } : {}) })\n\n const watch = (): void => {\n offStrike?.()\n offStrike = weather.on('strike', (_strike: Strike) => void (strikes += 1))\n }\n watch()\n\n const nameOf = (id: string): string => translate?.(`weather.${id}`, locale) ?? text.states[id] ?? id\n\n // the world restarts with the new seed or hour and keeps the weather it was in\n const rebuild = (): void => {\n const current = weather.state()\n weather = createWeather({ ...weatherOptions, seed: state.seed, start: current, startHour: state.hour, autoSchedule: state.auto, timeScale: state.auto ? FAST_SCALE : NORMAL_SCALE })\n strikes = 0\n watch()\n bridges?.bind(weather)\n }\n\n const applyFog = (far: number): void => {\n const scene = host?.scene as SceneLike | undefined\n const Fog = (host?.THREE as ThreeLike | undefined)?.Fog\n if (!scene || typeof Fog !== 'function') return\n const fog = scene.fog as { far: number } | undefined | null\n if (fog && typeof fog.far === 'number') fog.far = far\n else scene.fog = new Fog(0xa8b4c0, FOG_NEAR, far)\n }\n\n const publish = (): void => {\n const sample = weather.sample()\n if (state.environment) host?.environment?.set(environmentOf(sample))\n if (state.fog && !visual) applyFog(sample.fogFar)\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'layer') {\n if (change.id === 'environment' || change.id === 'fog') state[change.id] = change.on\n visual?.setLayer(change.id, change.on)\n return\n }\n if (change.kind === 'action') return\n const { id, value } = change\n if (id === 'state' && typeof value === 'string') weather.force(value, state.transition)\n else if (id === 'transition' && typeof value === 'string') state.transition = value === 'instant' ? 0 : BLEND_SECONDS\n else if (id === 'time_of_day' && typeof value === 'number') {\n state.hour = value\n rebuild()\n } else if (id === 'auto_schedule' && typeof value === 'boolean') {\n state.auto = value\n weather.setAutoSchedule(value)\n weather.setTimeScale(value ? FAST_SCALE : NORMAL_SCALE)\n } else if (id === 'seed' && typeof value === 'number') {\n state.seed = value\n rebuild()\n }\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'choice', id: 'state', name: text.controls.state, options: weather.registry.stateIds().map((id) => ({ id, name: nameOf(id) })), default: weather.state() },\n {\n kind: 'choice',\n id: 'transition',\n name: text.controls.transition,\n hint: text.hints.transition,\n options: [\n { id: 'instant', name: text.options.instant },\n { id: 'ten_seconds', name: text.options.ten_seconds },\n ],\n default: 'instant',\n },\n { kind: 'number', id: 'time_of_day', name: text.controls.time_of_day, hint: text.hints.time_of_day, unit: 'h', min: 0, max: HOURS_PER_DAY - 1, step: 1, default: state.hour },\n { kind: 'boolean', id: 'auto_schedule', name: text.controls.auto_schedule, hint: text.hints.auto_schedule, default: state.auto },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: state.seed },\n ]\n\n const layers = (): ModuleLayer[] => [\n { id: 'environment', name: text.layers.environment },\n { id: 'fog', name: text.layers.fog, default: state.fog },\n ...(options.visual?.layers(locale) ?? []),\n ]\n\n const metrics = (): ModuleMetric[] => [\n { id: 'current_state', name: text.metrics.state, read: () => nameOf(weather.state()) },\n { id: 'hour', name: text.metrics.hour, unit: 'h', digits: 1, read: () => weather.sample().hour },\n { id: 'blend', name: text.metrics.blend, digits: 2, read: () => weather.sample().blend },\n { id: 'rain', name: text.metrics.rain, unit: 'mm/h', digits: 1, read: () => weather.sample().rain },\n { id: 'visibility', name: text.metrics.visibility, unit: 'm', digits: 0, read: () => weather.sample().effects.visibility },\n { id: 'sight', name: text.metrics.sight, digits: 2, read: () => weather.sample().effects.sightScale },\n { id: 'hearing', name: text.metrics.hearing, digits: 2, read: () => weather.sample().effects.hearingScale },\n { id: 'wind', name: text.metrics.wind, unit: 'm/s', digits: 1, read: () => weather.sample().windSpeed },\n { id: 'temperature', name: text.metrics.temperature, unit: '°C', digits: 1, read: () => weather.sample().temperatureC },\n { id: 'heat_index', name: text.metrics.heat_index, unit: '°C', digits: 1, read: () => weather.sample().effects.heatIndexC },\n { id: 'wetness', name: text.metrics.wetness, digits: 2, read: () => weather.sample().groundWetness },\n { id: 'strikes', name: text.metrics.strikes, digits: 0, read: () => strikes },\n ]\n\n // each scenario runs its own worlds, so the bench's live one is not touched\n const fresh = (extra: WeatherOptions = {}): Weather => createWeather({ ...weatherOptions, autoSchedule: false, ...extra })\n const run = (world: Weather, seconds: number): void => {\n for (let elapsed = 0; elapsed < seconds; elapsed += 0.5) world.advance(0.5)\n }\n\n const scenarios = (): Array<ModuleScenario<WeatherScenarioLike>> => [\n {\n id: 'storm',\n name: text.scenarios.storm,\n run: ({ expect }) => {\n const clear = fresh({ seed: 3, start: 'clear' })\n const storm = fresh({ seed: 3, start: 'storm' })\n let hits = 0\n storm.on('strike', () => void (hits += 1))\n run(storm, 120)\n const calm = clear.sample().effects\n const rough = storm.sample().effects\n expect(rough.visibility < calm.visibility, 'a storm sees less far', { storm: rough.visibility, clear: calm.visibility })\n expect(rough.hearingScale < calm.hearingScale, 'rain masks sound', { storm: rough.hearingScale, clear: calm.hearingScale })\n expect(hits > 0, 'a storm strikes lightning', { strikes: hits })\n },\n },\n {\n id: 'blend',\n name: text.scenarios.blend,\n run: ({ expect }) => {\n const world = fresh({ seed: 3, start: 'clear' })\n world.force('heavy_rain', 10)\n run(world, 5)\n const middle = world.sample()\n expect(middle.blend > 0 && middle.blend < 1, 'halfway through the change it is still blending', { blend: middle.blend })\n expect(middle.rain > 0 && middle.rain < 15, 'the rain is between the two weathers', { rain: middle.rain })\n run(world, 6)\n expect(world.sample().blend === 1 && world.sample().state === 'heavy_rain', 'after its time it has settled', { blend: world.sample().blend })\n },\n },\n {\n id: 'determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const day = (seed: number): string => JSON.stringify(createWeather({ ...weatherOptions, seed }).timeline(48).samples)\n expect(day(5) === day(5), 'the same seed gives the same two days')\n expect(day(5) !== day(6), 'another seed gives another one')\n },\n },\n {\n id: 'dry_ground',\n name: text.scenarios.dry_ground,\n run: ({ expect }) => {\n const world = fresh({ seed: 3, start: 'heavy_rain' })\n run(world, 60)\n const wet = world.sample().groundWetness\n expect(wet > 0.3, 'rain wets the ground', { wetness: wet })\n world.force('clear', 0)\n run(world, 600)\n expect(world.sample().groundWetness < wet, 'it dries after the rain stops', { wet, after: world.sample().groundWetness })\n },\n },\n ]\n\n const module: WeatherTestModule = {\n id: 'weather_area',\n name: text.name,\n group: text.group,\n get weather() {\n return weather\n },\n items: () => [],\n controls: () => controls(),\n layers: () => layers(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n attach(lent) {\n host = lent\n const off = lent.bench?.onChange(onChange)\n bridges = createWeatherBridges({ ...options.targets, ...(lent.audio ? { audio: lent.audio } : {}) }, { sound: options.sound ?? {} })\n bridges.bind(weather)\n visual = options.visual?.create({ host: lent, locale, weather: { sample: () => weather.sample() } })\n if (visual && !state.fog) visual.setLayer('fog', false)\n publish()\n const offFrame = lent.onFrame((dt) => {\n weather.advance(dt)\n publish()\n bridges?.update(dt)\n visual?.update(dt)\n })\n return () => {\n visual?.dispose()\n visual = undefined\n off?.()\n offFrame()\n bridges?.dispose()\n bridges = 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;;;ACEO,MAAM,mBAA6C;AAAA,IACxD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEO,WAAS,SAAS,OAAkC;AACzD,UAAM,SAAiC,CAAC;AACxC,eAAW,OAAO,iBAAkB,QAAO,GAAG,IAAI,MAAM,GAAG;AAC3D,WAAO;AAAA,EACT;AAGO,WAAS,YAAY,MAAmB,IAAiB,UAA+B;AAC7F,UAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,QAAQ,CAAC;AAChD,UAAM,UAAkC,CAAC;AACzC,eAAW,OAAO,iBAAkB,SAAQ,GAAG,IAAI,KAAK,GAAG,KAAK,GAAG,GAAG,IAAI,KAAK,GAAG,KAAK;AACvF,WAAO;AAAA,EACT;;;ACpCO,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAEzB,MAAM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,OAAO,EAAE,EAAE,CAAC;AACnG,YAAI,UAAU,CAAC,MAAM,IAAK,QAAO,SAAS,OAAO,KAAK;AACtD,gBAAQ;AACR,cAAM,WAAW,KAAK,QAAQ,CAAC,OAAO;AACpC,kBAAQ,QAAQ,EAAE;AAClB,kBAAQ;AACR,mBAAS,OAAO,EAAE;AAClB,kBAAQ,OAAO,EAAE;AAAA,QACnB,CAAC;AACD,eAAO,MAAM;AACX,kBAAQ,QAAQ;AAChB,mBAAS;AACT,gBAAM;AACN,mBAAS;AACT,mBAAS,QAAQ;AACjB,oBAAU;AACV,iBAAO;AAAA,QACT;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts","../src/blend.ts","../src/daylight.ts","../src/heat.ts","../src/effects.ts","../src/rng.ts","../src/lightning.ts","../src/data/climates.json","../src/data/states.json","../src/registry.ts","../src/scheduler.ts","../src/wetness.ts","../src/weather.ts","../../game-audio/src/rng.ts","../../game-audio/src/recipe.ts","../../game-audio/src/falloff.ts","../../game-audio/src/listener.ts","../../game-audio/src/data/voice-groups.json","../../game-audio/src/voices.ts","../../game-audio/src/plan.ts","../../game-audio/src/loops.ts","../../game-audio/src/data/mix-profiles.json","../../game-audio/src/mix.ts","../../game-audio/src/bank.ts","../../game-audio/src/data/game-sfx.json","../../game-audio/src/recipes/noise-class.ts","../../game-audio/src/recipes/scene.ts","../../game-audio/src/library/crowd_rumble.json","../../game-audio/src/library/engine_saw.json","../../game-audio/src/library/horn.json","../../game-audio/src/library/radio_static.json","../../game-audio/src/library/rotor_blades.json","../../game-audio/src/library/siren.json","../../game-audio/src/library/index.ts","../../game-audio/src/webaudio/noise.ts","../../game-audio/src/webaudio/chain.ts","../../game-audio/src/webaudio/context.ts","../../game-audio/src/webaudio/nodes.ts","../../game-audio/src/webaudio/realize-loop.ts","../../game-audio/src/webaudio/engine-loop.ts","../../game-audio/src/webaudio/engine-noise.ts","../../game-audio/src/webaudio/realize-game.ts","../../game-audio/src/webaudio/realize-layered.ts","../../game-audio/src/webaudio/realize-weapon.ts","../../game-audio/src/webaudio/realize.ts","../../game-audio/src/webaudio/engine.ts","../../game-audio/src/webaudio/sink.ts","../../game-audio/src/bench/locale.ts","../../game-audio/src/bench/module.ts","../src/audio/recipes.ts","../src/audio/sound.ts","../src/bridges.ts","../src/bench/locale.ts","../src/bench/module.ts"],"sourcesContent":["/**\n * @adatechnology/game-weather: pure, seeded weather. States (clear to typhoon) with the numbers of the teams' pages, climates that move between\n * them in game time (2 to 6 hours each, fronts from the west), lightning with the thunder delay, ground wetness, what the weather means for\n * sight, hearing and footsteps, the heat index and the day-night formula, plus the bridges that push it to fluids, interactables, vegetation, vfx, the environment bus and the sound (rain, wind and thunder recipes of game-audio). No three.js, no game content: renderers read it.\n */\nexport { createWeather, createTimeline, DEFAULT_START_HOUR } from './weather'\nexport type { TimelineOptions, Weather, WeatherOptions, WeatherTimeline } from './weather'\nexport { CLIMATES, WEATHER_STATES, createWeatherRegistry } from './registry'\nexport type { RegistryOptions, WeatherRegistry } from './registry'\nexport { blendValues, STATE_VALUE_KEYS, valuesOf } from './blend'\nexport { createScheduler } from './scheduler'\nexport type { Scheduler } from './scheduler'\nexport { FLASH_END_SECONDS, SPEED_OF_SOUND, createLightningStream, flashIntensity, thunderDelay } from './lightning'\nexport type { LightningStream } from './lightning'\nexport { DEFAULT_DRY_OUT_SECONDS, DEFAULT_WET_RISE_SECONDS, createWetness } from './wetness'\nexport type { Wetness, WetnessOptions } from './wetness'\nexport { DRY_VISIBILITY_METERS, NIGHT_SIGHT_LOSS, deriveEffects } from './effects'\nexport type { EffectsInput } from './effects'\nexport { heatIndexC, heatStress } from './heat'\nexport { DAY_REAL_SECONDS, DEFAULT_TIME_SCALE, GAME_DAY_SECONDS, dayFractionAt, daylight } from './daylight'\nexport type { Daylight } from './daylight'\nexport { createRng, createStream, streamSeed } from './rng'\nexport type {\n Climate,\n DeepPartial,\n LightningConfig,\n StateValueKey,\n StateValues,\n Strike,\n WeatherEffects,\n WeatherEventMap,\n WeatherSample,\n WeatherState,\n} from './types'\n\nexport { createWeatherBridges, environmentOf, DEFAULT_BRIDGE_RULES } from './bridges'\nexport type { FilmTarget, InteractablesTarget, VegetationTarget, VfxTarget, WeatherBridgeOptions, WeatherBridgeRules, WeatherBridges, WeatherTargets } from './bridges'\nexport { RAIN_HISS_GAME, RAIN_LOOP, THUNDER, WEATHER_BANK, WEATHER_LOOPS, WEATHER_SOUNDS, WIND_LOOP } from './audio/recipes'\nexport { DEFAULT_RAIN_SOUND, DEFAULT_WIND_SOUND, createWeatherSound, rainVolume, strikePosition, windVolume } from './audio/sound'\nexport type { WeatherSound, WeatherSoundOptions, WeatherSoundStyle } from './audio/sound'\n\nexport { createWeatherTestModule } from './bench/module'\nexport type { WeatherScenarioLike, WeatherTestModule, WeatherTestModuleOptions, WeatherVisual, WeatherVisualContext, WeatherVisualFactory } from './bench/module'\nexport { weatherBenchTextOf } from './bench/locale'\nexport type { WeatherBenchText } from './bench/locale'\n","import type { StateValueKey, StateValues, WeatherState } from './types'\n\nexport const STATE_VALUE_KEYS: readonly StateValueKey[] = [\n 'rain',\n 'drops',\n 'sheets',\n 'windX',\n 'windZ',\n 'gust',\n 'fogFar',\n 'fogDensity',\n 'skyScale',\n 'visibility',\n 'humidity',\n 'temperatureDeltaC',\n 'wetness',\n 'hearingScale',\n 'footstepScale',\n 'dryingScale',\n 'debrisPush',\n 'haze',\n 'mistPerSecond',\n 'ashPerSecond',\n]\n\nexport function valuesOf(state: WeatherState): StateValues {\n const values: Record<string, number> = {}\n for (const key of STATE_VALUE_KEYS) values[key] = state[key]\n return values as unknown as StateValues\n}\n\n/** Every number between two states: `progress` 0 is `from`, 1 is `to`. */\nexport function blendValues(from: StateValues, to: StateValues, progress: number): StateValues {\n const amount = Math.min(1, Math.max(0, progress))\n const blended: Record<string, number> = {}\n for (const key of STATE_VALUE_KEYS) blended[key] = from[key] + (to[key] - from[key]) * amount\n return blended as unknown as StateValues\n}\n","/** A game day lasts 20 real minutes in the slice (jogo.js L69127: `dayT + dt / 1200`). */\nexport const DAY_REAL_SECONDS = 1200\nexport const GAME_DAY_SECONDS = 86400\n/** Game seconds per real second of the 20-minute day. */\nexport const DEFAULT_TIME_SCALE = GAME_DAY_SECONDS / DAY_REAL_SECONDS\n\nconst NIGHT_SPAN = 2.2\n\nconst clamp = (value: number, low: number, high: number): number => (value < low ? low : value > high ? high : value)\n\nexport type Daylight = {\n /** Sun height 0..1 (`s` of the game). */\n readonly sun: number\n /** 0 in full daylight, 1 in the darkest night. */\n readonly nightFactor: number\n}\n\n/** jogo.js L69128-L69130: `s = clamp(sin(dayT·2π − π/2)·0.5 + 0.5, 0, 1)`, `nightF = 1 − clamp(s·2.2, 0, 1)`. `dayFraction` 0 is midnight. */\nexport function daylight(dayFraction: number): Daylight {\n const sun = clamp(Math.sin(dayFraction * Math.PI * 2 - Math.PI / 2) * 0.5 + 0.5, 0, 1)\n return { sun, nightFactor: 1 - clamp(sun * NIGHT_SPAN, 0, 1) }\n}\n\n/** The fraction of the day after `gameSeconds` from `startHour`. */\nexport function dayFractionAt(startHour: number, gameSeconds: number): number {\n const fraction = (startHour / 24 + gameSeconds / GAME_DAY_SECONDS) % 1\n return fraction < 0 ? fraction + 1 : fraction\n}\n","const HEAT_STRESS_BANDS: ReadonlyArray<readonly [indexC: number, stress: number]> = [\n [27, 0],\n [32, 1 / 3],\n [41, 2 / 3],\n [54, 1],\n]\nconst NOAA_REGRESSION_FROM_F = 80\n\nconst toFahrenheit = (celsius: number): number => (celsius * 9) / 5 + 32\nconst toCelsius = (fahrenheit: number): number => ((fahrenheit - 32) * 5) / 9\n\n/**\n * NOAA heat index in °C: the Steadman estimate averaged with the temperature, and from 80 °F up the Rothfusz regression with the low-humidity and\n * high-humidity adjustments. Built from + - * / and `sqrt` only, so it is the same on every engine.\n */\nexport function heatIndexC(temperatureC: number, relativeHumidityPercent: number): number {\n const t = toFahrenheit(temperatureC)\n const r = relativeHumidityPercent\n const steadman = 0.5 * (t + 61 + (t - 68) * 1.2 + r * 0.094)\n const simple = (steadman + t) / 2\n if (simple < NOAA_REGRESSION_FROM_F) return toCelsius(simple)\n let index =\n -42.379 +\n 2.04901523 * t +\n 10.14333127 * r -\n 0.22475541 * t * r -\n 0.00683783 * t * t -\n 0.05481717 * r * r +\n 0.00122874 * t * t * r +\n 0.00085282 * t * r * r -\n 0.00000199 * t * t * r * r\n if (r < 13 && t >= 80 && t <= 112) index -= ((13 - r) / 4) * Math.sqrt((17 - Math.abs(t - 95)) / 17)\n else if (r > 85 && t >= 80 && t <= 87) index += ((r - 85) / 10) * ((87 - t) / 5)\n return toCelsius(index)\n}\n\n/** 0..1 across the NOAA bands (caution 27, extreme caution 32, danger 41, extreme danger 54 °C), linear between them. */\nexport function heatStress(heatIndex: number): number {\n const first = HEAT_STRESS_BANDS[0]!\n const last = HEAT_STRESS_BANDS[HEAT_STRESS_BANDS.length - 1]!\n if (heatIndex <= first[0]) return first[1]\n if (heatIndex >= last[0]) return last[1]\n for (let index = 1; index < HEAT_STRESS_BANDS.length; index++) {\n const [upperC, upperStress] = HEAT_STRESS_BANDS[index]!\n const [lowerC, lowerStress] = HEAT_STRESS_BANDS[index - 1]!\n if (heatIndex <= upperC) return lowerStress + ((heatIndex - lowerC) / (upperC - lowerC)) * (upperStress - lowerStress)\n }\n return last[1]\n}\n","import { heatIndexC, heatStress } from './heat'\nimport type { StateValues, WeatherEffects } from './types'\n\n/** Gameplay visibility of a dry day (the game's dry fog far, jogo.js L69141): `sightScale` is the visibility against it. */\nexport const DRY_VISIBILITY_METERS = 220\n/** jogo.js L66872: sight is `perc[0] × (1 − 0.4 × nightF)`. */\nexport const NIGHT_SIGHT_LOSS = 0.4\n\nexport type EffectsInput = {\n readonly values: StateValues\n readonly nightFactor: number\n readonly temperatureC: number\n readonly humidityPercent: number\n readonly lightningReveal: number\n}\n\n/** What the weather means for gameplay, as numbers for whoever has eyes, ears or feet in the world (perception, footsteps, heat). */\nexport function deriveEffects(input: EffectsInput): WeatherEffects {\n const { values, nightFactor } = input\n const weatherSight = Math.min(1, Math.max(0, values.visibility / DRY_VISIBILITY_METERS))\n const heatIndex = heatIndexC(input.temperatureC, input.humidityPercent)\n return {\n visibility: values.visibility,\n sightScale: weatherSight * (1 - NIGHT_SIGHT_LOSS * nightFactor),\n hearingScale: values.hearingScale,\n footstepScale: values.footstepScale,\n heatIndexC: heatIndex,\n heatStress: heatStress(heatIndex),\n lightningReveal: input.lightningReveal,\n dryingScale: values.dryingScale,\n debrisPush: values.debrisPush,\n }\n}\n","const FNV_OFFSET = 0x811c9dc5\nconst FNV_PRIME = 0x01000193\nconst MIX = 0x9e3779b1\n\n/** Deterministic mulberry32 generator; returns floats in [0, 1). */\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/** A seed for the stream called `name`: the same seed gives each name its own sequence, so lightning never shifts the schedule. */\nexport function streamSeed(seed: number, name: string): number {\n let hash = FNV_OFFSET\n for (let index = 0; index < name.length; index++) hash = Math.imul(hash ^ name.charCodeAt(index), FNV_PRIME) >>> 0\n return Math.imul((seed >>> 0) ^ hash, MIX) >>> 0\n}\n\nexport function createStream(seed: number, name: string): () => number {\n return createRng(streamSeed(seed, name))\n}\n\nexport function drawBetween(rng: () => number, range: readonly [min: number, max: number]): number {\n return range[0] + rng() * (range[1] - range[0])\n}\n","import { createStream, drawBetween } from './rng'\nimport type { LightningConfig } from './types'\n\n/** Speed of sound in air, m/s: a physical constant, so it is not configurable. */\nexport const SPEED_OF_SOUND = 343\n\n/** Seconds a flash goes on after a strike before the scene is back to normal (Workshop W1068: `k > .4`). */\nexport const FLASH_END_SECONDS = 0.4\n\n/** Seconds from the flash to the thunder for a strike `distance` metres away. */\nexport function thunderDelay(distance: number): number {\n return distance / SPEED_OF_SOUND\n}\n\n/** The Workshop double flash (W1068): full for 0.08 s, 0.2 until 0.16 s, 0.8 until 0.26 s, then dark. `elapsed` is seconds since the strike. */\nexport function flashIntensity(elapsed: number): number {\n if (elapsed < 0 || elapsed >= FLASH_END_SECONDS) return 0\n if (elapsed < 0.08) return 1\n if (elapsed < 0.16) return 0.2\n if (elapsed < 0.26) return 0.8\n return 0\n}\n\nexport type LightningStream = {\n /** Seconds from entering a state with lightning to its first strike. */\n first(config: LightningConfig): number\n /** Seconds from a strike to the next one. */\n interval(config: LightningConfig): number\n /** Where a strike lands: metres and degrees clockwise from north. Draws the distance, then the bearing. */\n place(config: LightningConfig): { readonly distance: number; readonly bearing: number }\n}\n\n/** The lightning's own seeded stream, apart from the scheduler's: the server can send the seed and every client sees the same strikes. */\nexport function createLightningStream(seed: number): LightningStream {\n const rng = createStream(seed, 'lightning')\n return {\n first: (config) => drawBetween(rng, config.first),\n interval: (config) => drawBetween(rng, config.interval),\n place(config) {\n const distance = drawBetween(rng, config.distance)\n return { distance, bearing: rng() * 360 }\n },\n }\n}\n","[\n {\n \"id\": \"temperate\",\n \"sources\": [\"galeria-vale-cinzento:L1393 (changes every 2-6 h, arrives from the west)\", \"design:T6 3.2 kit default: mostly clear and overcast, no extremes\"],\n \"start\": \"clear\",\n \"dwellHours\": [2, 6],\n \"blendMinutes\": 10,\n \"frontDirection\": [1, 0],\n \"temperatureC\": { \"mean\": 16, \"swing\": 6 },\n \"humidityOffset\": 0,\n \"transitions\": {\n \"clear\": { \"overcast\": 4, \"windy\": 1, \"fog\": 1, \"light_rain\": 1 },\n \"overcast\": { \"clear\": 3, \"light_rain\": 3, \"heavy_rain\": 1, \"fog\": 1, \"windy\": 1 },\n \"light_rain\": { \"overcast\": 3, \"clear\": 2, \"heavy_rain\": 2 },\n \"heavy_rain\": { \"light_rain\": 3, \"overcast\": 2, \"storm\": 1 },\n \"storm\": { \"heavy_rain\": 3, \"light_rain\": 2, \"overcast\": 1 },\n \"fog\": { \"clear\": 3, \"overcast\": 2 },\n \"windy\": { \"clear\": 3, \"overcast\": 3, \"light_rain\": 1 }\n }\n },\n {\n \"id\": \"tropical\",\n \"sources\": [\"galeria-vale-cinzento:L1393 (changes every 2-6 h, arrives from the west)\", \"design:T6 3.2 and Q3: extremes rare and enabled\"],\n \"start\": \"clear\",\n \"dwellHours\": [2, 6],\n \"blendMinutes\": 10,\n \"frontDirection\": [1, 0],\n \"temperatureC\": { \"mean\": 29, \"swing\": 3 },\n \"humidityOffset\": 0.1,\n \"transitions\": {\n \"clear\": { \"overcast\": 3, \"light_rain\": 2, \"windy\": 1, \"extreme_heat\": 0.8 },\n \"overcast\": { \"clear\": 3, \"light_rain\": 3, \"heavy_rain\": 2, \"fog\": 0.5 },\n \"light_rain\": { \"overcast\": 3, \"clear\": 2, \"heavy_rain\": 2 },\n \"heavy_rain\": { \"light_rain\": 3, \"overcast\": 2, \"storm\": 1.5 },\n \"storm\": { \"heavy_rain\": 3, \"light_rain\": 2, \"overcast\": 1, \"cyclone\": 0.5 },\n \"fog\": { \"clear\": 3, \"overcast\": 2 },\n \"windy\": { \"clear\": 3, \"overcast\": 2, \"light_rain\": 1, \"storm\": 0.5 },\n \"extreme_heat\": { \"clear\": 4, \"overcast\": 2, \"storm\": 0.8 },\n \"cyclone\": { \"storm\": 3, \"heavy_rain\": 2, \"typhoon\": 0.5 },\n \"typhoon\": { \"cyclone\": 3, \"storm\": 2 }\n }\n }\n]\n","[\n {\n \"id\": \"clear\",\n \"sources\": [\"jogo:L69141 (fog far 220 dry)\", \"showroom.js:L1693-1710 (breeze 3.5, 1.5 m/s)\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 3.5, \"windZ\": 1.5, \"gust\": 5,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 220,\n \"humidity\": 0.5, \"temperatureDeltaC\": 0, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"overcast\",\n \"sources\": [\"cena-de-arte:L413 (wind .35, .12)\", \"cena-de-arte:L36 (FogExp2 .03)\", \"design:T6 sky x0.9\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.35, \"windZ\": 0.12, \"gust\": 0.6,\n \"fogFar\": 220, \"fogDensity\": 0.03, \"skyScale\": 0.9, \"visibility\": 200,\n \"humidity\": 0.65, \"temperatureDeltaC\": -1, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"light_rain\",\n \"sources\": [\"oficina-vfx:W1065 (Garoa: 900 drops, slant .3)\", \"jogo:L70416-70427 (rain level .035)\", \"design:T6 2.5 mm/h, wetness .35, visibility 160, hearing x0.8 (Q4)\"],\n \"rain\": 2.5, \"drops\": 900, \"sheets\": 0,\n \"windX\": 0.3, \"windZ\": 0, \"gust\": 0.6,\n \"fogFar\": 180, \"fogDensity\": 0, \"skyScale\": 0.9, \"visibility\": 160,\n \"humidity\": 0.85, \"temperatureDeltaC\": -2, \"wetness\": 0.35,\n \"hearingScale\": 0.8, \"footstepScale\": 0.85, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"heavy_rain\",\n \"sources\": [\"oficina-vfx:W1065 (Chuva: 2200 drops, slant 1.2)\", \"cena-de-arte:L1314 (rain gain .06)\", \"jogo:L69141 (fog far 140, sky x0.8)\", \"galeria-vale-cinzento:L1393 (vision 120 m, quieter steps)\", \"design:T6 15 mm/h, hearing x0.6 (Q4)\"],\n \"rain\": 15, \"drops\": 2200, \"sheets\": 0,\n \"windX\": 1.2, \"windZ\": 0, \"gust\": 2,\n \"fogFar\": 140, \"fogDensity\": 0, \"skyScale\": 0.8, \"visibility\": 120,\n \"humidity\": 0.9, \"temperatureDeltaC\": -4, \"wetness\": 0.8,\n \"hearingScale\": 0.6, \"footstepScale\": 0.7, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"storm\",\n \"sources\": [\"oficina-vfx:W1065-1069 (Temporal: 4000 drops, slant 4.5, lightning 3.5-6 s, first at 2-4 s, sheets)\", \"showroom.js (60 mm/h)\", \"design:T6 hearing x0.5 (Q4)\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 4.5, \"windZ\": 0, \"gust\": 6,\n \"fogFar\": 110, \"fogDensity\": 0, \"skyScale\": 0.7, \"visibility\": 100,\n \"humidity\": 0.92, \"temperatureDeltaC\": -5, \"wetness\": 1,\n \"hearingScale\": 0.5, \"footstepScale\": 0.6, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"fog\",\n \"sources\": [\"oficina-vfx:W1073-1080 (density .075, ground mist 5/s, ash 14/s)\", \"jogo:L69101 (zone fog far 60)\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.3, \"windZ\": 0.1, \"gust\": 0.5,\n \"fogFar\": 60, \"fogDensity\": 0.075, \"skyScale\": 0.85, \"visibility\": 40,\n \"humidity\": 0.95, \"temperatureDeltaC\": -3, \"wetness\": 0.15,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 5, \"ashPerSecond\": 14\n },\n {\n \"id\": \"windy\",\n \"sources\": [\"cena-de-arte:L1315 (wind loop)\", \"design:T6 Q3 8 m/s, gust 12\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 8, \"windZ\": 0, \"gust\": 12,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 220,\n \"humidity\": 0.45, \"temperatureDeltaC\": -1, \"wetness\": 0,\n \"hearingScale\": 0.85, \"footstepScale\": 0.9, \"dryingScale\": 1, \"debrisPush\": 0,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n },\n {\n \"id\": \"cyclone\",\n \"sources\": [\"design:T6 Q3 physics preset, no team source: tropical cyclone 33 m/s sustained, gust x1.3, storm rain, debris push\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 33, \"windZ\": 0, \"gust\": 42.9,\n \"fogFar\": 80, \"fogDensity\": 0, \"skyScale\": 0.6, \"visibility\": 60,\n \"humidity\": 0.9, \"temperatureDeltaC\": 0, \"wetness\": 1,\n \"hearingScale\": 0.3, \"footstepScale\": 0.5, \"dryingScale\": 1, \"debrisPush\": 8,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"typhoon\",\n \"sources\": [\"design:T6 Q3 physics preset, no team source: typhoon 50 m/s sustained, gust x1.3, storm rain, debris push\"],\n \"rain\": 60, \"drops\": 4000, \"sheets\": 1,\n \"windX\": 50, \"windZ\": 0, \"gust\": 65,\n \"fogFar\": 60, \"fogDensity\": 0, \"skyScale\": 0.5, \"visibility\": 40,\n \"humidity\": 0.9, \"temperatureDeltaC\": 0, \"wetness\": 1,\n \"hearingScale\": 0.25, \"footstepScale\": 0.4, \"dryingScale\": 1, \"debrisPush\": 18,\n \"haze\": 0, \"mistPerSecond\": 0, \"ashPerSecond\": 0,\n \"lightning\": { \"interval\": [3.5, 6], \"first\": [2, 4], \"distance\": [200, 4000], \"reveal\": 0.2 }\n },\n {\n \"id\": \"extreme_heat\",\n \"sources\": [\"design:T6 Q3 no team source: 38 C at the tropical noon (+6 over the climate), 60 % humidity, haze, drying x2\"],\n \"rain\": 0, \"drops\": 0, \"sheets\": 0,\n \"windX\": 0.8, \"windZ\": 0.3, \"gust\": 1.5,\n \"fogFar\": 220, \"fogDensity\": 0, \"skyScale\": 1, \"visibility\": 200,\n \"humidity\": 0.6, \"temperatureDeltaC\": 6, \"wetness\": 0,\n \"hearingScale\": 1, \"footstepScale\": 1, \"dryingScale\": 2, \"debrisPush\": 0,\n \"haze\": 1, \"mistPerSecond\": 0, \"ashPerSecond\": 0\n }\n]\n","import climatesJson from './data/climates.json'\nimport statesJson from './data/states.json'\nimport type { Climate, DeepPartial, WeatherState } from './types'\n\nexport const WEATHER_STATES: readonly WeatherState[] = statesJson as unknown as readonly WeatherState[]\nexport const CLIMATES: readonly Climate[] = climatesJson as unknown as readonly Climate[]\n\nexport type RegistryOptions = {\n /** Added to the shipped states or, when the id exists, replacing it. */\n readonly states?: readonly WeatherState[]\n readonly climates?: readonly Climate[]\n /** Merged into a shipped or added entry by id; a patch for an id that does not exist is ignored. */\n readonly patch?: {\n readonly states?: Readonly<Record<string, DeepPartial<WeatherState>>>\n readonly climates?: Readonly<Record<string, DeepPartial<Climate>>>\n }\n readonly remove?: { readonly states?: readonly string[]; readonly climates?: readonly string[] }\n}\n\nexport type WeatherRegistry = {\n state(id: string): WeatherState | undefined\n climate(id: string): Climate | undefined\n stateIds(): string[]\n climateIds(): string[]\n registerState(state: WeatherState): void\n registerClimate(climate: Climate): void\n patchState(id: string, patch: DeepPartial<WeatherState>): void\n patchClimate(id: string, patch: DeepPartial<Climate>): void\n removeState(id: string): void\n removeClimate(id: string): void\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\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\nfunction deepMerge<TValue>(base: TValue, patch: DeepPartial<TValue>): TValue {\n return mergeRecords(base as Record<string, unknown>, patch as Record<string, unknown>) as TValue\n}\n\ntype Entry = { readonly id: string }\n\nfunction createTable<TEntry extends Entry>(shipped: readonly TEntry[]): Map<string, TEntry> {\n return new Map(shipped.map((entry) => [entry.id, entry]))\n}\n\nfunction patchEntry<TEntry extends Entry>(table: Map<string, TEntry>, id: string, patch: DeepPartial<TEntry>): void {\n const entry = table.get(id)\n if (entry) table.set(id, deepMerge(entry, patch))\n}\n\n/** The shipped states and climates with yours added, patched or removed; change it later with the same verbs. */\nexport function createWeatherRegistry(options: RegistryOptions = {}): WeatherRegistry {\n const states = createTable(WEATHER_STATES)\n const climates = createTable(CLIMATES)\n for (const state of options.states ?? []) states.set(state.id, state)\n for (const climate of options.climates ?? []) climates.set(climate.id, climate)\n for (const [id, patch] of Object.entries(options.patch?.states ?? {})) patchEntry(states, id, patch)\n for (const [id, patch] of Object.entries(options.patch?.climates ?? {})) patchEntry(climates, id, patch)\n for (const id of options.remove?.states ?? []) states.delete(id)\n for (const id of options.remove?.climates ?? []) climates.delete(id)\n return {\n state: (id) => states.get(id),\n climate: (id) => climates.get(id),\n stateIds: () => [...states.keys()],\n climateIds: () => [...climates.keys()],\n registerState: (state) => void states.set(state.id, state),\n registerClimate: (climate) => void climates.set(climate.id, climate),\n patchState: (id, patch) => patchEntry(states, id, patch),\n patchClimate: (id, patch) => patchEntry(climates, id, patch),\n removeState: (id) => void states.delete(id),\n removeClimate: (id) => void climates.delete(id),\n }\n}\n","import { createStream, drawBetween } from './rng'\nimport type { Climate } from './types'\n\nconst SECONDS_PER_HOUR = 3600\n/** A state lasts at least this long, so a climate patched to a zero dwell cannot stall the clock. */\nconst MIN_DWELL_SECONDS = 1\n\nexport type Scheduler = {\n /** Game seconds at which the current state ends. */\n nextChangeAt(): number\n /** Picks the state after `current`, then draws how long it lasts from `at`. Returns the new state's id. */\n next(current: string, at: number): string\n /** Draws a new duration from `at` (after a forced change). */\n restart(at: number): void\n}\n\n/**\n * A seeded Markov chain in game time. Draw order, fixed so the timeline repeats: at start one dwell; at each change the next state first\n * (one draw, over the weights in the climate's order), then its dwell. States `isKnown` rejects are left out of the weights.\n */\nexport function createScheduler(climate: Climate, seed: number, isKnown: (id: string) => boolean): Scheduler {\n const rng = createStream(seed, 'schedule')\n let changeAt = 0\n const drawDwell = (from: number): number => from + Math.max(MIN_DWELL_SECONDS, drawBetween(rng, climate.dwellHours) * SECONDS_PER_HOUR)\n changeAt = drawDwell(0)\n return {\n nextChangeAt: () => changeAt,\n next(current, at) {\n const options = Object.entries(climate.transitions[current] ?? {}).filter(([id, weight]) => weight > 0 && isKnown(id))\n const total = options.reduce((sum, [, weight]) => sum + weight, 0)\n let chosen = current\n if (total > 0) {\n let pick = rng() * total\n chosen = options[options.length - 1]![0]\n for (const [id, weight] of options) {\n if (pick < weight) {\n chosen = id\n break\n }\n pick -= weight\n }\n }\n changeAt = drawDwell(at)\n return chosen\n },\n restart(at) {\n changeAt = drawDwell(at)\n },\n }\n}\n","export const DEFAULT_WET_RISE_SECONDS = 120\n/** The Workshop sheet: the water goes back to the colour of the ground 3 minutes after the rain stops. */\nexport const DEFAULT_DRY_OUT_SECONDS = 180\n\nexport type WetnessOptions = {\n /** Seconds of rain to wet the ground fully. */\n readonly riseSeconds?: number\n /** Seconds from the end of the rain until the ground is dry. */\n readonly dryOutSeconds?: number\n}\n\nexport type Wetness = {\n value(): number\n /** Moves `seconds` toward `target` (the wetness the weather asks for); `dryingScale` speeds the dry-out up. Returns the new value. */\n update(seconds: number, target: number, dryingScale?: number): number\n reset(value?: number): void\n}\n\n/** Ground wetness: rises while the weather asks for more, then falls in a straight line that ends `dryOutSeconds` after the start of the fall. */\nexport function createWetness(options: WetnessOptions = {}): Wetness {\n const riseSeconds = options.riseSeconds ?? DEFAULT_WET_RISE_SECONDS\n const dryOutSeconds = options.dryOutSeconds ?? DEFAULT_DRY_OUT_SECONDS\n let current = 0\n let peak = 0\n let isDrying = false\n return {\n value: () => current,\n update(seconds, target, dryingScale = 1) {\n if (target > current) {\n isDrying = false\n current = Math.min(target, current + seconds / riseSeconds)\n } else if (target < current) {\n if (!isDrying) {\n isDrying = true\n peak = current\n }\n current = Math.max(target, current - (peak * seconds * dryingScale) / dryOutSeconds)\n } else isDrying = false\n return current\n },\n reset(value = 0) {\n current = value\n peak = value\n isDrying = false\n },\n }\n}\n","import { blendValues, valuesOf } from './blend'\nimport { DEFAULT_TIME_SCALE, daylight, dayFractionAt } from './daylight'\nimport { deriveEffects } from './effects'\nimport { createLightningStream, flashIntensity, thunderDelay } from './lightning'\nimport { createWeatherRegistry } from './registry'\nimport type { RegistryOptions, WeatherRegistry } from './registry'\nimport { createScheduler } from './scheduler'\nimport type { Climate, StateValues, Strike, WeatherEventMap, WeatherSample, WeatherState } from './types'\nimport { createWetness } from './wetness'\nimport type { WetnessOptions } from './wetness'\n\nexport const DEFAULT_START_HOUR = 8\nconst SECONDS_PER_MINUTE = 60\nconst WETNESS_STEP_SECONDS = 1\n\nexport type WeatherOptions = RegistryOptions & {\n /** Seed of the schedule and of the lightning (each has its own stream). Default 1. */\n readonly seed?: number\n /** Climate id. Default `temperate`. */\n readonly climate?: string\n /** First state; default the climate's `start`, which is `clear`: the normal world comes first. */\n readonly start?: string\n /** Game seconds per real second. Default 72 (the 20-minute day). */\n readonly timeScale?: number\n /** Hour of the day the world starts at. Default 8. */\n readonly startHour?: number\n /** `false` keeps the state until `force` changes it. Default true. */\n readonly autoSchedule?: boolean\n readonly wetness?: WetnessOptions\n /** An existing registry, instead of building one from the registry options. */\n readonly registry?: WeatherRegistry\n}\n\nexport type WeatherTimeline = {\n readonly seed: number\n readonly climate: string\n readonly start: string\n readonly hours: number\n readonly sampleMinutes: number\n readonly transitions: ReadonlyArray<{ readonly gameSeconds: number; readonly from: string; readonly to: string }>\n readonly strikes: readonly Strike[]\n readonly samples: ReadonlyArray<Readonly<Record<string, number | string>>>\n}\n\nexport type Weather = {\n readonly registry: WeatherRegistry\n /** Moves the world forward by `dt` real seconds (game time moves `timeScale` times as fast). Events fire in order as they are crossed. */\n advance(dt: number): void\n sample(): WeatherSample\n /** The state being blended to, or settled in. */\n state(): string\n /** Changes state now, blending over `blendSeconds` real seconds (0 is at once); the new state then lasts a normal dwell. */\n force(id: string, blendSeconds?: number): void\n setTimeScale(timeScale: number): void\n setAutoSchedule(isOn: boolean): void\n /** What a fresh world with these options does over `hours` game hours; the live world is not touched. */\n timeline(hours: number, sampleMinutes?: number): WeatherTimeline\n on<TEvent extends keyof WeatherEventMap>(event: TEvent, listener: (payload: WeatherEventMap[TEvent]) => void): () => void\n}\n\ntype Blend = { startedAt: number; duration: number }\n\nconst clamp01 = (value: number): number => Math.min(1, Math.max(0, value))\n\nfunction requireClimate(registry: WeatherRegistry, id: string): Climate {\n const climate = registry.climate(id)\n if (!climate) throw new Error(`game-weather: unknown climate \"${id}\"`)\n return climate\n}\n\nfunction requireState(registry: WeatherRegistry, id: string): WeatherState {\n const state = registry.state(id)\n if (!state) throw new Error(`game-weather: unknown state \"${id}\"`)\n return state\n}\n\nexport function createWeather(options: WeatherOptions = {}): Weather {\n const registry = options.registry ?? createWeatherRegistry(options)\n const seed = options.seed ?? 1\n const climateId = options.climate ?? 'temperate'\n const startClimate = requireClimate(registry, climateId)\n const startState = requireState(registry, options.start ?? startClimate.start)\n const startHour = options.startHour ?? DEFAULT_START_HOUR\n const scheduler = createScheduler(startClimate, seed, (id) => registry.state(id) !== undefined)\n const lightning = createLightningStream(seed)\n const wetness = createWetness(options.wetness)\n const listeners = new Map<keyof WeatherEventMap, Set<(payload: never) => void>>()\n\n let timeScale = options.timeScale ?? DEFAULT_TIME_SCALE\n let isAutoSchedule = options.autoSchedule ?? true\n let gameSeconds = 0\n let simSeconds = 0\n let target = startState\n let targetValues = valuesOf(startState)\n let fromValues: StateValues = targetValues\n let previousId: string | undefined\n let blend: Blend = { startedAt: 0, duration: 0 }\n let nextStrikeAt: number | undefined\n let strikeCount = 0\n let lastStrike: Strike | undefined\n const pendingThunder: Strike[] = []\n\n const climate = (): Climate => registry.climate(climateId) ?? startClimate\n\n const emit = <TEvent extends keyof WeatherEventMap>(event: TEvent, payload: WeatherEventMap[TEvent]): void => {\n for (const listener of [...(listeners.get(event) ?? [])]) (listener as (value: WeatherEventMap[TEvent]) => void)(payload)\n }\n\n const progressAt = (at: number): number => (blend.duration <= 0 ? 1 : clamp01((at - blend.startedAt) / blend.duration))\n const valuesAt = (at: number): StateValues => blendValues(fromValues, targetValues, progressAt(at))\n\n const scheduleFirstStrike = (atSim: number): void => {\n nextStrikeAt = target.lightning ? atSim + lightning.first(target.lightning) : undefined\n }\n\n const enter = (id: string, atGame: number, atSim: number, blendGameSeconds: number): void => {\n const next = requireState(registry, id)\n fromValues = valuesAt(atGame)\n previousId = target.id\n target = next\n targetValues = valuesOf(next)\n blend = { startedAt: atGame, duration: blendGameSeconds }\n scheduleFirstStrike(atSim)\n emit('transition', { from: previousId, to: id, gameSeconds: atGame })\n }\n\n const strikeAt = (atSim: number, startGame: number, startSim: number): void => {\n const config = target.lightning!\n const place = lightning.place(config)\n const strike: Strike = {\n id: strikeCount++,\n time: atSim,\n gameSeconds: startGame + (atSim - startSim) * timeScale,\n distance: place.distance,\n bearing: place.bearing,\n thunderDelay: thunderDelay(place.distance),\n }\n lastStrike = strike\n pendingThunder.push(strike)\n pendingThunder.sort((a, b) => a.time + a.thunderDelay - (b.time + b.thunderDelay))\n nextStrikeAt = atSim + lightning.interval(config)\n emit('strike', strike)\n }\n\n scheduleFirstStrike(0)\n\n const runEvents = (startGame: number, startSim: number, endSim: number): void => {\n for (;;) {\n const changeSim = isAutoSchedule ? Math.max(startSim, startSim + (scheduler.nextChangeAt() - startGame) / timeScale) : Infinity\n const strikeSim = nextStrikeAt ?? Infinity\n const thunder = pendingThunder[0]\n const thunderSim = thunder ? thunder.time + thunder.thunderDelay : Infinity\n const earliest = Math.min(changeSim, strikeSim, thunderSim)\n if (earliest > endSim) return\n if (earliest === changeSim) {\n const atGame = Math.max(startGame, scheduler.nextChangeAt())\n const next = scheduler.next(target.id, atGame)\n enter(next, atGame, changeSim, climate().blendMinutes * SECONDS_PER_MINUTE)\n } else if (earliest === strikeSim) strikeAt(strikeSim, startGame, startSim)\n else emit('thunder', pendingThunder.shift()!)\n }\n }\n\n const wet = (startGame: number, endGame: number, seconds: number): void => {\n const steps = Math.max(1, Math.ceil(seconds / WETNESS_STEP_SECONDS))\n for (let step = 1; step <= steps; step++) {\n const values = valuesAt(startGame + ((endGame - startGame) * step) / steps)\n wetness.update(seconds / steps, values.wetness, values.dryingScale)\n }\n }\n\n const api: Weather = {\n registry,\n advance(dt) {\n if (!(dt > 0)) return\n const startGame = gameSeconds\n const startSim = simSeconds\n const endGame = startGame + dt * timeScale\n runEvents(startGame, startSim, startSim + dt)\n gameSeconds = endGame\n simSeconds = startSim + dt\n wet(startGame, endGame, dt)\n },\n sample() {\n const values = valuesAt(gameSeconds)\n const dayFraction = dayFractionAt(startHour, gameSeconds)\n const { sun, nightFactor } = daylight(dayFraction)\n const current = climate()\n const temperatureC = current.temperatureC.mean + current.temperatureC.swing * (2 * sun - 1) + values.temperatureDeltaC\n const humidityPercent = clamp01(values.humidity + current.humidityOffset) * 100\n const progress = progressAt(gameSeconds)\n return {\n ...values,\n gameSeconds,\n dayFraction,\n hour: dayFraction * 24,\n nightFactor,\n sun,\n state: target.id,\n previous: progress < 1 ? previousId : undefined,\n blend: progress,\n front: { direction: current.frontDirection, progress },\n windSpeed: Math.sqrt(values.windX * values.windX + values.windZ * values.windZ),\n temperatureC,\n humidityPercent,\n groundWetness: wetness.value(),\n flash: lastStrike ? flashIntensity(simSeconds - lastStrike.time) : 0,\n effects: deriveEffects({ values, nightFactor, temperatureC, humidityPercent, lightningReveal: target.lightning?.reveal ?? 0 }),\n }\n },\n state: () => target.id,\n force(id, blendSeconds = 0) {\n enter(id, gameSeconds, simSeconds, blendSeconds * timeScale)\n scheduler.restart(gameSeconds)\n },\n setTimeScale(next) {\n if (!(next > 0)) throw new Error('game-weather: timeScale must be above 0')\n timeScale = next\n },\n setAutoSchedule(isOn) {\n if (isOn && !isAutoSchedule) scheduler.restart(gameSeconds)\n isAutoSchedule = isOn\n },\n timeline: (hours, sampleMinutes) => createTimeline({ ...options, registry, hours, ...(sampleMinutes === undefined ? {} : { sampleMinutes }) }),\n on(event, listener) {\n const set = listeners.get(event) ?? new Set()\n set.add(listener as (payload: never) => void)\n listeners.set(event, set)\n return () => void set.delete(listener as (payload: never) => void)\n },\n }\n return api\n}\n\nexport type TimelineOptions = WeatherOptions & {\n readonly hours: number\n /** Game minutes between samples. Default 10. */\n readonly sampleMinutes?: number\n}\n\nconst TIMELINE_DECIMALS = 6\nconst round = (value: number): number => Math.round(value * 10 ** TIMELINE_DECIMALS) / 10 ** TIMELINE_DECIMALS + 0\n\n/**\n * What a fresh world does over `hours` game hours, stepping one game minute at a time: the state changes, the strikes (time, distance, bearing) and\n * a sample every `sampleMinutes`. Plain JSON, rounded to 6 decimals, so it can be a golden.\n */\nexport function createTimeline(options: TimelineOptions): WeatherTimeline {\n const weather = createWeather(options)\n const timeScale = options.timeScale ?? DEFAULT_TIME_SCALE\n const sampleMinutes = options.sampleMinutes ?? 10\n const transitions: Array<{ gameSeconds: number; from: string; to: string }> = []\n const strikes: Strike[] = []\n weather.on('transition', (event) => transitions.push({ gameSeconds: round(event.gameSeconds), from: event.from, to: event.to }))\n weather.on('strike', (strike) =>\n strikes.push({ id: strike.id, time: round(strike.time), gameSeconds: round(strike.gameSeconds), distance: round(strike.distance), bearing: round(strike.bearing), thunderDelay: round(strike.thunderDelay) }),\n )\n const samples: Array<Record<string, number | string>> = []\n const record = (minute: number): void => {\n const sample = weather.sample()\n samples.push({\n at: minute * SECONDS_PER_MINUTE,\n hour: round(sample.hour),\n state: sample.state,\n blend: round(sample.blend),\n rain: round(sample.rain),\n windSpeed: round(sample.windSpeed),\n gust: round(sample.gust),\n visibility: round(sample.effects.visibility),\n sightScale: round(sample.effects.sightScale),\n hearingScale: round(sample.effects.hearingScale),\n temperatureC: round(sample.temperatureC),\n heatIndexC: round(sample.effects.heatIndexC),\n heatStress: round(sample.effects.heatStress),\n wetness: round(sample.groundWetness),\n nightFactor: round(sample.nightFactor),\n })\n }\n record(0)\n const minutes = Math.round(options.hours * 60)\n for (let minute = 1; minute <= minutes; minute++) {\n weather.advance(SECONDS_PER_MINUTE / timeScale)\n if (minute % sampleMinutes === 0) record(minute)\n }\n return {\n seed: options.seed ?? 1,\n climate: options.climate ?? 'temperate',\n start: options.start ?? weather.registry.climate(options.climate ?? 'temperate')!.start,\n hours: options.hours,\n sampleMinutes,\n transitions,\n strikes,\n samples,\n }\n}\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 readonly sources: readonly string[]\n}\n\nexport type SoundBank = {\n readonly id: string\n readonly sounds?: readonly SoundRecipe[]\n readonly loops?: readonly LoopRecipe[]\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}\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","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","[\n {\n \"id\": \"game\",\n \"master\": 0.5,\n \"noise\": { \"seconds\": 1.5, \"create\": \"lazy\" },\n \"sources\": [\"jogo:L62077-62081 master 0.5 to the output\", \"jogo:L62082-62088 noise 1.5 s made by the first sound that needs it\"]\n },\n {\n \"id\": \"art_scene\",\n \"master\": 0.85,\n \"compressor\": { \"threshold\": -12, \"ratio\": 5 },\n \"reverb\": { \"seconds\": 2.2, \"decay\": 3.4, \"wet\": 0.4 },\n \"noise\": { \"seconds\": 2, \"create\": \"eager\" },\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","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) → 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 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); `mix: 'game'` reverts. */\nexport const DEFAULT_MIX = 'art_scene'\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","import type { LoopRecipe, SoundBank, SoundRecipe } from './recipe'\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>): void\n remove(id: string): void\n sound(id: string): SoundRecipe | undefined\n loop(id: string): LoopRecipe | undefined\n soundIds(): string[]\n loopIds(): 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 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 },\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 },\n remove(id) {\n sounds.delete(id)\n loops.delete(id)\n owners.delete(id)\n },\n sound: (id) => sounds.get(id),\n loop: (id) => loops.get(id),\n soundIds: () => [...sounds.keys()],\n loopIds: () => [...loops.keys()],\n bankOf: (id) => owners.get(id),\n }\n for (const bank of banks) registry.register(bank)\n return registry\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","/** `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\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 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(context.destination)\n }\n const master = context.createGain()\n master.gain.value = profile.master\n master.connect(compressor ?? context.destination)\n if (!profile.reverb) {\n return {\n master,\n disconnect: () => {\n master.disconnect()\n compressor?.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 },\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 if (context.state === 'suspended') void context.resume()\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 readonly source: AudioScheduledSourceNode\n readonly frequency?: AudioParam\n stop(): void\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 gain.connect(target.output)\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, source, ...(frequency ? { 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 gain.connect(target.output)\n source.start()\n for (const lfo of lfos) lfo.start()\n return { gain, source, ...(frequency ? { frequency } : {}), stop: stopAll([source, ...lfos]) }\n}\n","import { 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/** A continuous sound: `set` glides the volume and, for an oscillator, the frequency; `stop` tears the nodes down. */\nexport type AudioLoopHandle = {\n set(state: { readonly volume?: number; readonly frequency?: number }): 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}\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?.gain.disconnect()\n nodes?.gain.connect(host.output(loopRecipe.bus))\n },\n stop() {\n nodes?.stop()\n nodes?.gain.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 return {\n set(next) {\n if (isChain && !nodes) open()\n const context = host.ready()\n if (!context) return\n const action = state.set(next)\n if (!action) return\n nodes ??= create(context, 0)\n nodes.gain.gain.setTargetAtTime(action.volume, context.currentTime, smoothing.volume)\n if (action.frequency !== undefined && nodes.frequency) nodes.frequency.setTargetAtTime(action.frequency, context.currentTime, smoothing.frequency)\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","// 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 { 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 { createNoiseStore, noiseBuffer, prepareNoise } from './engine-noise'\nimport type { NoiseStore } from './engine-noise'\nimport type { RealizedVoice } from './nodes'\nimport { realize } from './realize'\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 /** A named stream of the engine (`streamFor(seed, name)`), so one subject never shifts another's sounds. */\n readonly channel?: string\n}\n\nexport type VoiceHandle = { readonly id: number; readonly plan: SoundPlan; stop(): void }\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}\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 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 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 dispose(): void\n}\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\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 start = (plan: SoundPlan, store: NoiseStore, voiceId: number | undefined, delay = 0): VoiceHandle | null => {\n const audio = context as AudioContext\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: audio.currentTime + delay,\n })\n if (voiceId === undefined) return null\n voices.setLength(voiceId, plan.length + delay)\n active.set(voiceId, realized)\n return {\n id: voiceId,\n plan,\n stop() {\n realized.stop()\n voices.release(voiceId)\n active.delete(voiceId)\n },\n }\n }\n\n const admit = (recipe: SoundRecipe, 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 const playWith = (id: string, playOptions: PlayOptions, random: () => number, store: NoiseStore): VoiceHandle | null => {\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, playOptions.seed === undefined ? random : createRng(playOptions.seed)))\n return plan ? start(plan, store, voiceId, playOptions.delay) : 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 const planWith = (id: string, playOptions: PlayOptions, random: () => number): SoundPlan | null => {\n const recipe = registry.sound(id)\n return recipe ? planSound(recipe, inputFor(recipe, playOptions, random)) : 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 }\n\n return {\n registry,\n register: (bank) => registry.register(bank),\n plan: (id, playOptions = {}) => planWith(id, playOptions, createRng(playOptions.seed ?? seed)),\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 = {}) => createLoopHandle(registry.loop(id), loopHost, loopOptions.volume),\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 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 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 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 },\n }\n}\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 })\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): LoopHandle {\n const loop = engine.loop(sound)\n return { set: (state) => loop.set({ ...(state.volume === undefined ? {} : { volume: state.volume }), ...(state.frequency === undefined ? {} : { frequency: state.frequency }) }), stop: () => loop.stop() }\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' },\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' },\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 { 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: 'art_scene',\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 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","// Rain, wind and thunder as recipes of @adatechnology/game-audio. The loops are the teams' (the art scene's `initAudio`, cena L1314-L1315, and the game's\n// `chuva` loop, jogo L62116); the thunder is the game's `boom` (jogo L68278, a sine from 70 to 28 Hz) with a low rumble under it, the kit's choice.\nimport { sceneNoise, sceneTone } from '@adatechnology/game-audio'\nimport type { LoopRecipe, SoundBank, SoundRecipe } from '@adatechnology/game-audio'\n\n/** Rain of the art scene: noise through a highpass at 600 Hz and a lowpass at 6000 Hz (cena L1314), opened at its volume. */\nexport const RAIN_LOOP: LoopRecipe = {\n id: 'rain_loop',\n bus: 'weather',\n order: 'chain_loop',\n source: { kind: 'noise', loop: true },\n filters: {\n mode: 'serial',\n bank: [\n { type: 'highpass', frequency: { set: 600 } },\n { type: 'lowpass', frequency: { set: 6000 } },\n ],\n },\n sources: ['cena:L1314'],\n}\n\n/** Wind of the art scene: noise through a lowpass at 320 Hz whose gain swings 0.035 at 0.07 Hz (cena L1315). */\nexport const WIND_LOOP: LoopRecipe = {\n id: 'wind_loop',\n bus: 'weather',\n order: 'chain_loop',\n source: { kind: 'noise', loop: true },\n filters: { mode: 'serial', bank: [{ type: 'lowpass', frequency: { set: 320 } }] },\n modulators: [{ target: 'gain', rate: 0.07, depth: 0.035 }],\n sources: ['cena:L1315'],\n}\n\n/** Rain of the game: noise through a highpass at 2500 Hz, created when the volume first passes 0.002 (jogo L62116 `chuva`). */\nexport const RAIN_HISS_GAME: LoopRecipe = {\n id: 'rain_hiss_game',\n bus: 'weather',\n order: 'game_loop',\n source: { kind: 'noise', loop: true },\n filters: { mode: 'serial', bank: [{ type: 'highpass', frequency: { set: 2500 } }] },\n sources: ['jogo:L62116 chuva'],\n}\n\n/**\n * Thunder. The thump is the game's boom (a sine from 70 to 28 Hz over 1.2 s); the rumble is a lowpassed noise that slides from 260 to 50 Hz over 3.2 s\n * with a reverb send, the kit's choice (no team has a thunder). It carries much farther than a blast: `k` is 0.00001, so a strike 1 km away is still at\n * 0.13 and one 4 km away (the farthest the weather places) at 0.009.\n */\nexport const THUNDER: SoundRecipe = {\n id: 'thunder',\n bus: 'weather',\n pan: true,\n layers: [sceneTone({ f: 70, f2: 28, d: 1.2, vol: 1 }), sceneNoise({ f: 260, f2: 50, d: 3.2, vol: 0.9, wet: 0.8 })],\n falloff: { model: 'inverse_square', k: 0.00001, scale: 1.4 },\n sources: ['jogo:L68278-68285 boom', 'sdk: rumble and falloff'],\n}\n\nexport const WEATHER_BANK: SoundBank = { id: 'weather', sounds: [THUNDER], loops: [RAIN_LOOP, WIND_LOOP, RAIN_HISS_GAME] }\nexport const WEATHER_SOUNDS: readonly SoundRecipe[] = WEATHER_BANK.sounds ?? []\nexport const WEATHER_LOOPS: readonly LoopRecipe[] = WEATHER_BANK.loops ?? []\n","import type { AudioSink, LoopHandle, Vec3 } from '@adatechnology/game-contracts'\n\nimport type { Strike, WeatherSample } from '../types'\nimport { WEATHER_BANK } from './recipes'\n\nexport type WeatherSoundStyle = 'art_scene' | 'game'\n\nexport type WeatherSoundOptions = {\n /** Which team's rain: `art_scene` (default, the kit mix) or `game` (a highpass hiss). The wind and the thunder are the same. */\n readonly style?: WeatherSoundStyle\n /**\n * Level of the rain loop. It is `light` at `lightAt` mm/h (the game's rain, 0.035) and `heavy` from `heavyAt` mm/h (the art scene's, 0.06), a straight\n * line between, and 0 when it does not rain.\n */\n readonly rain?: { readonly light?: number; readonly heavy?: number; readonly lightAt?: number; readonly heavyAt?: number }\n /** Level of the wind loop: `base` (the art scene's 0.05) at `referenceSpeed` m/s, in proportion to the speed, at most `max`. */\n readonly wind?: { readonly base?: number; readonly referenceSpeed?: number; readonly max?: number }\n /** Where the listener is, to place the thunder around it (default the origin). */\n readonly listener?: () => Vec3\n /** Level of the thunder (default 1). */\n readonly thunderVolume?: number\n /** `false` keeps the sink's bank as it is (the host registered `WEATHER_BANK` itself). */\n readonly register?: boolean\n}\n\nexport const DEFAULT_RAIN_SOUND = { light: 0.035, heavy: 0.06, lightAt: 2.5, heavyAt: 15 } as const\n/** The art scene opens its wind at 0.05 with the breeze of its day (3.8 m/s, the `clear` state's wind): the level follows the speed from there. */\nexport const DEFAULT_WIND_SOUND = { base: 0.05, referenceSpeed: 3.8, max: 0.12 } as const\n\n/** The level of the rain loop for `rain` mm/h. */\nexport function rainVolume(rain: number, options: WeatherSoundOptions['rain'] = {}): number {\n if (!(rain > 0)) return 0\n const { light, heavy, lightAt, heavyAt } = { ...DEFAULT_RAIN_SOUND, ...options }\n if (heavyAt <= lightAt) return rain >= heavyAt ? heavy : light\n const t = Math.min(1, Math.max(0, (rain - lightAt) / (heavyAt - lightAt)))\n return light + (heavy - light) * t\n}\n\n/** The level of the wind loop for a wind of `speed` m/s. */\nexport function windVolume(speed: number, options: WeatherSoundOptions['wind'] = {}): number {\n const { base, referenceSpeed, max } = { ...DEFAULT_WIND_SOUND, ...options }\n return Math.min(max, (base * Math.max(0, speed)) / referenceSpeed)\n}\n\n/** Where a strike is, around `origin`: `bearing` is degrees clockwise from north, and north is -z. */\nexport function strikePosition(strike: Pick<Strike, 'distance' | 'bearing'>, origin: Vec3 = [0, 0, 0]): Vec3 {\n const angle = (strike.bearing * Math.PI) / 180\n return [origin[0] + Math.sin(angle) * strike.distance, origin[1], origin[2] - Math.cos(angle) * strike.distance]\n}\n\nexport type WeatherSound = {\n /** Sets the level of the loops from the weather of now (opens a loop the first time it is above 0). */\n update(sample: Pick<WeatherSample, 'rain' | 'windSpeed'>): void\n /** Plays a clap of thunder at the strike (call it when the thunder arrives: the weather delays it by `distance / 343`). */\n thunder(strike: Pick<Strike, 'distance' | 'bearing'>): void\n dispose(): void\n}\n\n/** The sound of the weather on the host's `audio`: the rain loop, the wind loop and the thunder. Without a sink (or one without loops) it does nothing. */\nexport function createWeatherSound(sink: AudioSink | undefined, options: WeatherSoundOptions = {}): WeatherSound {\n if (sink && options.register !== false) sink.register?.(WEATHER_BANK)\n const rainSound = options.style === 'game' ? 'rain_hiss_game' : 'rain_loop'\n const loops = new Map<string, LoopHandle>()\n const set = (id: string, volume: number): void => {\n let loop = loops.get(id)\n if (!loop) {\n if (!(volume > 0) || !sink?.loop) return\n loop = sink.loop(id)\n loops.set(id, loop)\n }\n loop.set({ volume })\n }\n return {\n update(sample) {\n set(rainSound, rainVolume(sample.rain, options.rain))\n set('wind_loop', windVolume(sample.windSpeed, options.wind))\n },\n thunder(strike) {\n sink?.play({ sound: 'thunder', position: strikePosition(strike, options.listener?.()), ...(options.thunderVolume === undefined ? {} : { volume: options.thunderVolume }) })\n },\n dispose() {\n for (const loop of loops.values()) loop.stop()\n loops.clear()\n },\n }\n}\n","import type { AudioSink, EnvironmentBus, EnvironmentState } from '@adatechnology/game-contracts'\n\nimport { createWeatherSound } from './audio/sound'\nimport type { WeatherSound, WeatherSoundOptions } from './audio/sound'\nimport type { Strike, WeatherSample } from './types'\nimport type { Weather } from './weather'\n\n/** The shape of the film of `game-fluids-three` (`FilmBridge`) this needs: no import, so the weather does not depend on it. */\nexport type FilmTarget = {\n setWeather(weather: { rain: number; drying?: number }): void\n wash?(maxDryness?: number): number\n}\n/** The interactables world (`game-interactables`): its water takes the rain, the soft volumes the wind. */\nexport type InteractablesTarget = { water: { setRain(mmPerHour: number): void }; setWind(x: number, z: number): void }\n/** The vegetation renderer (`game-vegetation`). `direction` is normalised by the renderer, `strength` and `gust` are 0..1. */\nexport type VegetationTarget = { setWind(wind: { direction?: [number, number]; strength?: number; gust?: number }): void }\n/** The effects world (`game-vfx`'s `VfxWorld`): smoke and dust drift with its wind. */\nexport type VfxTarget = { setWind(wind: readonly [number, number, number]): void }\n\nexport type WeatherTargets = {\n readonly film?: FilmTarget\n readonly interactables?: InteractablesTarget\n readonly vegetation?: VegetationTarget\n readonly vfx?: VfxTarget\n /** The host's environment bus (`ModuleHost.environment`). */\n readonly environment?: Pick<EnvironmentBus, 'set'>\n /** The host's sound (`ModuleHost.audio`): the rain and wind loops, and the thunder. */\n readonly audio?: AudioSink\n}\n\n/** The rules the bridges apply; every number can be replaced. */\nexport type WeatherBridgeRules = {\n /** Rain in mm/h at which the film counts as fully rained on (it stops drying, spreads 1.5 times faster). Default 2.5, the light rain. */\n readonly filmRainFullAt?: number\n /** Rain in mm/h from which the rain washes the fresh stain (Workshop and visor: heavy rain and stronger). Default 15; light rain does not wash. */\n readonly washFrom?: number\n /** Stains less dry than this are washed (visor L13494). Default 0.5. */\n readonly washBelow?: number\n /** Seconds between two washes while it pours. Default 1. */\n readonly washEvery?: number\n /** Wind speed in m/s that is 1 for the vegetation (`strength = min(1, speed / this)`). Default 20. */\n readonly windFull?: number\n}\n\nexport type WeatherBridgeOptions = WeatherBridgeRules & {\n readonly sound?: WeatherSoundOptions | false\n}\n\nexport const DEFAULT_BRIDGE_RULES = { filmRainFullAt: 2.5, washFrom: 15, washBelow: 0.5, washEvery: 1, windFull: 20 } as const\n\n/** The weather as the environment bus holds it. */\nexport function environmentOf(sample: WeatherSample): Partial<EnvironmentState> {\n return {\n rain: sample.rain,\n windX: sample.windX,\n windZ: sample.windZ,\n windSpeed: sample.windSpeed,\n gust: sample.gust,\n fogFar: sample.fogFar,\n visibility: sample.effects.visibility,\n nightFactor: sample.nightFactor,\n temperatureC: sample.temperatureC,\n wetness: sample.groundWetness,\n }\n}\n\nexport type WeatherBridges = {\n /** Follows this weather (the one before is let go) and pushes its values at once. */\n bind(weather: Weather): void\n /** Pushes the weather of now to every target; call it each frame after `weather.advance(dt)`. */\n update(dt: number): void\n dispose(): void\n}\n\n/**\n * Pushes one weather to the packages that react to it, each through a small interface of its own, so the weather depends on none of them and every\n * target is optional:\n * - fluids film: `setWeather({ rain: min(1, rain / filmRainFullAt), drying: dryingScale })`, and `wash()` every `washEvery` seconds while the rain is at\n * `washFrom` or stronger (light rain stops the drying and does not wash);\n * - interactables: `water.setRain(mm/h)` and `setWind(x, z)`;\n * - vegetation: `setWind({ direction: [x, z], strength: min(1, speed / windFull), gust: min(1, gust / windFull) })`;\n * - vfx: `setWind([x, 0, z])`;\n * - the environment bus: every value of `environmentOf`;\n * - sound: the rain and wind loops follow the weather, and each thunder that arrives plays at its bearing.\n */\nexport function createWeatherBridges(targets: WeatherTargets, options: WeatherBridgeOptions = {}): WeatherBridges {\n const rules = { ...DEFAULT_BRIDGE_RULES, ...options }\n const sound: WeatherSound | undefined = options.sound === false || !targets.audio ? undefined : createWeatherSound(targets.audio, options.sound ?? {})\n let weather: Weather | undefined\n let offThunder: (() => void) | undefined\n let sinceWash = 0\n let last: { rain?: number; windX?: number; windZ?: number; filmRain?: number; drying?: number } = {}\n\n const push = (): void => {\n if (!weather) return\n const sample = weather.sample()\n const { film, interactables, vegetation, vfx, environment } = targets\n environment?.set(environmentOf(sample))\n if (film) {\n const rain = Math.min(1, Math.max(0, sample.rain / rules.filmRainFullAt))\n const drying = sample.effects.dryingScale\n if (rain !== last.filmRain || drying !== last.drying) film.setWeather({ rain, drying })\n last.filmRain = rain\n last.drying = drying\n }\n if (interactables && sample.rain !== last.rain) interactables.water.setRain(sample.rain)\n const windChanged = sample.windX !== last.windX || sample.windZ !== last.windZ\n if (windChanged) {\n interactables?.setWind(sample.windX, sample.windZ)\n vfx?.setWind([sample.windX, 0, sample.windZ])\n if (vegetation) {\n const wind = { strength: Math.min(1, sample.windSpeed / rules.windFull), gust: Math.min(1, sample.gust / rules.windFull) }\n vegetation.setWind(sample.windSpeed > 1e-6 ? { direction: [sample.windX, sample.windZ], ...wind } : wind)\n }\n }\n last = { ...last, rain: sample.rain, windX: sample.windX, windZ: sample.windZ }\n sound?.update(sample)\n }\n\n const onThunder = (strike: Strike): void => sound?.thunder(strike)\n\n return {\n bind(next) {\n offThunder?.()\n weather = next\n offThunder = next.on('thunder', onThunder)\n last = {}\n sinceWash = 0\n push()\n },\n update(dt) {\n push()\n if (!weather || !targets.film?.wash) return\n if (weather.sample().rain < rules.washFrom) {\n sinceWash = 0\n return\n }\n sinceWash += dt\n if (sinceWash >= rules.washEvery) {\n sinceWash = 0\n targets.film.wash(rules.washBelow)\n }\n },\n dispose() {\n offThunder?.()\n offThunder = undefined\n weather = undefined\n sound?.dispose()\n },\n }\n}\n","export type WeatherBenchText = {\n readonly group: string\n readonly name: string\n readonly controls: Readonly<Record<'state' | 'transition' | 'time_of_day' | 'auto_schedule' | 'seed', string>>\n readonly hints: Readonly<Record<'transition' | 'time_of_day' | 'auto_schedule' | 'seed', string>>\n readonly options: Readonly<Record<'instant' | 'ten_seconds', string>>\n readonly layers: Readonly<Record<'environment' | 'fog', string>>\n readonly metrics: Readonly<Record<'state' | 'hour' | 'rain' | 'visibility' | 'sight' | 'hearing' | 'wind' | 'heat_index' | 'wetness' | 'strikes' | 'blend' | 'temperature', string>>\n readonly scenarios: Readonly<Record<'storm' | 'blend' | 'determinism' | 'dry_ground', string>>\n /** Names of the states and climates by id; the bench falls back to the id. */\n readonly states: Readonly<Record<string, string>>\n}\n\nconst EN: WeatherBenchText = {\n group: 'Weather',\n name: 'Weather area',\n controls: { state: 'Weather', transition: 'Transition', time_of_day: 'Time of day', auto_schedule: 'Automatic schedule', seed: 'Seed' },\n hints: {\n transition: 'How long the change to the chosen weather takes, in real seconds.',\n time_of_day: 'Hour of the day (the world restarts the clock there and keeps the weather).',\n auto_schedule: 'On: the climate changes the weather by itself and the clock runs 600 times faster than real time. Off: the weather stays until you change it.',\n seed: 'The same seed gives the same schedule and the same lightning.',\n },\n options: { instant: 'At once', ten_seconds: '10 seconds' },\n layers: { environment: 'Write host environment', fog: 'Fog in the scene' },\n metrics: {\n state: 'Weather',\n hour: 'Hour',\n rain: 'Rain',\n visibility: 'Visibility',\n sight: 'Sight scale',\n hearing: 'Hearing scale',\n wind: 'Wind',\n heat_index: 'Heat index',\n wetness: 'Ground wetness',\n strikes: 'Lightning strikes',\n blend: 'Blend',\n temperature: 'Temperature',\n },\n scenarios: {\n storm: 'A storm sees less and is heard less than a clear day, and strikes lightning',\n blend: 'A change blends over its time and settles in the new weather',\n determinism: 'The same seed gives the same day, another seed another one',\n dry_ground: 'Rain wets the ground and it dries after the rain stops',\n },\n states: {\n clear: 'Clear',\n overcast: 'Overcast',\n light_rain: 'Light rain',\n heavy_rain: 'Heavy rain',\n storm: 'Storm',\n fog: 'Fog',\n windy: 'Windy',\n cyclone: 'Cyclone',\n typhoon: 'Typhoon',\n extreme_heat: 'Extreme heat',\n },\n}\n\nconst PT_BR: WeatherBenchText = {\n group: 'Clima',\n name: 'Área de clima',\n controls: { state: 'Clima', transition: 'Transição', time_of_day: 'Hora do dia', auto_schedule: 'Sorteio automático', seed: 'Semente' },\n hints: {\n transition: 'Quanto demora a mudança para o clima escolhido, em segundos reais.',\n time_of_day: 'Hora do dia (o mundo reinicia o relógio nela e mantém o clima).',\n auto_schedule: 'Ligado: o clima do lugar muda sozinho e o relógio corre 600 vezes mais rápido que o real. Desligado: o clima fica até você trocar.',\n seed: 'A mesma semente dá o mesmo sorteio e os mesmos raios.',\n },\n options: { instant: 'De uma vez', ten_seconds: '10 segundos' },\n layers: { environment: 'Escrever no ambiente do host', fog: 'Névoa na cena' },\n metrics: {\n state: 'Clima',\n hour: 'Hora',\n rain: 'Chuva',\n visibility: 'Visibilidade',\n sight: 'Escala de visão',\n hearing: 'Escala de audição',\n wind: 'Vento',\n heat_index: 'Índice de calor',\n wetness: 'Chão molhado',\n strikes: 'Raios',\n blend: 'Mistura',\n temperature: 'Temperatura',\n },\n scenarios: {\n storm: 'Tempestade enxerga e é ouvida menos que um dia limpo, e solta raios',\n blend: 'Uma mudança se mistura no tempo dela e assenta no clima novo',\n determinism: 'A mesma semente dá o mesmo dia, outra semente dá outro',\n dry_ground: 'A chuva molha o chão e ele seca depois que a chuva para',\n },\n states: {\n clear: 'Limpo',\n overcast: 'Nublado',\n light_rain: 'Chuva fraca',\n heavy_rain: 'Chuva forte',\n storm: 'Tempestade',\n fog: 'Neblina',\n windy: 'Ventania',\n cyclone: 'Ciclone',\n typhoon: 'Tufão',\n extreme_heat: 'Calor extremo',\n },\n}\n\nexport const weatherBenchTextOf = (locale: string): WeatherBenchText => (locale === 'en' ? EN : PT_BR)\n","import type { BenchChange, ModuleControl, ModuleHost, ModuleLayer, ModuleMetric, ModuleScenario, TestableModule } from '@adatechnology/game-contracts'\n\nimport { createWeatherBridges, environmentOf } from '../bridges'\nimport type { WeatherBridges, WeatherTargets } from '../bridges'\nimport type { WeatherSoundOptions } from '../audio/sound'\nimport { createWeather } from '../weather'\nimport type { Weather, WeatherOptions } from '../weather'\nimport type { Strike, WeatherSample } from '../types'\nimport { weatherBenchTextOf } from './locale'\nimport type { WeatherBenchText } from './locale'\n\n/** What a renderer of the weather (game-weather-three) gives the bench: its layers, a step per frame and the switch of each layer. */\nexport type WeatherVisual = {\n update(dt: number): void\n setLayer(id: string, on: boolean): void\n dispose(): void\n}\n\n/** The bench hands a visual the weather it shows (always the live one, even after the bench restarts it) and what the room lends. */\nexport type WeatherVisualContext = { readonly host: ModuleHost; readonly locale: string; readonly weather: { sample(): WeatherSample } }\n\n/** The bench declares its layers before the room lends anything, so the factory tells them first (`fog` is the bench's own layer and reaches the visual through `setLayer` too). */\nexport type WeatherVisualFactory = {\n layers(locale: string): readonly ModuleLayer[]\n create(context: WeatherVisualContext): WeatherVisual\n}\n\nexport type WeatherTestModuleOptions = WeatherOptions & {\n locale?: string\n /** Text of a state id in the game's words; without it the bench uses its own names, then the id. */\n translate?: (key: string, locale: string) => string | undefined\n /** The weather to test (default a new one built from the other options). */\n weather?: Weather\n /** Whether the scene fog follows the weather at first (default true; the layer can be switched either way). A room that is not about weather starts it off. */\n fog?: boolean\n /** The packages the weather drives besides the host's environment bus and sound (fluids film, interactables, vegetation, vfx), from the example. */\n targets?: Omit<WeatherTargets, 'environment' | 'audio'>\n /** The rain, wind and thunder on the host's `audio`; `false` keeps the area silent. */\n sound?: WeatherSoundOptions | false\n /** The picture of the weather (rain, fog, sky, lightning, headlights, haze), from `@adatechnology/game-weather-three`. With it the bench leaves the scene fog to the visual. */\n visual?: WeatherVisualFactory\n}\n\n/** What the scenarios use of the context the test room passes. */\nexport interface WeatherScenarioLike {\n expect(condition: boolean, label: string, data?: Record<string, unknown>): void\n}\n\nexport type WeatherTestModule = TestableModule<WeatherScenarioLike> & {\n /** The weather in use (replaced when the bench changes the seed or the hour). */\n readonly weather: Weather\n}\n\nconst FAST_SCALE = 600\nconst NORMAL_SCALE = 72\nconst BLEND_SECONDS = 10\nconst HOURS_PER_DAY = 24\nconst FOG_NEAR = 1\n\ntype FogLike = new (color: number, near: number, far: number) => { far: number }\ntype SceneLike = { fog?: unknown }\ntype ThreeLike = { Fog?: FogLike }\n\n/**\n * The weather area of a test room, written against the generic contracts only: it drives a `createWeather` world, writes the result into the host's\n * environment bus (`host.environment`) every frame and shows the numbers a game reads from it. It also sets the scene fog from the weather's render fog.\n * Pure: no three.js beyond the host's own `Fog`, and the sky, rain, lightning and sound wait for the packages that draw and play them.\n */\nexport function createWeatherTestModule(options: WeatherTestModuleOptions = {}): WeatherTestModule {\n const locale = options.locale ?? 'pt-BR'\n const text: WeatherBenchText = weatherBenchTextOf(locale)\n const { locale: _locale, translate, weather: given, fog: _fog, targets: _targets, sound: _sound, visual: _visual, ...weatherOptions } = options\n void _locale\n void _fog\n void _targets\n void _sound\n void _visual\n const state = {\n seed: options.seed ?? 1,\n hour: options.startHour ?? 8,\n transition: 0,\n auto: options.autoSchedule ?? false,\n environment: true,\n fog: options.fog ?? true,\n }\n let host: ModuleHost | null = null\n let strikes = 0\n let offStrike: (() => void) | undefined\n let bridges: WeatherBridges | undefined\n let visual: WeatherVisual | undefined\n let weather: Weather = given ?? createWeather({ ...weatherOptions, autoSchedule: state.auto, ...(state.auto ? { timeScale: FAST_SCALE } : {}) })\n\n const watch = (): void => {\n offStrike?.()\n offStrike = weather.on('strike', (_strike: Strike) => void (strikes += 1))\n }\n watch()\n\n const nameOf = (id: string): string => translate?.(`weather.${id}`, locale) ?? text.states[id] ?? id\n\n // the world restarts with the new seed or hour and keeps the weather it was in\n const rebuild = (): void => {\n const current = weather.state()\n weather = createWeather({ ...weatherOptions, seed: state.seed, start: current, startHour: state.hour, autoSchedule: state.auto, timeScale: state.auto ? FAST_SCALE : NORMAL_SCALE })\n strikes = 0\n watch()\n bridges?.bind(weather)\n }\n\n const applyFog = (far: number): void => {\n const scene = host?.scene as SceneLike | undefined\n const Fog = (host?.THREE as ThreeLike | undefined)?.Fog\n if (!scene || typeof Fog !== 'function') return\n const fog = scene.fog as { far: number } | undefined | null\n if (fog && typeof fog.far === 'number') fog.far = far\n else scene.fog = new Fog(0xa8b4c0, FOG_NEAR, far)\n }\n\n const publish = (): void => {\n const sample = weather.sample()\n if (state.environment) host?.environment?.set(environmentOf(sample))\n if (state.fog && !visual) applyFog(sample.fogFar)\n }\n\n const onChange = (change: BenchChange): void => {\n if (change.kind === 'layer') {\n if (change.id === 'environment' || change.id === 'fog') state[change.id] = change.on\n visual?.setLayer(change.id, change.on)\n return\n }\n if (change.kind === 'action') return\n const { id, value } = change\n if (id === 'state' && typeof value === 'string') weather.force(value, state.transition)\n else if (id === 'transition' && typeof value === 'string') state.transition = value === 'instant' ? 0 : BLEND_SECONDS\n else if (id === 'time_of_day' && typeof value === 'number') {\n state.hour = value\n rebuild()\n } else if (id === 'auto_schedule' && typeof value === 'boolean') {\n state.auto = value\n weather.setAutoSchedule(value)\n weather.setTimeScale(value ? FAST_SCALE : NORMAL_SCALE)\n } else if (id === 'seed' && typeof value === 'number') {\n state.seed = value\n rebuild()\n }\n }\n\n const controls = (): ModuleControl[] => [\n { kind: 'choice', id: 'state', name: text.controls.state, options: weather.registry.stateIds().map((id) => ({ id, name: nameOf(id) })), default: weather.state() },\n {\n kind: 'choice',\n id: 'transition',\n name: text.controls.transition,\n hint: text.hints.transition,\n options: [\n { id: 'instant', name: text.options.instant },\n { id: 'ten_seconds', name: text.options.ten_seconds },\n ],\n default: 'instant',\n },\n { kind: 'number', id: 'time_of_day', name: text.controls.time_of_day, hint: text.hints.time_of_day, unit: 'h', min: 0, max: HOURS_PER_DAY - 1, step: 1, default: state.hour },\n { kind: 'boolean', id: 'auto_schedule', name: text.controls.auto_schedule, hint: text.hints.auto_schedule, default: state.auto },\n { kind: 'number', id: 'seed', name: text.controls.seed, hint: text.hints.seed, min: 1, max: 9999, step: 1, default: state.seed },\n ]\n\n const layers = (): ModuleLayer[] => [\n { id: 'environment', name: text.layers.environment },\n { id: 'fog', name: text.layers.fog, default: state.fog },\n ...(options.visual?.layers(locale) ?? []),\n ]\n\n const metrics = (): ModuleMetric[] => [\n { id: 'current_state', name: text.metrics.state, read: () => nameOf(weather.state()) },\n { id: 'hour', name: text.metrics.hour, unit: 'h', digits: 1, read: () => weather.sample().hour },\n { id: 'blend', name: text.metrics.blend, digits: 2, read: () => weather.sample().blend },\n { id: 'rain', name: text.metrics.rain, unit: 'mm/h', digits: 1, read: () => weather.sample().rain },\n { id: 'visibility', name: text.metrics.visibility, unit: 'm', digits: 0, read: () => weather.sample().effects.visibility },\n { id: 'sight', name: text.metrics.sight, digits: 2, read: () => weather.sample().effects.sightScale },\n { id: 'hearing', name: text.metrics.hearing, digits: 2, read: () => weather.sample().effects.hearingScale },\n { id: 'wind', name: text.metrics.wind, unit: 'm/s', digits: 1, read: () => weather.sample().windSpeed },\n { id: 'temperature', name: text.metrics.temperature, unit: '°C', digits: 1, read: () => weather.sample().temperatureC },\n { id: 'heat_index', name: text.metrics.heat_index, unit: '°C', digits: 1, read: () => weather.sample().effects.heatIndexC },\n { id: 'wetness', name: text.metrics.wetness, digits: 2, read: () => weather.sample().groundWetness },\n { id: 'strikes', name: text.metrics.strikes, digits: 0, read: () => strikes },\n ]\n\n // each scenario runs its own worlds, so the bench's live one is not touched\n const fresh = (extra: WeatherOptions = {}): Weather => createWeather({ ...weatherOptions, autoSchedule: false, ...extra })\n const run = (world: Weather, seconds: number): void => {\n for (let elapsed = 0; elapsed < seconds; elapsed += 0.5) world.advance(0.5)\n }\n\n const scenarios = (): Array<ModuleScenario<WeatherScenarioLike>> => [\n {\n id: 'storm',\n name: text.scenarios.storm,\n run: ({ expect }) => {\n const clear = fresh({ seed: 3, start: 'clear' })\n const storm = fresh({ seed: 3, start: 'storm' })\n let hits = 0\n storm.on('strike', () => void (hits += 1))\n run(storm, 120)\n const calm = clear.sample().effects\n const rough = storm.sample().effects\n expect(rough.visibility < calm.visibility, 'a storm sees less far', { storm: rough.visibility, clear: calm.visibility })\n expect(rough.hearingScale < calm.hearingScale, 'rain masks sound', { storm: rough.hearingScale, clear: calm.hearingScale })\n expect(hits > 0, 'a storm strikes lightning', { strikes: hits })\n },\n },\n {\n id: 'blend',\n name: text.scenarios.blend,\n run: ({ expect }) => {\n const world = fresh({ seed: 3, start: 'clear' })\n world.force('heavy_rain', 10)\n run(world, 5)\n const middle = world.sample()\n expect(middle.blend > 0 && middle.blend < 1, 'halfway through the change it is still blending', { blend: middle.blend })\n expect(middle.rain > 0 && middle.rain < 15, 'the rain is between the two weathers', { rain: middle.rain })\n run(world, 6)\n expect(world.sample().blend === 1 && world.sample().state === 'heavy_rain', 'after its time it has settled', { blend: world.sample().blend })\n },\n },\n {\n id: 'determinism',\n name: text.scenarios.determinism,\n run: ({ expect }) => {\n const day = (seed: number): string => JSON.stringify(createWeather({ ...weatherOptions, seed }).timeline(48).samples)\n expect(day(5) === day(5), 'the same seed gives the same two days')\n expect(day(5) !== day(6), 'another seed gives another one')\n },\n },\n {\n id: 'dry_ground',\n name: text.scenarios.dry_ground,\n run: ({ expect }) => {\n const world = fresh({ seed: 3, start: 'heavy_rain' })\n run(world, 60)\n const wet = world.sample().groundWetness\n expect(wet > 0.3, 'rain wets the ground', { wetness: wet })\n world.force('clear', 0)\n run(world, 600)\n expect(world.sample().groundWetness < wet, 'it dries after the rain stops', { wet, after: world.sample().groundWetness })\n },\n },\n ]\n\n const module: WeatherTestModule = {\n id: 'weather_area',\n name: text.name,\n group: text.group,\n get weather() {\n return weather\n },\n items: () => [],\n controls: () => controls(),\n layers: () => layers(),\n metrics: () => metrics(),\n scenarios: () => scenarios(),\n attach(lent) {\n host = lent\n const off = lent.bench?.onChange(onChange)\n bridges = createWeatherBridges({ ...options.targets, ...(lent.audio ? { audio: lent.audio } : {}) }, { sound: options.sound ?? {} })\n bridges.bind(weather)\n visual = options.visual?.create({ host: lent, locale, weather: { sample: () => weather.sample() } })\n if (visual && !state.fog) visual.setLayer('fog', false)\n publish()\n const offFrame = lent.onFrame((dt) => {\n weather.advance(dt)\n publish()\n bridges?.update(dt)\n visual?.update(dt)\n })\n return () => {\n visual?.dispose()\n visual = undefined\n off?.()\n offFrame()\n bridges?.dispose()\n bridges = 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;;;ACEO,MAAM,mBAA6C;AAAA,IACxD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEO,WAAS,SAAS,OAAkC;AACzD,UAAM,SAAiC,CAAC;AACxC,eAAW,OAAO,iBAAkB,QAAO,GAAG,IAAI,MAAM,GAAG;AAC3D,WAAO;AAAA,EACT;AAGO,WAAS,YAAY,MAAmB,IAAiB,UAA+B;AAC7F,UAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,GAAG,QAAQ,CAAC;AAChD,UAAM,UAAkC,CAAC;AACzC,eAAW,OAAO,iBAAkB,SAAQ,GAAG,IAAI,KAAK,GAAG,KAAK,GAAG,GAAG,IAAI,KAAK,GAAG,KAAK;AACvF,WAAO;AAAA,EACT;;;ACpCO,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAEzB,MAAM,qBAAqB,mBAAmB;AAErD,M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