Cut 5d-1: Haven audio curation, WetMix PcmSynth, WalkerFootstepTracker & ArenaAudioSystem

This commit is contained in:
Meta Vens 2026-12-05 10:05:12 +01:00
commit 7f811c3011
41 changed files with 3067 additions and 10 deletions

View file

@ -40,6 +40,11 @@ royale, aliens, language design). This repo holds no lore.
`mech_paint.gdshader`, `PomDecalPool` combat scars, tactical radar,
clickable Aetheria Hardpoint & Heat schematic, and Imperial Broadcast chyron.
- Sion terrain and building data attribution: `"Federal Office of Topography swisstopo"`.
- Hybrid 3D combat audio (`ArenaAudioSystem` + `ProceduralAudioBank` + `WalkerFootstepTracker`):
curated weapon/mechanical WAVs by **Haven Kendrick** (`assets/audio/haven/`,
see [`assets/audio/ATTRIBUTION.md`](assets/audio/ATTRIBUTION.md)) paired with
deterministic `PcmSynth` GRF-synced footsteps, vehicle/servo loops, impacts,
and 2D UI cues behind a separable `WetMixMode` room stage.
## Build, test, and run
@ -59,7 +64,3 @@ godot --path client
# Run the headless Godot smoke test
godot --headless --path client res://tests/Smoke.tscn
```
## Planned, not live yet
- Multiplayer networking and audio synthesis.

View file

@ -0,0 +1,47 @@
# Audio Attribution & Migration Notes
## Curated Weapon & Mechanical Sound Effects (`assets/audio/haven/`)
- **Author / Source:** **Haven Kendrick** (Cult member) — *MWO Soundpack* (original weapon and mechanical sound effects, used with explicit permission).
- **Modifications applied by `tools/audio/curate_haven_audio.py`:**
- Converted to mono `44,100 Hz` `16-bit` signed PCM WAV (`RIFF/WAVE`).
- Trimmed leading silence / sliced sustained loops into crisp single-shot and burst windows with smooth cosine fade-outs (`30-50 ms`).
- Peak-normalized to `0.89` (`-1.0 dBFS`).
- **Explicitly excluded:** All third-party/stock-named files in the source folder (`SW01_*`, `MW4 - *`, `Utilities-*`, `desktop.ini`) were excluded and never copied.
### Curated Clip Manifest (25 files)
| Destination (`assets/audio/haven/`) | Source File | Role |
|---|---|---|
| `mg_shot_01.wav` | `ClanMG3_fixed.wav` | 7.62 MG shot variant A (`0.24 s`) |
| `mg_shot_02.wav` | `New_MG 2.wav` | 7.62 MG shot variant B (`0.24 s`) |
| `mg_tail.wav` | `mgtail.wav` | MG mechanical receiver tail (`0.66 s`) |
| `ac_light_01.wav` | `AC5.wav` | Light autocannon variant A (`0.85 s`) |
| `ac_light_02.wav` | `AC5_2.wav` | Light autocannon variant B (`0.80 s`) |
| `ac_med_01.wav` | `AC10.wav` | Medium autocannon (`0.95 s`) |
| `ac_rotary.wav` | `RAC5.wav` | Rotary autocannon (`1.01 s`) |
| `flak_blast_01.wav` | `ClanLBX7_2019.wav` | Flak scattergun variant A (`1.15 s`) |
| `flak_blast_02.wav` | `IS_LBX20_2.wav` | Flak scattergun variant B (`1.35 s`) |
| `cannon_heavy_01.wav` | `BigCannon1.wav` | 105mm Recoilless / heavy cannon A (`1.80 s`) |
| `cannon_heavy_02.wav` | `AC20.wav` | 105mm Recoilless / heavy cannon B (`1.50 s`) |
| `pd_bark_01.wav` | `AMS3.wav` | Point-defense flak bark A (`0.28 s`) |
| `pd_bark_02.wav` | `amsTP.wav` | Point-defense flak bark B (`0.28 s`) |
| `pd_laser.wav` | `laserams.wav` | Imperial Aegis PD pulse (`0.32 s`) |
| `rocket_salvo_01.wav` | `MRM1.wav` | Rocket/missile salvo A (`1.20 s`) |
| `rocket_salvo_02.wav` | `NEWSRM1.wav` | Rocket/missile salvo B (`1.35 s`) |
| `plasma_ppc_01.wav` | `Snub_PPC2.wav` | Touring Plasma Repeater A (`1.25 s`) |
| `plasma_ppc_02.wav` | `PPcSWEET.wav` | Touring Plasma Repeater B (`0.78 s`) |
| `lance_beam_01.wav` | `CPPC_DEC2018_2.wav` | Gilded Thermal Lance (`1.55 s`) |
| `laser_heavy_01.wav` | `CLL3.wav` | Heavy laser (reserved for Cut 7) (`1.20 s`) |
| `gauss_rail_01.wav` | `Gauss Sweet 1.wav` | Gauss rifle (reserved for Cut 7) (`1.15 s`) |
| `mech_reload_bolt.wav` | `CannonReload2.wav` | Heavy chassis swap bolt-clank (`1.25 s`) |
| `mech_quick_bolt.wav` | `reload.wav` | Module equip latch (`0.94 s`) |
| `mech_eject.wav` | `eject.wav` | Ruin / casing ejection clatter (`0.74 s`) |
| `mech_turret_servo.wav` | `turret9.wav` | Turret traverse mechanical accent (`1.10 s`) |
## Procedural Synth & `WetMixMode` Dry-Mode Migration Plan
`RustToDust.Core.Audio.PcmSynth` synthesizes all non-weapon audio cues (GRF-synced mech footsteps, engine/rotor/servo loops, metallic ricochets, armor/core impacts, explosions, and 2D UI feedback) as **pure dry mono 44.1 kHz PCM buffers first**, then passes them through a cleanly separable `WetMixMode` post-stage:
- **`WetMixMode = true` (current default):** Applies early reflections (`11-43 ms` taps), a short diffused room tail, and gentle `tanh` soft-clipping so procedural footsteps, impacts, and loops sit cohesively alongside Haven's pre-reverbed weapon recordings.
- **`WetMixMode = false` (future acoustic raycast DSP):** Bypasses the baked room stage and returns the dry PCM buffers untouched so an audio raytracer / convolution reverb bus can compute per-ray canyon and city-corridor reflections dynamically without double-reverberating procedural sources.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

1081
client/ArenaAudioSystem.cs Normal file

File diff suppressed because it is too large Load diff

View file

@ -24,6 +24,7 @@ public partial class Main : Node3D
private TerrainRenderer _terrain = null!;
private SionMapRenderer _sionMap = null!;
private ArenaRenderer _arena = null!;
private ArenaAudioSystem _audio = null!;
private Camera3D _camera = null!;
private Hud _hud = null!;
private DirectionalLight3D _sun = null!;
@ -32,6 +33,9 @@ public partial class Main : Node3D
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private readonly WalkerFootstepTracker _footsteps = new();
private readonly List<ISimEvent> _frameEvents = new(128);
private readonly List<FootstepPulse> _frameFootsteps = new(32);
private ArenaMapKind _mapKind = ArenaMapKind.Sion;
private string _callsign = "Pilot";
private string _lastEndpoint = $"127.0.0.1:{DefaultNetPort}";
@ -74,6 +78,8 @@ public partial class Main : Node3D
public TerrainRenderer Terrain => _terrain;
public SionMapRenderer SionMap => _sionMap;
public ArenaRenderer Arena => _arena;
public ArenaAudioSystem Audio => _audio;
public WalkerFootstepTracker Footsteps => _footsteps;
public Hud Hud => _hud;
public ArenaMapKind MapKind => _mapKind;
public ArenaMapKind? InitialMapKindOverride { get; set; }
@ -94,6 +100,9 @@ public partial class Main : Node3D
_arena = new ArenaRenderer { Name = "Arena" };
AddChild(_arena);
_audio = new ArenaAudioSystem { Name = "ArenaAudio" };
AddChild(_audio);
_camera = new Camera3D
{
Name = "ShoulderCamera",
@ -392,6 +401,10 @@ public partial class Main : Node3D
_cameraPitch = _mapKind == ArenaMapKind.Sion ? Mathf.DegToRad(5f) : Mathf.DegToRad(12f);
_cameraZoom = 1.0f;
_lastCamChassisId = null;
_footsteps.Clear();
_frameEvents.Clear();
_frameFootsteps.Clear();
_audio.ClearAll();
}
_camera.Far = _mapKind == ArenaMapKind.Sion ? 4200f : 1800f;
@ -711,6 +724,7 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta, alpha);
StepAudioAndFootsteps((float)delta, alpha);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
@ -763,6 +777,7 @@ public partial class Main : Node3D
}
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
UpdateCamera((float)delta, alpha);
StepAudioAndFootsteps((float)delta, alpha);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
@ -775,6 +790,43 @@ public partial class Main : Node3D
}
}
private void StepAudioAndFootsteps(float dt, float alpha)
{
if (_session is null)
{
return;
}
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
_frameFootsteps.Clear();
_footsteps.StepSession(_session, dt, alpha, _frameFootsteps, ResolveLiveWalkerFootWorld);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, dt, alpha);
}
private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex)
{
VehicleVisualInstance? vis = isContender
? _arena.GetContenderVisual(id)
: _arena.GetSpectatorVisual(id);
if (vis is null || vis.IsStaticLod || vis.RigState?.WalkerRig is not { } rig)
{
return null;
}
if ((uint)legIndex >= (uint)rig.Legs.Length)
{
return null;
}
Node3D footNode = rig.Legs[legIndex].Foot.Node;
if (!GodotObject.IsInstanceValid(footNode) || !footNode.IsInsideTree())
{
return null;
}
Vector3 p = footNode.GlobalPosition;
return new System.Numerics.Vector3(p.X, p.Y, p.Z);
}
private void PrintPerfSummaryAndQuit()
{
static double Avg(List<double> v)

View file

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.IO;
using Godot;
using RustToDust.Core;
using RustToDust.Core.Audio;
namespace RustToDust.Client;
/// <summary>
/// Owns all immutable <see cref="AudioStreamWav"/> assets built once at client startup:
/// 25 curated Haven Kendrick WAVs from <c>assets/audio/haven/</c> plus all deterministic
/// <see cref="PcmSynth"/> procedural clips (with separable <see cref="WetMixMode"/>).
/// Zero <c>.import</c> sidecar dependency.
/// </summary>
public sealed class ProceduralAudioBank
{
public static readonly string[] ExpectedHavenClips =
{
"mg_shot_01", "mg_shot_02", "mg_tail",
"ac_light_01", "ac_light_02", "ac_med_01", "ac_rotary",
"flak_blast_01", "flak_blast_02", "cannon_heavy_01", "cannon_heavy_02",
"pd_bark_01", "pd_bark_02", "pd_laser",
"rocket_salvo_01", "rocket_salvo_02",
"plasma_ppc_01", "plasma_ppc_02", "lance_beam_01", "laser_heavy_01", "gauss_rail_01",
"mech_reload_bolt", "mech_quick_bolt", "mech_eject", "mech_turret_servo"
};
private readonly Dictionary<string, AudioStreamWav> _streams = new(StringComparer.OrdinalIgnoreCase);
public ProceduralAudioBank(bool wetMixMode = true, string? havenDirOverride = null)
{
WetMixMode = wetMixMode;
LoadHavenClips(havenDirOverride ?? LocateHavenAudioDirectory());
BuildProceduralClips(wetMixMode);
}
public bool WetMixMode { get; private set; }
public int HavenClipCount { get; private set; }
public int ProceduralClipCount { get; private set; }
public int TotalClipCount => _streams.Count;
public bool TryGetStream(string key, out AudioStreamWav stream) =>
_streams.TryGetValue(key, out stream!);
public AudioStreamWav GetStream(string key) =>
_streams.TryGetValue(key, out var stream)
? stream
: throw new KeyNotFoundException($"Missing audio clip '{key}' in ProceduralAudioBank.");
public void RebuildProcedural(bool wetMixMode)
{
WetMixMode = wetMixMode;
BuildProceduralClips(wetMixMode);
}
public static string LocateHavenAudioDirectory()
{
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
string havenDir = Path.Combine(assetsDir, "audio", "haven");
if (!Directory.Exists(havenDir))
{
throw new DirectoryNotFoundException($"Curated Haven audio directory not found: {havenDir}");
}
return havenDir;
}
private void LoadHavenClips(string havenDir)
{
int loaded = 0;
for (int i = 0; i < ExpectedHavenClips.Length; i++)
{
string key = ExpectedHavenClips[i];
string path = Path.Combine(havenDir, key + ".wav");
if (!File.Exists(path))
{
throw new FileNotFoundException($"Missing curated Haven WAV '{path}'.", path);
}
WavPcmInfo wav = WavFileReader.ReadMonoOrStereo16(path);
var stream = new AudioStreamWav
{
Format = AudioStreamWav.FormatEnum.Format16Bits,
MixRate = wav.SampleRate,
Stereo = wav.Channels == 2,
LoopMode = AudioStreamWav.LoopModeEnum.Disabled,
Data = wav.PcmBytes
};
_streams[key] = stream;
loaded++;
}
HavenClipCount = loaded;
}
private void BuildProceduralClips(bool wetMixMode)
{
Dictionary<string, PcmClipData> clips = PcmSynth.SynthesizeAll(wetMixMode);
int count = 0;
foreach (var kv in clips)
{
PcmClipData clip = kv.Value;
var stream = new AudioStreamWav
{
Format = AudioStreamWav.FormatEnum.Format16Bits,
MixRate = clip.SampleRate,
Stereo = false,
LoopMode = clip.IsLoop ? AudioStreamWav.LoopModeEnum.Forward : AudioStreamWav.LoopModeEnum.Disabled,
LoopBegin = 0,
LoopEnd = clip.IsLoop ? clip.Samples.Length : 0,
Data = clip.Pcm16Bytes
};
_streams[clip.Key] = stream;
count++;
}
ProceduralClipCount = count;
}
}

View file

@ -0,0 +1,196 @@
using System;
using System.Collections.Generic;
using System.Numerics;
using RustToDust.Core;
using RustToDust.Ymir;
namespace RustToDust.Client;
public readonly record struct FootstepPulse(
bool IsContender,
int EntityId,
int LegIndex,
string ChassisId,
float MassKg,
float LoadG,
Vector3 WorldPos);
/// <summary>
/// Tracks per-walker leg GRF hysteresis (<c>LoadG</c> arming &lt; 0.10, touchdown &gt;= 0.24,
/// 0.18 s cooldown) from interpolated <see cref="WalkerVisualSnapshot"/>s across both Solo and
/// Multiplayer (<see cref="IClientArenaSession"/>). Zero Godot dependency so xUnit and headless
/// Godot tests run the exact same edge detector.
/// </summary>
public sealed class WalkerFootstepTracker
{
public const float ArmLoadGThreshold = 0.10f;
public const float TriggerLoadGThreshold = 0.24f;
public const float LegCooldownSec = 0.18f;
private struct LegHysteresis
{
public bool Armed;
public float Cooldown;
}
private sealed class WalkerTrackState
{
public string ChassisId = string.Empty;
public int LegCount;
public readonly LegHysteresis[] Legs = new LegHysteresis[4];
}
private readonly Dictionary<(bool IsContender, int Id), WalkerTrackState> _walkers = new();
public int TrackedWalkerCount => _walkers.Count;
public void Clear() => _walkers.Clear();
public void StepSession(
IClientArenaSession session,
float dt,
float alpha,
List<FootstepPulse> outPulses,
Func<bool, int, int, Vector3?>? resolveLiveFootWorld = null)
{
var state = session.ViewState;
var contenders = state.Contenders;
for (int i = 0; i < contenders.Count; i++)
{
var c = contenders[i];
if (!c.Alive || !c.Grid.Spec.IsWalker || !session.IsContenderVisible(c.Id))
{
_walkers.Remove((true, c.Id));
continue;
}
if (!session.TrySampleInterpolatedWalkerPose(true, c.Id, alpha, out var snap))
{
continue;
}
StepActor(
isContender: true,
entityId: c.Id,
chassisId: c.Grid.Spec.Id,
massKg: c.Grid.Spec.MassKg,
in snap,
state.Terrain,
dt,
outPulses,
resolveLiveFootWorld);
}
var specs = state.Spectators.Spectators;
for (int i = 0; i < specs.Count; i++)
{
var s = specs[i];
if (!s.Alive || !s.Grid.Spec.IsWalker || !session.IsSpectatorVisible(s.Id))
{
_walkers.Remove((false, s.Id));
continue;
}
if (!session.TrySampleInterpolatedWalkerPose(false, s.Id, alpha, out var snap))
{
continue;
}
StepActor(
isContender: false,
entityId: s.Id,
chassisId: s.Grid.Spec.Id,
massKg: s.Grid.Spec.MassKg,
in snap,
state.Terrain,
dt,
outPulses,
resolveLiveFootWorld);
}
}
public void StepActor(
bool isContender,
int entityId,
string chassisId,
float massKg,
in WalkerVisualSnapshot snap,
TerrainField terrain,
float dt,
List<FootstepPulse> outPulses,
Func<bool, int, int, Vector3?>? resolveLiveFootWorld = null)
{
int legCount = Math.Clamp(snap.LegCount, 0, 4);
if (legCount == 0)
{
return;
}
var key = (isContender, entityId);
if (!_walkers.TryGetValue(key, out var track) ||
!string.Equals(track.ChassisId, chassisId, StringComparison.OrdinalIgnoreCase) ||
track.LegCount != legCount)
{
track = new WalkerTrackState
{
ChassisId = chassisId,
LegCount = legCount
};
// First sighting initializes Armed = false for zero spawn / swap pop
_walkers[key] = track;
return;
}
float stepDt = MathF.Max(0f, dt);
WalkerGeometrySpec? geom = null;
float geomScale = snap.GeomScale > 0.01f ? snap.GeomScale : 1f;
Quaternion comRot = snap.ComRot.LengthSquared() > 1e-6f
? Quaternion.Normalize(snap.ComRot)
: Quaternion.Identity;
for (int i = 0; i < legCount; i++)
{
ref LegHysteresis leg = ref track.Legs[i];
if (leg.Cooldown > 0f)
{
leg.Cooldown = MathF.Max(0f, leg.Cooldown - stepDt);
}
float loadG = snap.LoadG[i];
if (loadG < ArmLoadGThreshold)
{
leg.Armed = true;
continue;
}
if (leg.Armed && loadG >= TriggerLoadGThreshold && leg.Cooldown <= 0f)
{
leg.Armed = false;
leg.Cooldown = LegCooldownSec;
Vector3? liveFoot = resolveLiveFootWorld?.Invoke(isContender, entityId, i);
Vector3 footWorld;
if (liveFoot.HasValue)
{
float fy = terrain.SampleHeight(liveFoot.Value.X, liveFoot.Value.Z);
footWorld = new Vector3(liveFoot.Value.X, fy, liveFoot.Value.Z);
}
else
{
geom ??= WalkerGeometrySpec.GetForChassis(chassisId);
Vector2 restXZ = geom.Legs[i].RestFootXZ * geomScale;
Vector3 offset = Vector3.Transform(new Vector3(restXZ.X, 0f, restXZ.Y), comRot);
float fx = snap.ComPos.X + offset.X;
float fz = snap.ComPos.Z + offset.Z;
float fy = terrain.SampleHeight(fx, fz);
footWorld = new Vector3(fx, fy, fz);
}
outPulses.Add(new FootstepPulse(
isContender,
entityId,
i,
chassisId,
massKg,
loadG,
footWorld));
}
}
}
}

View file

@ -1283,6 +1283,116 @@ public partial class Smoke : Node
Check(remoteIface.LocalContender.Alive, "Expected loopback RemoteArenaSession LocalContender alive");
}
// 14. Cut 5d-1: Headless AudioBank, voice-cap/priority/dedupe, and mass-scaled GRF footstep pitch falsification
{
var audio = _main.Audio;
audio.EnsureInitialized();
Check(audio.Bank.HavenClipCount == 25, $"Expected 25 curated Haven clips in ProceduralAudioBank, got {audio.Bank.HavenClipCount}");
Check(audio.Bank.ProceduralClipCount == 18, $"Expected 18 procedural clips in ProceduralAudioBank, got {audio.Bank.ProceduralClipCount}");
audio.ClearAll();
audio.ResetStatsForTest();
var localC = _main.Session.LocalContender;
Vector3 listener = new(localC.X, localC.Y, localC.Z);
var burstEvents = new List<ISimEvent>();
// Local player shot first (priority 10)
burstEvents.Add(new ShotFiredEvent
{
TracerId = 90001,
IsSpectatorShooter = false,
ShooterId = _main.Session.LocalContenderId,
StartX = listener.X,
StartY = listener.Y + 1f,
StartZ = listener.Z,
EndX = listener.X + 40f,
EndY = listener.Y + 1f,
EndZ = listener.Z,
WeaponClass = (byte)WeaponVisualClass.KineticLight,
WeaponId = "mg_762"
});
// 5-pellet flak salvo from contender 1 -> must dedupe to 1 audio voice
for (int p = 0; p < 5; p++)
{
burstEvents.Add(new ShotFiredEvent
{
TracerId = 90010 + p,
IsSpectatorShooter = false,
ShooterId = 1,
StartX = listener.X + 18f,
StartY = listener.Y + 1f,
StartZ = listener.Z,
EndX = listener.X,
EndY = listener.Y + 1f,
EndZ = listener.Z,
WeaponClass = (byte)WeaponVisualClass.Explosive,
WeaponId = "flak"
});
}
// 30 simultaneous distant AI shots (>150m, <240m) trying to saturate all 19 one-shot voices
for (int a = 2; a < 32; a++)
{
burstEvents.Add(new ShotFiredEvent
{
TracerId = 90100 + a,
IsSpectatorShooter = false,
ShooterId = a,
StartX = listener.X + 175f,
StartY = listener.Y + 1f,
StartZ = listener.Z + (a % 5),
EndX = listener.X,
EndY = listener.Y + 1f,
EndZ = listener.Z,
WeaponClass = (byte)WeaponVisualClass.Autocannon,
WeaponId = "autocannon"
});
}
// 1 event beyond MaxAudioDistance (260m) -> must be culled (0 voices)
burstEvents.Add(new ShotFiredEvent
{
TracerId = 90999,
IsSpectatorShooter = false,
ShooterId = 99,
StartX = listener.X + 320f,
StartY = listener.Y + 1f,
StartZ = listener.Z,
EndX = listener.X,
EndY = listener.Y + 1f,
EndZ = listener.Z,
WeaponClass = (byte)WeaponVisualClass.Explosive,
WeaponId = "recoilless"
});
audio.ConsumeSimEvents(_main.Session, burstEvents, listener);
Check(audio.Active3DVoiceCount <= ArenaAudioSystem.Total3DVoiceCount,
$"Active 3D voices exceeded 24 cap: {audio.Active3DVoiceCount}");
Check(audio.ActiveOneShotVoiceCount == ArenaAudioSystem.OneShotVoiceCount,
$"Expected 19 saturated one-shot voices, got {audio.ActiveOneShotVoiceCount}");
Check(audio.DedupedCount == 4,
$"Expected 5-pellet flak salvo to dedupe 4 pellets, got DedupedCount={audio.DedupedCount}");
Check(audio.RejectedDistanceCount == 1,
$"Expected >260m event to be distance-culled, got RejectedDistanceCount={audio.RejectedDistanceCount}");
Check(audio.HasActiveVoiceForSource(isLocalSource: true, sourceEntityId: _main.Session.LocalContenderId),
"Expected local player priority-10 voice never to be stolen by distant AI shots");
// Footstep mass-scaled pitch verification: Bastion (4600 kg) pitch < Kestrel (1650 kg) pitch
audio.ClearAll();
var kestrelPulse = new FootstepPulse(true, 0, 0, "kestrel", Catalog.Kestrel.MassKg, 1.0f, new System.Numerics.Vector3(listener.X, listener.Y, listener.Z));
audio.ConsumeFootsteps(new[] { kestrelPulse }, _main.Session.LocalContenderId, listener);
float? kestrelPitch = audio.GetLastPitchForClipPrefix("footstep_");
var bastionPulse = new FootstepPulse(true, 1, 0, "bastion", Catalog.Bastion.MassKg, 1.0f, new System.Numerics.Vector3(listener.X + 10f, listener.Y, listener.Z));
audio.ConsumeFootsteps(new[] { bastionPulse }, _main.Session.LocalContenderId, listener);
float? bastionPitch = audio.GetLastPitchForClipPrefix("footstep_heavy_");
Check(kestrelPitch.HasValue && bastionPitch.HasValue && bastionPitch.Value < kestrelPitch.Value,
$"Expected Bastion pitch ({bastionPitch}) < Kestrel pitch ({kestrelPitch})");
GD.Print($"SMOKE INFO: Audio verified (haven={audio.Bank.HavenClipCount}, proc={audio.Bank.ProceduralClipCount}, dummy={audio.IsDummyAudio}, kestrelPitch={kestrelPitch:F3}, bastionPitch={bastionPitch:F3})");
}
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
}

View file

@ -0,0 +1,860 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace RustToDust.Core.Audio
{
public enum ProceduralCueId
{
FootstepHeavyThud,
FootstepMedStep,
FootstepLightStep,
LoopEngineWheeled,
LoopEngineTracked,
LoopEngineHover,
LoopRotorVtol,
LoopMechServo,
ImpactRicochet,
ImpactArmorCrunch,
ImpactCore,
ImpactExplosion,
UiHitArmor,
UiHitCore,
UiHitKill,
UiOverheatAlarm,
UiPickupModule,
UiPickupImperial
}
public sealed record PcmClipData(
string Key,
ProceduralCueId CueId,
bool IsLoop,
int SampleRate,
float[] Samples,
byte[] Pcm16Bytes,
int DrySampleCount);
public readonly record struct WavPcmInfo(
int SampleRate,
int Channels,
int BitsPerSample,
byte[] PcmBytes,
float[] FloatSamples);
public static class WavFileReader
{
public static WavPcmInfo ReadMonoOrStereo16(string path)
{
byte[] raw = File.ReadAllBytes(path);
return Parse(raw, path);
}
public static WavPcmInfo Parse(ReadOnlySpan<byte> raw, string sourceLabel = "<memory>")
{
if (raw.Length < 44)
{
throw new InvalidDataException($"WAV '{sourceLabel}' too short ({raw.Length} bytes).");
}
if (Encoding.ASCII.GetString(raw[0..4]) != "RIFF" ||
Encoding.ASCII.GetString(raw[8..12]) != "WAVE")
{
throw new InvalidDataException($"WAV '{sourceLabel}' missing RIFF/WAVE header.");
}
int offset = 12;
bool hasFmt = false;
bool hasData = false;
int audioFormat = 0;
int channels = 0;
int sampleRate = 0;
int bitsPerSample = 0;
byte[] pcmBytes = Array.Empty<byte>();
while (offset + 8 <= raw.Length)
{
string chunkId = Encoding.ASCII.GetString(raw.Slice(offset, 4));
int chunkSize = BitConverter.ToInt32(raw.Slice(offset + 4, 4));
int dataStart = offset + 8;
if (chunkSize < 0 || dataStart + chunkSize > raw.Length)
{
throw new InvalidDataException($"WAV '{sourceLabel}' has invalid chunk '{chunkId}' size {chunkSize}.");
}
if (chunkId == "fmt ")
{
if (chunkSize < 16)
{
throw new InvalidDataException($"WAV '{sourceLabel}' fmt chunk too small ({chunkSize}).");
}
audioFormat = BitConverter.ToUInt16(raw.Slice(dataStart, 2));
channels = BitConverter.ToUInt16(raw.Slice(dataStart + 2, 2));
sampleRate = BitConverter.ToInt32(raw.Slice(dataStart + 4, 4));
bitsPerSample = BitConverter.ToUInt16(raw.Slice(dataStart + 14, 2));
hasFmt = true;
}
else if (chunkId == "data")
{
pcmBytes = raw.Slice(dataStart, chunkSize).ToArray();
hasData = true;
}
int paddedSize = chunkSize + (chunkSize & 1);
offset = dataStart + paddedSize;
}
if (!hasFmt || !hasData)
{
throw new InvalidDataException($"WAV '{sourceLabel}' missing fmt or data chunk.");
}
if (audioFormat != 1 || bitsPerSample != 16)
{
throw new InvalidDataException($"WAV '{sourceLabel}' must be 16-bit PCM (got fmt={audioFormat}, bits={bitsPerSample}).");
}
int sampleCount = pcmBytes.Length / 2;
var floats = new float[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
short s = BitConverter.ToInt16(pcmBytes, i * 2);
floats[i] = s / 32768f;
}
return new WavPcmInfo(sampleRate, channels, bitsPerSample, pcmBytes, floats);
}
}
/// <summary>
/// Pure-C# deterministic 44.1 kHz mono PCM synthesizer with a cleanly separable
/// <c>wetMixMode</c> room/saturation post-stage. Zero Godot dependency so xUnit
/// and headless client tests validate the exact same waveforms.
/// </summary>
public static class PcmSynth
{
public const int SampleRate = 44100;
private const float MaxSafePeak = 0.92f;
private static readonly (ProceduralCueId Cue, string Key)[] AllCues =
{
(ProceduralCueId.FootstepHeavyThud, "footstep_heavy_thud"),
(ProceduralCueId.FootstepMedStep, "footstep_med_step"),
(ProceduralCueId.FootstepLightStep, "footstep_light_step"),
(ProceduralCueId.LoopEngineWheeled, "loop_engine_wheeled"),
(ProceduralCueId.LoopEngineTracked, "loop_engine_tracked"),
(ProceduralCueId.LoopEngineHover, "loop_engine_hover"),
(ProceduralCueId.LoopRotorVtol, "loop_rotor_vtol"),
(ProceduralCueId.LoopMechServo, "loop_mech_servo"),
(ProceduralCueId.ImpactRicochet, "impact_ricochet"),
(ProceduralCueId.ImpactArmorCrunch, "impact_armor_crunch"),
(ProceduralCueId.ImpactCore, "impact_core"),
(ProceduralCueId.ImpactExplosion, "impact_explosion"),
(ProceduralCueId.UiHitArmor, "ui_hit_armor"),
(ProceduralCueId.UiHitCore, "ui_hit_core"),
(ProceduralCueId.UiHitKill, "ui_hit_kill"),
(ProceduralCueId.UiOverheatAlarm, "ui_overheat_alarm"),
(ProceduralCueId.UiPickupModule, "ui_pickup_module"),
(ProceduralCueId.UiPickupImperial, "ui_pickup_imperial")
};
public static IReadOnlyList<(ProceduralCueId Cue, string Key)> CueRegistry => AllCues;
public static Dictionary<string, PcmClipData> SynthesizeAll(bool wetMixMode = true)
{
var dict = new Dictionary<string, PcmClipData>(AllCues.Length, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < AllCues.Length; i++)
{
var clip = Synthesize(AllCues[i].Cue, wetMixMode);
dict[clip.Key] = clip;
}
return dict;
}
public static PcmClipData Synthesize(ProceduralCueId cue, bool wetMixMode = true)
{
GenerateDry(cue, out float[] dry, out bool isLoop, out string key);
int dryLen = dry.Length;
float[] finalSamples;
if (wetMixMode)
{
finalSamples = ApplyWetRoomStage(dry, isLoop);
}
else
{
finalSamples = dry;
ClampNormalizePeak(finalSamples, MaxSafePeak);
}
byte[] pcmBytes = FloatToPcm16(finalSamples);
return new PcmClipData(key, cue, isLoop, SampleRate, finalSamples, pcmBytes, dryLen);
}
public static float[] ApplyWetRoomStage(ReadOnlySpan<float> dry, bool isLoop)
{
if (isLoop)
{
return ApplyWetRoomLoop(dry);
}
const int tailSamples = (int)(0.20f * SampleRate);
int outLen = dry.Length + tailSamples;
var wet = new float[outLen];
// Early reflections (11ms, 19ms, 29ms, 43ms)
ReadOnlySpan<int> tapDelays = stackalloc int[] { 485, 838, 1279, 1896 };
ReadOnlySpan<float> tapGains = stackalloc float[] { 0.30f, -0.24f, 0.19f, -0.14f };
// 4-comb Schroeder/Moorer diffused room tail with one-pole damping
ReadOnlySpan<int> combDelays = stackalloc int[] { 1327, 1621, 1949, 2269 };
ReadOnlySpan<float> combGains = stackalloc float[] { 0.72f, 0.69f, 0.66f, 0.63f };
var combBuf0 = new float[combDelays[0]];
var combBuf1 = new float[combDelays[1]];
var combBuf2 = new float[combDelays[2]];
var combBuf3 = new float[combDelays[3]];
int idx0 = 0, idx1 = 0, idx2 = 0, idx3 = 0;
float lp0 = 0f, lp1 = 0f, lp2 = 0f, lp3 = 0f;
const int apDelay = 347;
var apBuf = new float[apDelay];
int apIdx = 0;
for (int i = 0; i < outLen; i++)
{
float d = i < dry.Length ? dry[i] : 0f;
float early = 0f;
for (int t = 0; t < tapDelays.Length; t++)
{
int srcIdx = i - tapDelays[t];
if (srcIdx >= 0 && srcIdx < dry.Length)
{
early += dry[srcIdx] * tapGains[t];
}
}
float c0 = combBuf0[idx0];
lp0 = lp0 * 0.42f + c0 * 0.58f;
combBuf0[idx0] = d + lp0 * combGains[0];
idx0 = (idx0 + 1) % combDelays[0];
float c1 = combBuf1[idx1];
lp1 = lp1 * 0.42f + c1 * 0.58f;
combBuf1[idx1] = d + lp1 * combGains[1];
idx1 = (idx1 + 1) % combDelays[1];
float c2 = combBuf2[idx2];
lp2 = lp2 * 0.42f + c2 * 0.58f;
combBuf2[idx2] = d + lp2 * combGains[2];
idx2 = (idx2 + 1) % combDelays[2];
float c3 = combBuf3[idx3];
lp3 = lp3 * 0.42f + c3 * 0.58f;
combBuf3[idx3] = d + lp3 * combGains[3];
idx3 = (idx3 + 1) % combDelays[3];
float combSum = (c0 + c1 + c2 + c3) * 0.25f;
// Allpass diffusion
float apOut = apBuf[apIdx];
float apIn = combSum + apOut * 0.45f;
apBuf[apIdx] = apIn;
float diffused = apOut - apIn * 0.45f;
apIdx = (apIdx + 1) % apDelay;
float mixed = d * 0.92f + early * 0.46f + diffused * 0.44f;
wet[i] = MathF.Tanh(mixed * 1.12f);
}
// Smooth 16ms cosine fade on very end of tail so no abrupt cut
int fadeLen = Math.Min(tailSamples, (int)(0.016f * SampleRate));
int fadeStart = outLen - fadeLen;
for (int i = 0; i < fadeLen; i++)
{
float g = 0.5f * (1f + MathF.Cos(MathF.PI * (i + 1) / fadeLen));
wet[fadeStart + i] *= g;
}
ClampNormalizePeak(wet, MaxSafePeak);
return wet;
}
private static float[] ApplyWetRoomLoop(ReadOnlySpan<float> dry)
{
int len = dry.Length;
var wet = new float[len];
// Circular early reflections + 2-tap circular diffusion preserve exact periodicity at wrap (sample N-1 -> 0)
ReadOnlySpan<int> taps = stackalloc int[] { 331, 617, 1019, 1511 };
ReadOnlySpan<float> gains = stackalloc float[] { 0.16f, -0.12f, 0.09f, -0.06f };
float lp = 0f;
for (int pass = 0; pass < 2; pass++)
{
for (int i = 0; i < len; i++)
{
float d = dry[i];
float room = 0f;
for (int t = 0; t < taps.Length; t++)
{
int src = (i - taps[t] + len) % len;
room += dry[src] * gains[t];
}
lp = lp * 0.65f + room * 0.35f;
float mixed = d * 0.90f + room * 0.55f + lp * 0.40f;
wet[i] = MathF.Tanh(mixed * 1.08f);
}
}
ClampNormalizePeak(wet, MaxSafePeak);
return wet;
}
private static void GenerateDry(ProceduralCueId cue, out float[] buf, out bool isLoop, out string key)
{
switch (cue)
{
case ProceduralCueId.FootstepHeavyThud:
key = "footstep_heavy_thud";
isLoop = false;
buf = GenFootstep(durSec: 0.38f, fStart: 88f, fEnd: 32f, clackFreq: 380f, clackMix: 0.22f, gravelMix: 0.34f, seed: 101u);
break;
case ProceduralCueId.FootstepMedStep:
key = "footstep_med_step";
isLoop = false;
buf = GenFootstep(durSec: 0.30f, fStart: 112f, fEnd: 40f, clackFreq: 520f, clackMix: 0.28f, gravelMix: 0.28f, seed: 102u);
break;
case ProceduralCueId.FootstepLightStep:
key = "footstep_light_step";
isLoop = false;
buf = GenFootstep(durSec: 0.24f, fStart: 135f, fEnd: 48f, clackFreq: 690f, clackMix: 0.36f, gravelMix: 0.22f, seed: 103u);
break;
case ProceduralCueId.LoopEngineWheeled:
key = "loop_engine_wheeled";
isLoop = true;
buf = GenLoopWheeled();
break;
case ProceduralCueId.LoopEngineTracked:
key = "loop_engine_tracked";
isLoop = true;
buf = GenLoopTracked();
break;
case ProceduralCueId.LoopEngineHover:
key = "loop_engine_hover";
isLoop = true;
buf = GenLoopHover();
break;
case ProceduralCueId.LoopRotorVtol:
key = "loop_rotor_vtol";
isLoop = true;
buf = GenLoopVtol();
break;
case ProceduralCueId.LoopMechServo:
key = "loop_mech_servo";
isLoop = true;
buf = GenLoopServo();
break;
case ProceduralCueId.ImpactRicochet:
key = "impact_ricochet";
isLoop = false;
buf = GenRicochet();
break;
case ProceduralCueId.ImpactArmorCrunch:
key = "impact_armor_crunch";
isLoop = false;
buf = GenArmorCrunch();
break;
case ProceduralCueId.ImpactCore:
key = "impact_core";
isLoop = false;
buf = GenCoreImpact();
break;
case ProceduralCueId.ImpactExplosion:
key = "impact_explosion";
isLoop = false;
buf = GenExplosion();
break;
case ProceduralCueId.UiHitArmor:
key = "ui_hit_armor";
isLoop = false;
buf = GenUiHitArmor();
break;
case ProceduralCueId.UiHitCore:
key = "ui_hit_core";
isLoop = false;
buf = GenUiHitCore();
break;
case ProceduralCueId.UiHitKill:
key = "ui_hit_kill";
isLoop = false;
buf = GenUiHitKill();
break;
case ProceduralCueId.UiOverheatAlarm:
key = "ui_overheat_alarm";
isLoop = false;
buf = GenUiOverheatAlarm();
break;
case ProceduralCueId.UiPickupModule:
key = "ui_pickup_module";
isLoop = false;
buf = GenUiPickupModule();
break;
case ProceduralCueId.UiPickupImperial:
key = "ui_pickup_imperial";
isLoop = false;
buf = GenUiPickupImperial();
break;
default:
throw new ArgumentOutOfRangeException(nameof(cue), cue, null);
}
}
private static float[] GenFootstep(
float durSec,
float fStart,
float fEnd,
float clackFreq,
float clackMix,
float gravelMix,
uint seed)
{
int n = (int)(durSec * SampleRate);
var s = new float[n];
uint rng = seed;
float phase = 0f;
float lp = 0f;
float hpPrev = 0f;
float hpOut = 0f;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float envAttack = MathF.Min(1f, t / 0.004f);
float subEnv = envAttack * MathF.Exp(-t * (10.5f / durSec * 0.38f));
float freq = fEnd + (fStart - fEnd) * MathF.Exp(-t * 28f);
phase += MathF.Tau * freq / SampleRate;
float sub = MathF.Sin(phase) * subEnv;
float clackEnv = envAttack * MathF.Exp(-t * 48f);
float clack = (MathF.Sin(MathF.Tau * clackFreq * t) + 0.5f * MathF.Sin(MathF.Tau * clackFreq * 1.47f * t)) * clackEnv;
float white = NextSignedNoise(ref rng);
lp = lp * 0.84f + white * 0.16f;
hpOut = 0.90f * (hpOut + lp - hpPrev);
hpPrev = lp;
float gravelEnv = envAttack * MathF.Exp(-t * 16f);
float damperHiss = white * 0.12f * MathF.Exp(-t * 11f);
float fadeOut = u > 0.85f ? (1f - (u - 0.85f) / 0.15f) : 1f;
s[i] = (sub * 0.82f + clack * clackMix + hpOut * gravelMix + damperHiss) * fadeOut;
}
NormalizePeak(s, 0.86f);
return s;
}
private static float[] GenLoopWheeled()
{
int n = SampleRate;
var s = new float[n];
float[] noise = GeneratePeriodicFilteredNoise(n, 0x201u, lpAlpha: 0.06f);
for (int i = 0; i < n; i++)
{
float t = i / (float)n;
// Integer harmonic cosines -> exact 1.000s periodicity with zero-slope wrap
float baseOsc =
MathF.Cos(MathF.Tau * 42f * t) * 0.48f +
MathF.Cos(MathF.Tau * 84f * t) * 0.30f +
MathF.Cos(MathF.Tau * 126f * t) * 0.18f +
MathF.Cos(MathF.Tau * 168f * t) * 0.10f;
float lfo = 0.82f + 0.18f * MathF.Cos(MathF.Tau * 14f * t);
s[i] = baseOsc * lfo + noise[i] * 0.22f;
}
NormalizePeak(s, 0.78f);
return s;
}
private static float[] GenLoopTracked()
{
int n = SampleRate;
var s = new float[n];
float[] noise = GeneratePeriodicFilteredNoise(n, 0x202u, lpAlpha: 0.10f);
for (int i = 0; i < n; i++)
{
float t = i / (float)n;
float diesel =
MathF.Cos(MathF.Tau * 32f * t) * 0.52f +
MathF.Cos(MathF.Tau * 64f * t) * 0.34f +
MathF.Cos(MathF.Tau * 96f * t) * 0.20f +
MathF.Cos(MathF.Tau * 160f * t) * 0.10f;
float treadMod = 0.5f + 0.5f * MathF.Cos(MathF.Tau * 18f * t);
float treadClick = MathF.Pow(treadMod, 4f) * MathF.Cos(MathF.Tau * 240f * t) * 0.22f;
s[i] = diesel * (0.85f + 0.15f * treadMod) + treadClick + noise[i] * 0.25f;
}
NormalizePeak(s, 0.80f);
return s;
}
private static float[] GenLoopHover()
{
int n = SampleRate;
var s = new float[n];
float[] noise = GeneratePeriodicFilteredNoise(n, 0x203u, lpAlpha: 0.20f);
for (int i = 0; i < n; i++)
{
float t = i / (float)n;
float turbine =
MathF.Cos(MathF.Tau * 55f * t) * 0.36f +
MathF.Cos(MathF.Tau * 110f * t) * 0.26f +
MathF.Cos(MathF.Tau * 220f * t) * 0.14f;
s[i] = turbine + noise[i] * 0.28f;
}
NormalizePeak(s, 0.72f);
return s;
}
private static float[] GenLoopVtol()
{
int n = SampleRate;
var s = new float[n];
float[] noise = GeneratePeriodicFilteredNoise(n, 0x204u, lpAlpha: 0.15f);
for (int i = 0; i < n; i++)
{
float t = i / (float)n;
float chop = 0.55f + 0.45f * MathF.Cos(MathF.Tau * 16f * t);
float thump = MathF.Cos(MathF.Tau * 32f * t) * 0.40f + MathF.Cos(MathF.Tau * 64f * t) * 0.24f;
float whine = MathF.Cos(MathF.Tau * 210f * t) * 0.24f + MathF.Cos(MathF.Tau * 420f * t) * 0.10f;
s[i] = (thump + noise[i] * 0.42f) * chop + whine;
}
NormalizePeak(s, 0.80f);
return s;
}
private static float[] GenLoopServo()
{
int n = SampleRate;
var s = new float[n];
float[] noise = GeneratePeriodicFilteredNoise(n, 0x205u, lpAlpha: 0.28f);
for (int i = 0; i < n; i++)
{
float t = i / (float)n;
float hum =
MathF.Cos(MathF.Tau * 140f * t) * 0.34f +
MathF.Cos(MathF.Tau * 280f * t) * 0.26f +
MathF.Cos(MathF.Tau * 420f * t) * 0.10f;
float pulse = 0.88f + 0.12f * MathF.Cos(MathF.Tau * 6f * t);
s[i] = hum * pulse + noise[i] * 0.24f;
}
NormalizePeak(s, 0.74f);
return s;
}
private static float[] GenRicochet()
{
int n = (int)(0.22f * SampleRate);
var s = new float[n];
float p1 = 0f;
float p2 = 0f;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float attack = MathF.Min(1f, t / 0.002f);
float env = attack * MathF.Exp(-t * 18f);
float f1 = 1650f + 420f * MathF.Exp(-t * 32f);
float f2 = 2480f + 580f * MathF.Exp(-t * 28f);
float fm = MathF.Sin(MathF.Tau * 410f * t) * 0.35f * MathF.Exp(-t * 20f);
p1 += MathF.Tau * f1 / SampleRate;
p2 += MathF.Tau * f2 / SampleRate;
float fadeOut = u > 0.82f ? (1f - (u - 0.82f) / 0.18f) : 1f;
s[i] = (MathF.Sin(p1 + fm) * 0.58f + MathF.Sin(p2) * 0.42f) * env * fadeOut;
}
NormalizePeak(s, 0.82f);
return s;
}
private static float[] GenArmorCrunch()
{
int n = (int)(0.30f * SampleRate);
var s = new float[n];
uint rng = 0x302u;
float phase = 0f;
float lp = 0f;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float attack = MathF.Min(1f, t / 0.003f);
float freq = 52f + 88f * MathF.Exp(-t * 30f);
phase += MathF.Tau * freq / SampleRate;
float body = MathF.Sin(phase) * MathF.Exp(-t * 14f);
float clang = (MathF.Sin(MathF.Tau * 610f * t) + 0.6f * MathF.Sin(MathF.Tau * 945f * t)) * MathF.Exp(-t * 26f);
float white = NextSignedNoise(ref rng);
lp = lp * 0.78f + white * 0.22f;
float crunch = lp * MathF.Exp(-t * 17f);
float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f;
s[i] = attack * (body * 0.68f + clang * 0.28f + crunch * 0.55f) * fadeOut;
}
NormalizePeak(s, 0.86f);
return s;
}
private static float[] GenCoreImpact()
{
int n = (int)(0.34f * SampleRate);
var s = new float[n];
uint rng = 0x303u;
float phase = 0f;
float lp = 0f;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float attack = MathF.Min(1f, t / 0.0025f);
float freq = 38f + 72f * MathF.Exp(-t * 24f);
phase += MathF.Tau * freq / SampleRate;
float punch = MathF.Sin(phase) * MathF.Exp(-t * 11f);
float snap = MathF.Sin(MathF.Tau * 1180f * t) * MathF.Exp(-t * 34f);
float white = NextSignedNoise(ref rng);
lp = lp * 0.82f + white * 0.18f;
float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f;
s[i] = attack * (punch * 0.76f + snap * 0.34f + lp * 0.45f * MathF.Exp(-t * 14f)) * fadeOut;
}
NormalizePeak(s, 0.88f);
return s;
}
private static float[] GenExplosion()
{
int n = (int)(1.15f * SampleRate);
var s = new float[n];
uint rng = 0x304u;
float phase = 0f;
float lp = 0f;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float attack = MathF.Min(1f, t / 0.006f);
float freq = 22f + 43f * MathF.Exp(-t * 9f);
phase += MathF.Tau * freq / SampleRate;
float sub = MathF.Sin(phase) * MathF.Exp(-t * 3.8f);
float white = NextSignedNoise(ref rng);
lp = lp * 0.88f + white * 0.12f;
float roar = lp * MathF.Exp(-t * 3.1f);
float crackle = white * 0.25f * MathF.Exp(-t * 9.5f);
float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f;
s[i] = attack * (sub * 0.70f + roar * 0.78f + crackle) * fadeOut;
}
NormalizePeak(s, 0.88f);
return s;
}
private static float[] GenUiHitArmor()
{
int n = (int)(0.07f * SampleRate);
var s = new float[n];
uint rng = 0x401u;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 58f);
float tone = MathF.Sin(MathF.Tau * 1380f * t) * 0.65f + MathF.Sin(MathF.Tau * 2240f * t) * 0.35f;
float tick = NextSignedNoise(ref rng) * 0.30f * MathF.Exp(-t * 90f);
float fadeOut = u > 0.78f ? (1f - (u - 0.78f) / 0.22f) : 1f;
s[i] = (tone * env + tick) * fadeOut;
}
NormalizePeak(s, 0.80f);
return s;
}
private static float[] GenUiHitCore()
{
int n = (int)(0.11f * SampleRate);
var s = new float[n];
uint rng = 0x402u;
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float env = MathF.Min(1f, t / 0.0015f) * MathF.Exp(-t * 36f);
float tone =
MathF.Sin(MathF.Tau * 420f * t) * 0.50f +
MathF.Sin(MathF.Tau * 1080f * t) * 0.45f +
MathF.Sin(MathF.Tau * 1760f * t) * 0.25f;
float crunch = NextSignedNoise(ref rng) * 0.25f * MathF.Exp(-t * 60f);
float fadeOut = u > 0.80f ? (1f - (u - 0.80f) / 0.20f) : 1f;
s[i] = (tone * env + crunch) * fadeOut;
}
NormalizePeak(s, 0.84f);
return s;
}
private static float[] GenUiHitKill()
{
int n = (int)(0.22f * SampleRate);
var s = new float[n];
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float g1 = MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 24f);
float t2 = t - 0.075f;
float g2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 18f) : 0f;
float tone1 = MathF.Sin(MathF.Tau * 740f * t) + 0.35f * MathF.Sin(MathF.Tau * 1480f * t);
float tone2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1110f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2220f * t2)) : 0f;
float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f;
s[i] = (tone1 * g1 * 0.55f + tone2 * g2 * 0.65f) * fadeOut;
}
NormalizePeak(s, 0.85f);
return s;
}
private static float[] GenUiOverheatAlarm()
{
int n = (int)(0.42f * SampleRate);
var s = new float[n];
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
// Dual-pulse cockpit buzzer
float pulseA = (t < 0.16f) ? MathF.Sin(MathF.PI * (t / 0.16f)) : 0f;
float tB = t - 0.21f;
float pulseB = (tB >= 0f && tB < 0.17f) ? MathF.Sin(MathF.PI * (tB / 0.17f)) : 0f;
float env = pulseA + pulseB;
float wave =
MathF.Sin(MathF.Tau * 880f * t) * 0.55f +
MathF.Sin(MathF.Tau * 1175f * t) * 0.45f;
float fadeOut = u > 0.90f ? (1f - (u - 0.90f) / 0.10f) : 1f;
s[i] = wave * env * fadeOut;
}
NormalizePeak(s, 0.78f);
return s;
}
private static float[] GenUiPickupModule()
{
int n = (int)(0.18f * SampleRate);
var s = new float[n];
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float clunk = MathF.Sin(MathF.Tau * 240f * t) * MathF.Min(1f, t / 0.002f) * MathF.Exp(-t * 32f);
float t2 = t - 0.055f;
float latch = t2 >= 0f
? (MathF.Sin(MathF.Tau * 580f * t2) + 0.4f * MathF.Sin(MathF.Tau * 870f * t2)) * MathF.Min(1f, t2 / 0.002f) * MathF.Exp(-t2 * 26f)
: 0f;
float fadeOut = u > 0.84f ? (1f - (u - 0.84f) / 0.16f) : 1f;
s[i] = (clunk * 0.65f + latch * 0.55f) * fadeOut;
}
NormalizePeak(s, 0.82f);
return s;
}
private static float[] GenUiPickupImperial()
{
int n = (int)(0.28f * SampleRate);
var s = new float[n];
for (int i = 0; i < n; i++)
{
float t = i / (float)SampleRate;
float u = i / (float)(n - 1);
float e1 = MathF.Min(1f, t / 0.003f) * MathF.Exp(-t * 13f);
float t2 = t - 0.055f;
float e2 = t2 >= 0f ? MathF.Min(1f, t2 / 0.003f) * MathF.Exp(-t2 * 12f) : 0f;
float c1 = MathF.Sin(MathF.Tau * 880f * t) + 0.3f * MathF.Sin(MathF.Tau * 1760f * t);
float c2 = t2 >= 0f ? (MathF.Sin(MathF.Tau * 1320f * t2) + 0.35f * MathF.Sin(MathF.Tau * 2640f * t2)) : 0f;
float fadeOut = u > 0.86f ? (1f - (u - 0.86f) / 0.14f) : 1f;
s[i] = (c1 * e1 * 0.48f + c2 * e2 * 0.56f) * fadeOut;
}
NormalizePeak(s, 0.82f);
return s;
}
private static float[] GeneratePeriodicFilteredNoise(int n, uint seed, float lpAlpha)
{
int fade = Math.Min(2048, n / 4);
var raw = new float[n + fade];
uint rng = seed;
float lp = 0f;
float lp2 = 0f;
float smooth = Math.Clamp(lpAlpha, 0.02f, 0.12f);
for (int i = 0; i < raw.Length; i++)
{
float white = NextSignedNoise(ref rng);
lp = lp * (1f - smooth) + white * smooth;
lp2 = lp2 * 0.90f + lp * 0.10f;
raw[i] = lp2;
}
var result = new float[n];
Array.Copy(raw, result, n);
for (int i = 0; i < fade; i++)
{
float w = i / (float)fade;
result[i] = raw[i] * w + raw[n + i] * (1f - w);
}
return result;
}
private static float NextSignedNoise(ref uint state)
{
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
return ((state & 0xFFFFu) / 32767.5f) - 1f;
}
private static void NormalizePeak(float[] samples, float targetPeak)
{
float peak = 0f;
for (int i = 0; i < samples.Length; i++)
{
float a = MathF.Abs(samples[i]);
if (a > peak) peak = a;
}
if (peak > 1e-6f)
{
float scale = targetPeak / peak;
for (int i = 0; i < samples.Length; i++)
{
samples[i] *= scale;
}
}
}
private static void ClampNormalizePeak(float[] samples, float maxPeak)
{
float peak = 0f;
for (int i = 0; i < samples.Length; i++)
{
float a = MathF.Abs(samples[i]);
if (a > peak) peak = a;
}
if (peak > maxPeak && peak > 1e-6f)
{
float scale = maxPeak / peak;
for (int i = 0; i < samples.Length; i++)
{
samples[i] *= scale;
}
}
}
private static byte[] FloatToPcm16(ReadOnlySpan<float> samples)
{
var bytes = new byte[samples.Length * 2];
for (int i = 0; i < samples.Length; i++)
{
float clamped = Math.Clamp(samples[i], -1f, 1f);
short val = (short)MathF.Round(clamped * 32767f);
bytes[i * 2] = (byte)(val & 0xFF);
bytes[i * 2 + 1] = (byte)((val >> 8) & 0xFF);
}
return bytes;
}
}
}

View file

@ -50,6 +50,7 @@ namespace RustToDust.Core
void BeginRenderFrame(double dt, float physicsAlpha);
void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick);
void DrainSimEvents(List<ISimEvent> dest);
bool RequestEquipCargo(int cargoIndex, string hardpointId);
void RequestNewMatch(int seed, ArenaMapKind mapKind);

View file

@ -70,8 +70,10 @@ namespace RustToDust.Net
_host.StepOnce(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
}
public void DrainSimEvents(List<ISimEvent> dest) => _host.DrainHostEvents(dest);
public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
_host.Session.TryEquipCargo(0, cargoIndex, hardpointId);
_host.TryEquipHostCargo(cargoIndex, hardpointId);
public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
_host.ResetMatch(seed, mapKind);

View file

@ -48,6 +48,7 @@ namespace RustToDust.Net
private readonly Dictionary<int, List<WalkerSample>> _contenderWalkerTimelines = new();
private readonly Dictionary<int, List<WalkerSample>> _spectatorWalkerTimelines = new();
private readonly Dictionary<int, float> _pingSamples = new();
private readonly List<ISimEvent> _pendingClientEvents = new();
private MatchState _viewState;
private Box3DSoaWorld? _predWorld;
@ -238,6 +239,16 @@ namespace RustToDust.Net
}
}
public void DrainSimEvents(List<ISimEvent> dest)
{
if (_pendingClientEvents.Count == 0)
{
return;
}
dest.AddRange(_pendingClientEvents);
_pendingClientEvents.Clear();
}
public void SubmitLocalInput(in PlayerInput input, bool isPhysicsTick)
{
ObjectDisposedException.ThrowIf(_disposed, this);
@ -676,6 +687,7 @@ namespace RustToDust.Net
_prevInteractPressed = false;
_pendingChassisSwapSnap = false;
_unackedInputs.Clear();
_pendingClientEvents.Clear();
_predErrorPos = Vector3.Zero;
_predErrorRot = Quaternion.Identity;
Array.Clear(_lastCombatSpecSeenSeq);
@ -1324,6 +1336,11 @@ namespace RustToDust.Net
ApplyInitialMatchState(reset.FullInitialState, reset.AssignedContenderId);
break;
}
_pendingClientEvents.Add(batch.Events[i]);
}
if (_pendingClientEvents.Count > 4096)
{
_pendingClientEvents.RemoveRange(0, _pendingClientEvents.Count - 4096);
}
}

View file

@ -46,6 +46,7 @@ namespace RustToDust.Net
private readonly HashSet<CultNetRudpSocketServerPeer> _retiredTransportPeers = new();
private readonly Dictionary<Guid, (int SlotId, string Callsign)> _reconnectTokens = new();
private readonly List<ISimEvent> _stepEvents = new();
private readonly List<ISimEvent> _hostPendingEvents = new();
private readonly List<TerrainStampEvent> _terrainStampHistory = new();
private readonly int _maxHumans;
private readonly double _autoRestartSec;
@ -120,6 +121,27 @@ namespace RustToDust.Net
}
}
public void DrainHostEvents(List<ISimEvent> dest)
{
if (_hostPendingEvents.Count == 0)
{
return;
}
dest.AddRange(_hostPendingEvents);
_hostPendingEvents.Clear();
}
public bool TryEquipHostCargo(int cargoIndex, string hardpointId)
{
if (!_hostContenderId.HasValue) return false;
bool ok = _session.TryEquipCargo(_hostContenderId.Value, cargoIndex, hardpointId);
if (ok)
{
_session.DrainStepEvents(_hostPendingEvents);
}
return ok;
}
public void ResetMatch(int seed, ArenaMapKind mapKind)
{
if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count)
@ -133,6 +155,7 @@ namespace RustToDust.Net
_roundCompletedElapsed = 0f;
_terrainStampHistory.Clear();
_stepEvents.Clear();
_hostPendingEvents.Clear();
_reconnectTokens.Clear();
if (_hostContenderId.HasValue)
@ -180,6 +203,14 @@ namespace RustToDust.Net
_simTick++;
_session.DrainStepEvents(_stepEvents);
if (_hostContenderId.HasValue && _stepEvents.Count > 0)
{
_hostPendingEvents.AddRange(_stepEvents);
if (_hostPendingEvents.Count > 4096)
{
_hostPendingEvents.RemoveRange(0, _hostPendingEvents.Count - 4096);
}
}
for (int i = 0; i < _stepEvents.Count; i++)
{
if (_stepEvents[i] is TerrainStampEvent ts)

View file

@ -7,7 +7,7 @@ namespace RustToDust.Ymir
{
public sealed class LocalArenaSession : IClientArenaSession
{
private readonly List<ISimEvent> _discardEvents = new();
private readonly List<ISimEvent> _pendingEvents = new();
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null)
{
@ -55,16 +55,37 @@ namespace RustToDust.Ymir
}
Inner.SetHumanInput(0, input);
Inner.Step();
_discardEvents.Clear();
Inner.DrainStepEvents(_discardEvents);
Inner.DrainStepEvents(_pendingEvents);
if (_pendingEvents.Count > 4096)
{
_pendingEvents.RemoveRange(0, _pendingEvents.Count - 4096);
}
}
public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
Inner.TryEquipCargo(0, cargoIndex, hardpointId);
public void DrainSimEvents(List<ISimEvent> dest)
{
if (_pendingEvents.Count == 0)
{
return;
}
dest.AddRange(_pendingEvents);
_pendingEvents.Clear();
}
public bool RequestEquipCargo(int cargoIndex, string hardpointId)
{
bool ok = Inner.TryEquipCargo(0, cargoIndex, hardpointId);
if (ok)
{
Inner.DrainStepEvents(_pendingEvents);
}
return ok;
}
public void RequestNewMatch(int seed, ArenaMapKind mapKind)
{
string? name = LocalContender.Name;
_pendingEvents.Clear();
Inner.Dispose();
Inner = new ArenaSession(seed, mapKind, slot0Human: true);
if (!string.IsNullOrWhiteSpace(name))

View file

@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Numerics;
using RustToDust.Client;
using RustToDust.Core;
using RustToDust.Core.Audio;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
namespace RustToDust.Tests;
public sealed class AudioSynthTests
{
private static readonly string[] ExpectedHavenWavs =
{
"mg_shot_01.wav", "mg_shot_02.wav", "mg_tail.wav",
"ac_light_01.wav", "ac_light_02.wav", "ac_med_01.wav", "ac_rotary.wav",
"flak_blast_01.wav", "flak_blast_02.wav", "cannon_heavy_01.wav", "cannon_heavy_02.wav",
"pd_bark_01.wav", "pd_bark_02.wav", "pd_laser.wav",
"rocket_salvo_01.wav", "rocket_salvo_02.wav",
"plasma_ppc_01.wav", "plasma_ppc_02.wav", "lance_beam_01.wav", "laser_heavy_01.wav", "gauss_rail_01.wav",
"mech_reload_bolt.wav", "mech_quick_bolt.wav", "mech_eject.wav", "mech_turret_servo.wav"
};
private static string LocateAssetsAudioDir()
{
string vehiclesDir = VehicleCatalogLoader.LocateVehiclesDirectory();
string assetsDir = Directory.GetParent(vehiclesDir)?.FullName
?? throw new DirectoryNotFoundException("Could not locate assets directory.");
return Path.Combine(assetsDir, "audio");
}
[Fact]
public void CuratedHavenWavs_AreExactly25ValidMono44100PcmUnderBudgetWithZeroThirdPartyFiles()
{
string audioDir = LocateAssetsAudioDir();
string havenDir = Path.Combine(audioDir, "haven");
Assert.True(Directory.Exists(havenDir), $"Missing curated Haven directory: {havenDir}");
string[] allAudioFiles = Directory.GetFiles(audioDir, "*", SearchOption.AllDirectories);
foreach (string filePath in allAudioFiles)
{
string name = Path.GetFileName(filePath);
Assert.False(name.StartsWith("SW01_", StringComparison.OrdinalIgnoreCase), $"Forbidden SW01 file found: {name}");
Assert.False(name.StartsWith("MW4", StringComparison.OrdinalIgnoreCase), $"Forbidden MW4 file found: {name}");
Assert.False(name.StartsWith("Utilities", StringComparison.OrdinalIgnoreCase), $"Forbidden Utilities file found: {name}");
Assert.False(string.Equals(name, "desktop.ini", StringComparison.OrdinalIgnoreCase), $"Forbidden desktop.ini found: {filePath}");
}
string[] havenFiles = Directory.GetFiles(havenDir);
Assert.Equal(25, havenFiles.Length);
var actualNames = havenFiles.Select(Path.GetFileName).OrderBy(x => x, StringComparer.Ordinal).ToArray();
var expectedSorted = ExpectedHavenWavs.OrderBy(x => x, StringComparer.Ordinal).ToArray();
Assert.Equal(expectedSorted, actualNames);
long totalBytes = 0;
foreach (string wavPath in havenFiles)
{
totalBytes += new FileInfo(wavPath).Length;
WavPcmInfo info = WavFileReader.ReadMonoOrStereo16(wavPath);
Assert.Equal(44100, info.SampleRate);
Assert.Equal(1, info.Channels);
Assert.Equal(16, info.BitsPerSample);
Assert.True(info.FloatSamples.Length >= 4410, $"{Path.GetFileName(wavPath)} unexpectedly short.");
float peak = 0f;
double sumSq = 0.0;
for (int i = 0; i < info.FloatSamples.Length; i++)
{
float s = info.FloatSamples[i];
Assert.True(float.IsFinite(s));
float a = MathF.Abs(s);
if (a > peak) peak = a;
sumSq += s * s;
}
double rms = Math.Sqrt(sumSq / info.FloatSamples.Length);
Assert.True(rms > 0.01, $"{Path.GetFileName(wavPath)} is silent (RMS={rms:F5}).");
Assert.True(peak <= 0.95f, $"{Path.GetFileName(wavPath)} clips/exceeds 0.95 (peak={peak:F4}).");
}
Assert.True(totalBytes < 4L * 1024L * 1024L, $"Curated Haven WAV total size {totalBytes} bytes exceeds 4 MB.");
}
[Fact]
public void AttributionFile_ExistsAndCreditsHavenKendrick()
{
string attributionPath = Path.Combine(LocateAssetsAudioDir(), "ATTRIBUTION.md");
Assert.True(File.Exists(attributionPath), $"Missing attribution file: {attributionPath}");
string text = File.ReadAllText(attributionPath);
Assert.Contains("Haven Kendrick", text, StringComparison.Ordinal);
Assert.Contains("WetMixMode", text, StringComparison.Ordinal);
}
[Fact]
public void PcmSynth_AllCuesAreFiniteNonSilentNonClippingInBothWetAndDryModes_AndWetAddsTailEnergy()
{
Dictionary<string, PcmClipData> wetClips = PcmSynth.SynthesizeAll(wetMixMode: true);
Dictionary<string, PcmClipData> dryClips = PcmSynth.SynthesizeAll(wetMixMode: false);
Assert.Equal(PcmSynth.CueRegistry.Count, wetClips.Count);
Assert.Equal(PcmSynth.CueRegistry.Count, dryClips.Count);
foreach (var (_, key) in PcmSynth.CueRegistry)
{
PcmClipData wet = wetClips[key];
PcmClipData dry = dryClips[key];
Assert.Equal(44100, wet.SampleRate);
Assert.Equal(44100, dry.SampleRate);
Assert.Equal(wet.IsLoop, dry.IsLoop);
AssertValidPcmBounds(wet, key + " (wet)");
AssertValidPcmBounds(dry, key + " (dry)");
if (wet.IsLoop)
{
Assert.Equal(44100, wet.Samples.Length);
Assert.Equal(44100, dry.Samples.Length);
float wetWrapDiff = MathF.Abs(wet.Samples[^1] - wet.Samples[0]);
float dryWrapDiff = MathF.Abs(dry.Samples[^1] - dry.Samples[0]);
Assert.True(wetWrapDiff < 0.02f, $"Wet loop '{key}' wrap click: {wetWrapDiff:F5}");
Assert.True(dryWrapDiff < 0.02f, $"Dry loop '{key}' wrap click: {dryWrapDiff:F5}");
// Wet room stage alters loop signal measurably vs dry
double diffSq = 0.0;
for (int i = 0; i < wet.Samples.Length; i++)
{
double d = wet.Samples[i] - dry.Samples[i];
diffSq += d * d;
}
Assert.True(Math.Sqrt(diffSq / wet.Samples.Length) > 0.005, $"Wet loop '{key}' did not measurably differ from dry.");
}
else
{
// Wet one-shots carry real diffused reverb tail beyond the pure dry buffer length
// and measurably higher late/tail energy than the pure dry buffer.
Assert.True(wet.Samples.Length > dry.Samples.Length, $"Wet one-shot '{key}' should include reverb tail.");
int lateStart = (int)(dry.Samples.Length * 0.90);
double dryLateEnergy = 0.0;
for (int i = lateStart; i < dry.Samples.Length; i++)
{
dryLateEnergy += dry.Samples[i] * dry.Samples[i];
}
double wetLateEnergy = 0.0;
for (int i = lateStart; i < wet.Samples.Length; i++)
{
wetLateEnergy += wet.Samples[i] * wet.Samples[i];
}
double postDryEnergy = 0.0;
for (int i = dry.Samples.Length; i < wet.Samples.Length; i++)
{
postDryEnergy += wet.Samples[i] * wet.Samples[i];
}
Assert.True(postDryEnergy > 0.001, $"Wet one-shot '{key}' has zero post-dry tail energy ({postDryEnergy:F6}).");
Assert.True(wetLateEnergy > dryLateEnergy * 1.15 + 0.001,
$"Wet one-shot '{key}' lacks measurable reverb tail energy (dryLate={dryLateEnergy:F4}, wetLate={wetLateEnergy:F4}).");
}
}
}
[Fact]
public void WalkerFootstepTracker_TriggersStrictlyOnStanceTouchdownEdges()
{
var tracker = new WalkerFootstepTracker();
var terrain = new TerrainField(seed: 42);
var pulses = new List<FootstepPulse>();
var snap = new WalkerVisualSnapshot
{
LegCount = 2,
GeomScale = 1f,
ComPos = new Vector3(10f, 3f, 20f),
ComRot = Quaternion.Identity
};
// 1. Standing still with high load: first sighting + 20 frames -> 0 footsteps (no spawn pop, no spam)
snap.LoadG[0] = 1.0f;
snap.LoadG[1] = 1.0f;
for (int f = 0; f < 20; f++)
{
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
}
Assert.Empty(pulses);
// 2. Airborne (swing) across 20 frames -> 0 footsteps, legs become armed
snap.LoadG[0] = 0.0f;
snap.LoadG[1] = 0.0f;
for (int f = 0; f < 20; f++)
{
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
}
Assert.Empty(pulses);
// 3. Touchdown leg 0 rising across sub-frames -> fires EXACTLY ONCE
snap.LoadG[0] = 0.25f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
snap.LoadG[0] = 0.80f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
snap.LoadG[0] = 1.40f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 1f / 60f, pulses);
Assert.Single(pulses);
Assert.Equal(0, pulses[0].LegIndex);
Assert.InRange(MathF.Abs(pulses[0].WorldPos.Y - terrain.SampleHeight(pulses[0].WorldPos.X, pulses[0].WorldPos.Z)), 0f, 0.01f);
// 4. Re-arm and bounce faster than 0.18s cooldown -> suppressed by cooldown
pulses.Clear();
snap.LoadG[0] = 0.02f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
snap.LoadG[0] = 0.50f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
Assert.Empty(pulses);
// 5. After cooldown expires (> 0.18s), re-arm + touchdown fires again
snap.LoadG[0] = 0.02f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.20f, pulses);
snap.LoadG[0] = 0.60f;
tracker.StepActor(true, 0, "paladin", 4100f, in snap, terrain, 0.02f, pulses);
Assert.Single(pulses);
}
[Fact]
public void ClientArenaSession_DrainSimEvents_WorksInSoloAndLoopbackRemote()
{
using var local = new LocalArenaSession(seed: 42, ArenaMapKind.Desert, "AudioTester");
IClientArenaSession localIface = local;
var events = new List<ISimEvent>();
var player = local.Inner.State.Contenders[0];
var input = new PlayerInput(
Throttle: 0f,
Steer: 0f,
AimWorldX: player.X + 25f,
AimWorldZ: player.Z,
Fire: true,
InteractPickup: false,
Brake: false);
for (int i = 0; i < 10; i++)
{
localIface.SubmitLocalInput(in input, isPhysicsTick: true);
}
localIface.DrainSimEvents(events);
Assert.Contains(events, e => e is ShotFiredEvent s && !s.IsSpectatorShooter && s.ShooterId == 0);
// Draining again returns empty until new steps occur
events.Clear();
localIface.DrainSimEvents(events);
Assert.Empty(events);
// Loopback host + remote receives ShotFiredEvent through IClientArenaSession.DrainSimEvents
using var host = new ServerMatchHost(IPAddress.Loopback, port: 0, seed: 42, mapKind: ArenaMapKind.Desert);
using var remote = new RemoteArenaSession(new IPEndPoint(IPAddress.Loopback, host.BoundPort), "AudioRemote");
IClientArenaSession remoteIface = remote;
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
for (int t = 0; t < 15 && !remote.IsJoined; t++)
{
host.StepOnce(nowMs + t * 16);
remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f);
}
Assert.True(remote.IsJoined);
var rLocal = remoteIface.LocalContender;
var fireInput = new PlayerInput(0f, 0f, rLocal.X + 30f, rLocal.Z, true, false, false);
for (int t = 0; t < 10; t++)
{
remoteIface.SubmitLocalInput(in fireInput, isPhysicsTick: true);
host.StepOnce(nowMs + 300 + t * 16);
remoteIface.BeginRenderFrame(1.0 / 60.0, 1.0f);
}
events.Clear();
remoteIface.DrainSimEvents(events);
Assert.Contains(events, e => e is ShotFiredEvent);
}
private static void AssertValidPcmBounds(PcmClipData clip, string label)
{
Assert.True(clip.Samples.Length > 0, $"{label} empty");
float peak = 0f;
double sumSq = 0.0;
for (int i = 0; i < clip.Samples.Length; i++)
{
float s = clip.Samples[i];
Assert.True(float.IsFinite(s), $"{label} has non-finite sample at {i}");
float a = MathF.Abs(s);
if (a > peak) peak = a;
sumSq += s * s;
}
double rms = Math.Sqrt(sumSq / clip.Samples.Length);
Assert.True(rms > 0.01, $"{label} is silent (RMS={rms:F5})");
Assert.True(peak <= 0.98f, $"{label} clips (peak={peak:F4})");
}
}

View file

@ -14,6 +14,10 @@
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\client\WalkerFootstepTracker.cs" Link="Client\WalkerFootstepTracker.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RustToDust.Core\RustToDust.Core.csproj" />
<ProjectReference Include="..\..\src\RustToDust.Ymir\RustToDust.Ymir.csproj" />

View file

@ -0,0 +1,217 @@
#!/usr/bin/env python3
"""Curate 25 original Haven Kendrick MWO WAVs into mono 44.1 kHz 16-bit PCM WAVs.
Strictly read-only on D:\\Google Drive\\Gamecult\\Aetheria\\Audio\\WIP & Ideas\\Haven\\MWO Soundpack.
Explicitly excludes SW01_*, MW4*, Utilities-*, and desktop.ini.
"""
from __future__ import annotations
import array
import math
import os
import subprocess
import sys
import wave
from dataclasses import dataclass
from pathlib import Path
SOURCE_DIR = Path(r"D:\Google Drive\Gamecult\Aetheria\Audio\WIP & Ideas\Haven\MWO Soundpack")
REPO_ROOT = Path(__file__).resolve().parents[2]
DEST_DIR = REPO_ROOT / "assets" / "audio" / "haven"
TARGET_SAMPLE_RATE = 44100
TARGET_PEAK = 0.89
FORBIDDEN_PREFIXES = ("SW01_", "MW4", "Utilities-")
FORBIDDEN_EXACT = {"desktop.ini"}
@dataclass(frozen=True)
class ClipSpec:
dest_name: str
src_name: str
lead_trim_s: float
max_dur_s: float
fade_out_s: float
auto_trim_lead: bool = True
CLIPS: tuple[ClipSpec, ...] = (
# Machine guns (mg_762)
ClipSpec("mg_shot_01.wav", "ClanMG3_fixed.wav", 0.0, 0.24, 0.035),
ClipSpec("mg_shot_02.wav", "New_MG 2.wav", 0.0, 0.24, 0.035),
ClipSpec("mg_tail.wav", "mgtail.wav", 0.0, 0.66, 0.030),
# Autocannons (autocannon)
ClipSpec("ac_light_01.wav", "AC5.wav", 0.0, 0.85, 0.040),
ClipSpec("ac_light_02.wav", "AC5_2.wav", 0.065, 0.80, 0.040, auto_trim_lead=False),
ClipSpec("ac_med_01.wav", "AC10.wav", 0.0, 0.95, 0.040),
ClipSpec("ac_rotary.wav", "RAC5.wav", 0.0, 1.01, 0.040),
# Flak & heavy recoilless (flak, recoilless)
ClipSpec("flak_blast_01.wav", "ClanLBX7_2019.wav", 0.0, 1.15, 0.045),
ClipSpec("flak_blast_02.wav", "IS_LBX20_2.wav", 0.0, 1.35, 0.045),
ClipSpec("cannon_heavy_01.wav", "BigCannon1.wav", 0.070, 1.80, 0.050, auto_trim_lead=False),
ClipSpec("cannon_heavy_02.wav", "AC20.wav", 0.0, 1.50, 0.050),
# Point defense (pd_flak, aegis_pd)
ClipSpec("pd_bark_01.wav", "AMS3.wav", 0.0, 0.28, 0.030),
ClipSpec("pd_bark_02.wav", "amsTP.wav", 0.0, 0.28, 0.030),
ClipSpec("pd_laser.wav", "laserams.wav", 0.0, 0.32, 0.030),
# Missiles / Rockets (Cut 7)
ClipSpec("rocket_salvo_01.wav", "MRM1.wav", 0.0, 1.20, 0.045),
ClipSpec("rocket_salvo_02.wav", "NEWSRM1.wav", 0.0, 1.35, 0.045),
# Energy / Plasma / Thermal Lance / Gauss (touring_plasma, gilded_lance, Cut 7)
ClipSpec("plasma_ppc_01.wav", "Snub_PPC2.wav", 0.0, 1.25, 0.045),
ClipSpec("plasma_ppc_02.wav", "PPcSWEET.wav", 0.045, 0.78, 0.040, auto_trim_lead=False),
ClipSpec("lance_beam_01.wav", "CPPC_DEC2018_2.wav", 0.0, 1.55, 0.050),
ClipSpec("laser_heavy_01.wav", "CLL3.wav", 0.0, 1.20, 0.045),
ClipSpec("gauss_rail_01.wav", "Gauss Sweet 1.wav", 0.015, 1.15, 0.045, auto_trim_lead=False),
# Mechanical / Bolt-clank / Chassis swap
ClipSpec("mech_reload_bolt.wav", "CannonReload2.wav", 0.0, 1.25, 0.045),
ClipSpec("mech_quick_bolt.wav", "reload.wav", 0.0, 0.94, 0.040),
ClipSpec("mech_eject.wav", "eject.wav", 0.0, 0.74, 0.035),
ClipSpec("mech_turret_servo.wav", "turret9.wav", 0.0, 1.10, 0.040),
)
def validate_source_name(name: str) -> None:
if name in FORBIDDEN_EXACT or any(name.startswith(p) for p in FORBIDDEN_PREFIXES):
raise ValueError(f"Refusing forbidden third-party/system file: {name}")
def decode_mono_f32(src_path: Path) -> list[float]:
cmd = [
"ffmpeg",
"-v",
"error",
"-i",
str(src_path),
"-ac",
"1",
"-ar",
str(TARGET_SAMPLE_RATE),
"-f",
"f32le",
"-",
]
proc = subprocess.run(cmd, capture_output=True, check=False)
if proc.returncode != 0:
err = proc.stderr.decode("utf-8", errors="replace").strip()
raise RuntimeError(f"ffmpeg failed on '{src_path}': {err}")
arr = array.array("f")
arr.frombytes(proc.stdout)
if sys.byteorder != "little":
arr.byteswap()
return list(arr)
def process_clip(spec: ClipSpec, src_path: Path, dst_path: Path) -> tuple[float, float, int]:
samples = decode_mono_f32(src_path)
if not samples:
raise RuntimeError(f"Decoded zero samples from '{src_path}'")
lead_idx = int(round(spec.lead_trim_s * TARGET_SAMPLE_RATE))
if lead_idx > 0 and lead_idx < len(samples):
samples = samples[lead_idx:]
if spec.auto_trim_lead:
# Trim only genuinely silent leading padding (>10 ms below -54 dBFS)
silence_thresh = 0.002
first_active = 0
for idx, s in enumerate(samples):
if abs(s) >= silence_thresh:
first_active = idx
break
if first_active > int(0.010 * TARGET_SAMPLE_RATE):
samples = samples[first_active:]
max_samples = int(round(spec.max_dur_s * TARGET_SAMPLE_RATE))
if len(samples) > max_samples:
samples = samples[:max_samples]
# Trim trailing near-silence beyond 15ms if tail is quieter than -60 dBFS, keeping at least 150ms
min_keep = min(len(samples), int(0.15 * TARGET_SAMPLE_RATE))
last_active = len(samples) - 1
while last_active > min_keep and abs(samples[last_active]) < 0.001:
last_active -= 1
samples = samples[: min(len(samples), last_active + int(0.015 * TARGET_SAMPLE_RATE))]
n = len(samples)
if n < 256:
raise RuntimeError(f"Clip '{spec.dest_name}' became too short ({n} samples)")
# Short 4ms fade-in only if attack begins non-zero, avoiding click
fade_in = min(n // 8, int(0.004 * TARGET_SAMPLE_RATE))
if fade_in > 0 and abs(samples[0]) > 0.005:
for i in range(fade_in):
gain = 0.5 * (1.0 - math.cos(math.pi * (i + 0.5) / fade_in))
samples[i] *= gain
# Smooth cosine fade-out on tail
fade_out = min(n // 2, int(round(spec.fade_out_s * TARGET_SAMPLE_RATE)))
if fade_out > 0:
start = n - fade_out
for i in range(fade_out):
gain = 0.5 * (1.0 + math.cos(math.pi * (i + 1) / fade_out))
samples[start + i] *= gain
peak = max(abs(x) for x in samples)
if peak < 1e-4:
raise RuntimeError(f"Clip '{spec.dest_name}' is silent (peak={peak})")
scale = TARGET_PEAK / peak
pcm = array.array("h")
final_peak = 0.0
for s in samples:
v = max(-1.0, min(1.0, s * scale))
final_peak = max(final_peak, abs(v))
pcm.append(int(round(v * 32767.0)))
if sys.byteorder != "little":
pcm.byteswap()
with wave.open(str(dst_path), "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(TARGET_SAMPLE_RATE)
wf.writeframes(pcm.tobytes())
size_bytes = dst_path.stat().st_size
dur_s = n / TARGET_SAMPLE_RATE
return dur_s, final_peak, size_bytes
def main() -> int:
if len(CLIPS) != 25:
raise AssertionError(f"Expected exactly 25 clips, got {len(CLIPS)}")
if not SOURCE_DIR.is_dir():
raise FileNotFoundError(f"Source directory not found: {SOURCE_DIR}")
DEST_DIR.mkdir(parents=True, exist_ok=True)
expected_names = {c.dest_name for c in CLIPS}
for existing in DEST_DIR.glob("*"):
if existing.is_file() and existing.name not in expected_names:
existing.unlink()
total_bytes = 0
for spec in CLIPS:
validate_source_name(spec.src_name)
src_path = SOURCE_DIR / spec.src_name
if not src_path.is_file():
raise FileNotFoundError(f"Missing Haven source WAV: {src_path}")
dst_path = DEST_DIR / spec.dest_name
dur_s, peak, size_bytes = process_clip(spec, src_path, dst_path)
total_bytes += size_bytes
print(f" {spec.dest_name:<22} <- {spec.src_name:<22} {dur_s:5.2f}s peak={peak:.3f} {size_bytes/1024:6.1f} KiB")
produced = sorted(p.name for p in DEST_DIR.glob("*.wav"))
if len(produced) != 25:
raise RuntimeError(f"Expected 25 WAVs in {DEST_DIR}, found {len(produced)}")
total_mib = total_bytes / (1024.0 * 1024.0)
print(f"Curated {len(produced)} WAVs into {DEST_DIR} (total {total_mib:.2f} MiB)")
if total_mib >= 4.0:
raise RuntimeError(f"Total audio size {total_mib:.2f} MiB exceeds 4.0 MiB budget")
return 0
if __name__ == "__main__":
raise SystemExit(main())