using System.Collections.Concurrent; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using EvilEngine.Conversion; using EvilEngine.Formats; using EvilEngine.Formats.Maps; using EvilEngine.Formats.Records; using EvilEngine.Formats.Sounds; using EvilEngine.Host.Collision; using EvilEngine.Host.Movement; using EvilEngine.Host.Sessions; using EvilEngine.Host.Steps; using EvilEngine.Mounts; namespace EvilEngine.Host.Tests; public sealed class SourceSoundTests(ITestOutputHelper output) { private static readonly string Installed = typeof(SourceSoundTests).Assembly .GetCustomAttributes() .Single(attribute => attribute.Key == "AdapterOutputRoot").Value!; private static (EngineHost Host, Mount Mount) Open(IConversionCache? cache = null) { var path = Environment.GetEnvironmentVariable("EVIL_GMOD"); Assert.SkipWhen(path is null, "Set EVIL_GMOD to a Garry's Mod install to convert its sounds."); var host = new EngineHost(cache); host.Adapters.LoadAll([Installed]); var mount = host.Mounts.Open(Assert.Single(host.Mounts.Probe(path!))); host.Conversion.AddNamespace(ContentNamespace.For(mount)); return (host, mount); } private RecordSet Set(EngineHost host, string id) { var result = host.Conversion.Get(ContentKind.Record, ContentId.Parse(id)); Assert.True(result.Succeeded, string.Join('\n', result.Diagnostics)); var kinds = result.Diagnostics .Select(note => Regex.Replace(Regex.Replace(note, @"^[^ ]+ ", ""), @"'[^']*'", "'…'")) .GroupBy(kind => kind).OrderByDescending(group => group.Count()); output.WriteLine($"{id}: {result.Diagnostics.Count} notes"); foreach (var kind in kinds.Take(40)) output.WriteLine($"{kind.Count(),6} × {kind.Key}"); foreach (var note in result.Diagnostics.Take(60)) output.WriteLine($" {note}"); return RecordText.Read("gmod", Encoding.UTF8.GetString(result.Content!.Data.Span), id); } [Fact] public void ConvertsEverySoundscriptAndSoundAdd() { var (host, _) = Open(); var set = Set(host, "gmod:records/sounds"); var step = Assert.Single(set.Sounds, sound => sound.Id == ContentId.Parse("gmod:concrete.stepleft")); output.WriteLine($"{set.Sounds.Count} sounds; {set.Sounds.Count(sound => sound.Loop == true)} loop; " + string.Join(", ", set.Sounds.GroupBy(sound => sound.Branch) .Select(group => $"{group.Key} {group.Count()}"))); output.WriteLine($"concrete.stepleft: {string.Join(", ", step.Files.Select(file => file.Content))}, " + $"volume {step.Volume}, pitch {step.Pitch}, level {step.Level}, channel {step.Channel}"); Assert.Equal( [ ContentId.Parse("gmod:sound/player/footsteps/concrete1.wav"), ContentId.Parse("gmod:sound/player/footsteps/concrete3.wav") ], step.Files.Select(file => file.Content)); Assert.Equal(new SoundRange(75), step.Level); Assert.True(set.Sounds.Count > 5000); } [Fact] public void ConvertsEverySoundscapeInTheManifest() { var (host, _) = Open(); var set = Set(host, "gmod:records/soundscapes"); var outside = Assert.Single(set.Soundscapes, record => record.Id == ContentId.Parse("gmod:construct.outside")); output.WriteLine($"{set.Soundscapes.Count} soundscapes, {set.Soundscapes.Sum(record => record.Loops.Count)} " + $"loops, {set.Soundscapes.Sum(record => record.Randoms.Count)} random sets, " + $"{set.Soundscapes.Sum(record => record.Includes.Count)} includes"); Assert.Equal( [ new SoundscapeLoop(new SoundFile(ContentId.Parse("gmod:sound/ambient/construct_tone.wav")) { Flags = SoundFlags.Omni }) { Volume = new SoundRange(0.15), Pitch = new SoundRange(110), Level = new SoundRange(30) }, new SoundscapeLoop(new SoundFile(ContentId.Parse("gmod:sound/ambient/forest_day.wav"))) { Volume = new SoundRange(0.25), Level = new SoundRange(30) } ], outside.Loops); Assert.Equal("1", outside.Games["gmod"]["dsp"]); output.WriteLine(RecordText.Write(RecordSet.Empty with { Soundscapes = set.Soundscapes.Where(record => record.Id.Name is "construct.lake" or "e3_techdemo_06" or "d1_canals_junkyard").ToArray() })); var names = set.Soundscapes.Select(record => record.Id).ToHashSet(); var unresolved = set.Soundscapes.SelectMany(record => record.Includes.Where(include => !names.Contains(include.Soundscape)) .Select(include => $"{record.Id} -> {include.Soundscape}")) .ToArray(); output.WriteLine($"unresolved includes: {string.Join(", ", unresolved)}"); Assert.True(set.Soundscapes.Count > 800, $"{set.Soundscapes.Count} soundscapes"); Assert.True(unresolved.Length <= 2, string.Join(", ", unresolved)); } [Fact] public void ConvertsEverySurface() { var (host, _) = Open(); var set = Set(host, "gmod:records/surfaces"); var concrete = Assert.Single(set.Surfaces, surface => surface.Id == ContentId.Parse("gmod:surfaces/concrete")); output.WriteLine($"{set.Surfaces.Count} surfaces: " + string.Join(", ", set.Surfaces.GroupBy(surface => surface.Class) .Select(group => $"{group.Key} {group.Count()}"))); Assert.Equal(ContentId.Parse("gmod:concrete.stepleft"), concrete.Sounds["step.left"]); Assert.Equal(ContentId.Parse("gmod:concrete.stepright"), concrete.Sounds["step.right"]); Assert.Equal("concrete", concrete.Class); var sounds = Set(host, "gmod:records/sounds").Sounds.Select(sound => sound.Id).ToHashSet(); var unresolved = set.Surfaces.SelectMany(surface => surface.Sounds.Where(pair => !sounds.Contains(pair.Value)) .Select(pair => $"{surface.Id} {pair.Key} {pair.Value}")).ToArray(); output.WriteLine($"{unresolved.Length} surface sounds name no sound record"); foreach (var line in unresolved.Take(40)) output.WriteLine($" {line}"); Assert.All(set.Surfaces, surface => { Assert.True(surface.Sounds.ContainsKey("step.left"), $"{surface.Id} has no step.left"); Assert.Contains(surface.Sounds["step.left"], sounds); }); } [Fact] public void ConvertsEveryWaveUnderSound() { var (host, mount) = Open(new NoCache()); var waves = mount.Files.EnumerateAll() .Select(entry => entry.Path.Value) .Where(path => path.StartsWith("sound/", StringComparison.OrdinalIgnoreCase) && SoundContent.IsSound(path)) .Order(StringComparer.Ordinal) .ToArray(); var failures = new ConcurrentBag(); var kinds = new ConcurrentDictionary(); var sources = new ConcurrentDictionary(); Parallel.ForEach(waves, new ParallelOptions { MaxDegreeOfParallelism = 8 }, path => { var result = host.Conversion.Get(ContentKind.Sound, ContentId.Create("gmod", path)); if (!result.Succeeded) { failures.Add($"{path}: {string.Join(" / ", result.Diagnostics)}"); return; } var data = result.Content!.Data; var kind = SoundContent.Extension(path)!; if (kind == "wav") { var wave = WaveFile.Read(data, path); var rewritten = mount.Files.TryOpenAccess(VirtualPath.Parse(path), out var original) && original.Length != data.Length; original?.Dispose(); if (rewritten && mount.Files.TryOpen(VirtualPath.Parse(path), out var stream)) { using var copy = new MemoryStream(); using (stream) { stream.CopyTo(copy); } var source = WaveFile.Read(copy.ToArray(), path); sources.AddOrUpdate( $"from format {source.Format} {source.BitsPerSample}-bit, {source.Cues.Count} cues{(source.HasCue ? "" : ", no cue")}", 1, (_, count) => count + 1); } kind = $"wav {(wave.Format == WaveFormats.Pcm ? "pcm" : wave.Format.ToString())} {wave.BitsPerSample}-bit " + $"{wave.Channels}ch{(wave.Loop is null ? "" : " loop")}{(wave.HasCue ? " cue" : "")}{(rewritten ? " rewritten" : "")}"; } kinds.AddOrUpdate(kind, 1, (_, count) => count + 1); }); output.WriteLine($"{waves.Length} sounds, {failures.Count} failed"); foreach (var (kind, count) in kinds.OrderByDescending(pair => pair.Value)) output.WriteLine($"{count,6} × {kind}"); foreach (var (kind, count) in sources.OrderByDescending(pair => pair.Value)) output.WriteLine($"{count,6} × rewritten {kind}"); foreach (var failure in failures.Order(StringComparer.Ordinal).Take(100)) output.WriteLine(failure); Assert.True(waves.Length > 5000); Assert.Empty(failures); Assert.DoesNotContain(kinds.Keys, kind => kind.EndsWith(" cue")); } [Fact] public void WalksABodyOverGmConstructsConcreteWithItsStepSounds() { var (host, mount) = Open(); var registry = LocalRegistry.Build([mount], host.Conversion); var cell = MapText.ReadCell(Encoding.UTF8.GetString(host.Conversion.Get(ContentKind.Cell, ContentId.Parse("gmod:maps/gm_construct/cells/0")).Content!.Data.Span), "cell"); var space = HullSpace.Build(MapColliders.Build([cell], host.Conversion.Get, (_, _) => { }), HullSpace.BlocksPlayers); var spawn = cell.Spawns[0]; var server = new ServerSession(new SessionStart(ContentId.Parse("gmod:gm_construct"), space, [spawn], -1000) { StepSounds = StepSounds.From(registry, host.Conversion) }); var heard = new List(); var bot = server.AddBot(brain: _ => new MoveCommand(1, 0, 0, 0, spawn.Transform.Angles.Y, MoveButtons.None)); bot.Arrived = snapshot => heard.AddRange(snapshot.Sounds); for (var tick = 0; tick < 200; tick++) server.Tick(); output.WriteLine($"{registry.Sounds.Count} sounds, {registry.Surfaces.Count} surfaces in the registry"); foreach (var sound in heard) output.WriteLine($"{sound.Sound} at {sound.Position} volume {sound.Volume}"); Assert.True(heard.Count >= 3, $"{heard.Count} step sounds"); Assert.Equal([ContentId.Parse("gmod:concrete.stepright"), ContentId.Parse("gmod:concrete.stepleft")], heard.Take(2).Select(sound => sound.Sound)); Assert.All(heard, sound => Assert.NotNull(registry.Sound(sound.Sound))); } private sealed class NoCache : IConversionCache { public ConvertedContent? Find(ContentKind kind, ContentId id) { return null; } public void Store(ConvertedContent content) { } public void Forget(ContentKind kind, ContentId id) { } public int Invalidate(string @namespace, IReadOnlyCollection paths, CaseRule caseRule) { return 0; } } }