diff --git a/Common/MusicEvents.cs b/Common/MusicEvents.cs index a823b83..dd420c2 100644 --- a/Common/MusicEvents.cs +++ b/Common/MusicEvents.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Reflection; using System.Threading; using Terraria; using Terraria.ID; @@ -14,7 +13,7 @@ namespace UnCalamityModMusic.Common // This system was created by Nycro for the main Calamity Mod. // An altered form of it is here so VCMM doesn't have to rely on external code. public record class MusicEventEntry(string Id, int Song, TimeSpan Length, TimeSpan IntroSilence, TimeSpan OutroSilence, Func ShouldPlay, Func Enabled); - + public class MusicEvents : ModSystem { #region Statics @@ -33,7 +32,7 @@ namespace UnCalamityModMusic.Common public static Thread EventTrackerThread { get; set; } = null; - public static HashSet PlayedEvents { get; set; } = []; + public static List PlayedEvents { get; set; } = []; public static List EventCollection { get; set; } = []; @@ -136,7 +135,7 @@ namespace UnCalamityModMusic.Common // Even if an event isn't marked as enabled, it should be counted // as "played" so it isn't played when the player doesn't expect it PlayedEvents.Add(musicEvent.Id); - + // Events are always enabled on the server if (Main.dedServ || musicEvent.Enabled()) { @@ -206,7 +205,7 @@ namespace UnCalamityModMusic.Common while (CurrentEvent is not null) { bool musicPaused = !Main.instance.IsActive; - + if (musicPaused && !minimized.HasValue) minimized = DateTime.Now; @@ -227,9 +226,11 @@ namespace UnCalamityModMusic.Common public override void SaveWorldData(TagCompound tag) { tag["VCMM:PlayedMusicEventCount"] = PlayedEvents.Count; - int i = 0; - foreach (string playedEvent in PlayedEvents) - tag[$"VCMM:PlayedMusicEventCount{i++}"] = playedEvent; + + for (int i = 0; i < PlayedEvents.Count; i++) + { + tag[$"VCMM:PlayedMusicEvent{i}"] = PlayedEvents[i]; + } } public override void LoadWorldData(TagCompound tag) @@ -265,14 +266,53 @@ namespace UnCalamityModMusic.Common public static void SendSyncRequest() { - MusicEventSyncRequestPacket.Send(); + ModPacket packet = UnCalamityModMusic.Instance.GetPacket(); + packet.Write((byte)MusicEventsNetcode.VanillaCalamityModMusicMessageType.MusicEventSyncRequest); + packet.Send(); + } + + public static void FulfillSyncRequest(int requester) + { + // Only fulfill requests as the server host + if (!Main.dedServ) + { + return; + } + + ModPacket packet = UnCalamityModMusic.Instance.GetPacket(); + packet.Write((byte)MusicEventsNetcode.VanillaCalamityModMusicMessageType.MusicEventSyncResponse); + + int trackCount = PlayedEvents.Count; + packet.Write(trackCount); + + for (int i = 0; i < trackCount; i++) + { + packet.Write(PlayedEvents[i]); + } + + packet.Send(toClient: requester); + } + + public static void ReceiveSyncResponse(BinaryReader reader) + { + // Only receive info on clients + if (Main.dedServ) + { + return; + } + + PlayedEvents.Clear(); + int trackCount = reader.ReadInt32(); + + for (int i = 0; i < trackCount; i++) + { + PlayedEvents.Add(reader.ReadString()); + } } #endregion } - #region Multiplayer Syncing - public class MusicEventsPlayer : ModPlayer { public override void OnEnterWorld() @@ -284,140 +324,59 @@ namespace UnCalamityModMusic.Common } } - internal sealed class MusicEventSyncRequestPacket : MusicEventPacket + public class MusicEventsNetcode { - public static MusicEventSyncRequestPacket Instance { get; private set; } - - public static void Send(int toClient = -1, int ignoreClient = -1) + public enum VanillaCalamityModMusicMessageType : byte { - if (Main.netMode != NetmodeID.MultiplayerClient) - return; - - var packet = Instance.CreateBasePacket(); - packet.Send(toClient, ignoreClient); + MusicEventSyncRequest, + MusicEventSyncResponse } - public override void HandlePacket(BinaryReader packet, int sender) + public static void HandlePacket(Mod mod, BinaryReader reader, int whoAmI) { - if (!Main.dedServ) - return; - - MusicEventSyncResponsePacket.Send(toClient: sender); - } - } - - internal sealed class MusicEventSyncResponsePacket : MusicEventPacket - { - public static MusicEventSyncResponsePacket Instance { get; private set; } - - public static void Send(int toClient = -1, int ignoreClient = -1) - { - if (!Main.dedServ) - return; - - var packet = Instance.CreateBasePacket(); - int trackCount = MusicEvents.PlayedEvents.Count; - packet.Write(trackCount); - - foreach (string playedEvent in MusicEvents.PlayedEvents) - packet.Write(playedEvent); - - packet.Send(toClient, ignoreClient); - } - - public override void HandlePacket(BinaryReader packet, int sender) - { - if (Main.netMode != NetmodeID.MultiplayerClient) + try { - int c = packet.ReadInt32(); - for (int i = 0; i < c; i++) - _ = packet.ReadString(); + VanillaCalamityModMusicMessageType msgType = (VanillaCalamityModMusicMessageType)reader.ReadByte(); + switch (msgType) + { + case VanillaCalamityModMusicMessageType.MusicEventSyncRequest: + { + MusicEvents.FulfillSyncRequest(whoAmI); + break; + } - return; + case VanillaCalamityModMusicMessageType.MusicEventSyncResponse: + { + MusicEvents.ReceiveSyncResponse(reader); + break; + } + + default: + { + UnCalamityModMusic.Instance.Logger.Error($"Failed to parse VCMM packet: No VCMM packet exists with ID {msgType}."); + throw new Exception("Failed to parse VCMM packet: Invalid VCMM packet ID."); + } + } + } + catch (Exception e) + { + if (e is EndOfStreamException eose) + { + UnCalamityModMusic.Instance.Logger.Error("Failed to parse VCMM packet: Packet was too short, missing data, or otherwise corrupt.", eose); + } + else if (e is ObjectDisposedException ode) + { + UnCalamityModMusic.Instance.Logger.Error("Failed to parse VCMM packet: Packet reader disposed or destroyed.", ode); + } + else if (e is IOException ioe) + { + UnCalamityModMusic.Instance.Logger.Error("Failed to parse VCMM packet: An unknown I/O error occurred.", ioe); + } + else + { + throw; + } } - - MusicEvents.PlayedEvents.Clear(); - - int trackCount = packet.ReadInt32(); - for (int i = 0; i < trackCount; i++) - MusicEvents.PlayedEvents.Add(packet.ReadString()); } } - - internal abstract class MusicEventPacket : ILoadable - { - public abstract void HandlePacket(BinaryReader packet, int sender); - - private ushort _NetID; - private PropertyInfo _Prop_Static_Instance; - - public void Load(Mod mod) - { - _NetID = MusicEventsNetcode.RegisterHandler(this); - - var type = GetType(); - var instanceProperty = type.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic); - - if (instanceProperty == null) - return; - - if (!instanceProperty.PropertyType.IsAssignableFrom(type)) - UnCalamityModMusic.Instance.Logger.Error($"Packet instance's 'Instance' property is not asssignable with given type! [Failed On: '{type.FullName}']"); - - instanceProperty.SetValue(null, this); - _Prop_Static_Instance = instanceProperty; - } - - public virtual void Unload() - { - _Prop_Static_Instance?.SetValue(null, null); - _Prop_Static_Instance = null; - } - - public void CloneAndBroadcast(BinaryReader packet, long startIndex, int length, int ignoreClient = -1) - { - if (!Main.dedServ) - return; - - if (startIndex < 0) - return; - - packet.BaseStream.Position = startIndex; - - Span buffer = length <= 256 ? stackalloc byte[length] : new byte[length]; - packet.BaseStream.Read(buffer); - - var newPacket = CreateBasePacket(); - newPacket.Write(buffer); - newPacket.Send(ignoreClient); - } - - public ModPacket CreateBasePacket() - { - var packet = UnCalamityModMusic.Instance.GetPacket(); - MusicEventsNetcode.WriteHandlerNetID(packet, _NetID); - return packet; - } - } - - public class MusicEventsNetcode : ModSystem - { - private static List _PacketHandlers = []; - - internal static ushort RegisterHandler(MusicEventPacket handler) - { - var id = (ushort)_PacketHandlers.Count; - _PacketHandlers.Add(handler); - return id; - } - - internal static void WriteHandlerNetID(BinaryWriter packet, ushort netID) - { - if (_PacketHandlers.Count > 256) - packet.Write(netID); - else - packet.Write((byte)netID); - } - } - #endregion -} \ No newline at end of file +} diff --git a/build.txt b/build.txt index f118b72..e9ccdf4 100644 --- a/build.txt +++ b/build.txt @@ -1,5 +1,5 @@ author = The VCMM Dev Team -version = 2.1.1 +version = 2.1.2 displayName = Vanilla Calamity Mod Music weakReferences = CalamityMod homepage = https://calamitymod.com