using System; using System.Collections.Generic; using System.Reflection; namespace Mistox.Attributes { public class NetworkPacketDictionary { // Fills out the NetworkPacket Lookup Dictionary public static readonly Dictionary PacketLookupTable = new(); public static readonly Dictionary PacketIDTable = new(); // Have a way to assign a number to the packet that will run the same ever time static ushort GetDeterministicHashCode(string str) { unchecked { uint hash = 2166136261; foreach (char c in str) { hash = (hash ^ c) * 16777619; } return (ushort)(hash % 0xFFFF); } } // Map all packets to a number [ Error on packet collisions ] public static void BuildNetworkPacketList() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { Type[] allClasses = assembly.GetTypes(); foreach( Type cur in allClasses) { mPacket attribute = cur.GetCustomAttribute(false); if (attribute != null) { // Generate a deterministic 16-bit ID based on the Type's FullName string identifier = cur.FullName ?? cur.Name; ushort packetId = GetDeterministicHashCode(identifier); if (PacketLookupTable.ContainsKey(packetId)) { throw new Exception($"CRITICAL: Duplicate Packet ID detected! ID {packetId} is used by both {PacketLookupTable[packetId].Name} and {cur.Name}"); } PacketLookupTable[packetId] = cur; PacketIDTable[cur] = packetId; } } } } } }