Skip to content
0.2.0-dev Download ZIP
72 lines ·2.1 KB Raw
1using EvilEngine.Client.Audio;
2using EvilEngine.Formats.Maps;
3using EvilEngine.Host.Sessions;
4using Godot;
5
6namespace EvilEngine.Client.World;
7
8public partial class WorldSounds : Node3D
9{
10 private readonly WorldBodies? _bodies;
11 private readonly ClientSession _session;
12 private readonly List<SoundVoice> _voices = [];
13
14 public WorldSounds(ClientSession session, WorldBodies? bodies)
15 {
16 _session = session;
17 _bodies = bodies;
18 Name = "Sounds";
19 }
20
21 public int Heard { get; private set; }
22
23 public override void _EnterTree()
24 {
25 _session.Arrived += Arrived;
26 }
27
28 public override void _ExitTree()
29 {
30 _session.Arrived -= Arrived;
31 foreach (var voice in _voices)
32 voice.Stop();
33 _voices.Clear();
34 }
35
36 private void Arrived(Snapshot snapshot)
37 {
38 if (snapshot.Sounds.Count == 0)
39 return;
40 _voices.RemoveAll(voice => voice.Ended);
41 if (AudioManager.Instance is not { } audio)
42 return;
43 foreach (var sound in snapshot.Sounds)
44 {
45 Heard++;
46 var emitter = sound.Emitter;
47 var offset = !emitter.IsNone && ClientSession.Body(snapshot, emitter) is { } body
48 ? Map(sound.Position) - Map(body.Feet)
49 : Vector3.Zero;
50 var place = new SoundPlace(ToGlobal(Map(sound.Position)))
51 {
52 Emitter = emitter, Follow = emitter.IsNone ? null : () => Where(emitter) + offset
53 };
54 if (audio.Play(sound.Sound, place, sound.Volume) is { } voice)
55 _voices.Add(voice);
56 }
57 }
58
59 private Vector3? Where(EntityHandle emitter)
60 {
61 if (!IsInsideTree())
62 return null;
63 if (_bodies?.Body(emitter) is { } node && node.IsInsideTree())
64 return node.GlobalPosition;
65 return ClientSession.Body(_session.Latest, emitter) is { } state ? ToGlobal(Map(state.Feet)) : null;
66 }
67
68 private static Vector3 Map(MapVector at)
69 {
70 return new Vector3((float)at.X, (float)at.Y, (float)at.Z);
71 }
72}