Change manual packet numbering to a dictionary
This commit is contained in:
1 parent
37a6b5d59b
commit
b83887cb2a
8 files changed
+53
-44
No files matched your search
@@ -7,17 +7,38 @@ namespace Mistox.Attributes {
|
||||
public class NetworkPacketDictionary {
|
||||
|
||||
// Fills out the NetworkPacket Lookup Dictionary
|
||||
public static readonly Dictionary<byte, Type> ClientToClientPackets = new();
|
||||
public static readonly Dictionary<byte, Type> ServerToClientPackets = new();
|
||||
public static readonly Dictionary<ushort, Type> PacketLookupTable = new();
|
||||
public static readonly Dictionary<Type, ushort> 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() {
|
||||
Type[] allClasses = Assembly.GetExecutingAssembly().GetTypes();
|
||||
foreach( Type cur in allClasses) {
|
||||
mPacket attribute = cur.GetCustomAttribute<mPacket>(false);
|
||||
if (attribute != null) {
|
||||
if ( attribute.PacketUse.HasFlag(PacketUsage.ClientToClient) ) {
|
||||
ClientToClientPackets[attribute.ID] = cur;
|
||||
} else if ( attribute.PacketUse.HasFlag(PacketUsage.ClientToServer) ) {
|
||||
ServerToClientPackets[attribute.ID] = cur;
|
||||
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
|
||||
foreach (Assembly assembly in assemblies) {
|
||||
Type[] allClasses = assembly.GetTypes();
|
||||
foreach( Type cur in allClasses) {
|
||||
mPacket attribute = cur.GetCustomAttribute<mPacket>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user