using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Vision.Core.Logging.Loggers; namespace Vision.Core.Networking.Packet { public static class NetPacketHandlerLoader where T : NetConnectionBase { private static readonly EngineLog Logger = new EngineLog(typeof(NetPacketHandlerLoader)); private static readonly Dictionary>> Handlers = new Dictionary>>(); // public static readonly FastDictionary Structs = new FastDictionary(); public static void LoadHandlers() { var allMethods = VisionAssembly.GetMethodsWithAttribute().ToList(); foreach (var pair in allMethods) { var first = pair.First; var second = pair.Second; if (Handlers.ContainsKey(first.Command)) { Logger.Warning($"Duplicate message handler found: [{first.Command}], ignoring."); continue; } var destinations = first.Destinations; var theDelegate = Delegate.CreateDelegate(typeof(NetPacketHandlerDelegate), second) as NetPacketHandlerDelegate; var both = new Tuple>(destinations, theDelegate); Handlers.Add(first.Command, both); var destinationsStr = ""; for (var index = 0; index < destinations.Length; index++) { var dest = destinations[index]; destinationsStr += dest.ToMessage(); if (index != destinations.Length - 1) destinationsStr += ", "; } Logger.Debug($"Added message handler: (Command: {first.Command}, Destinations: {destinationsStr})"); } Logger.Info($"Loaded {Handlers.Count} packet handlers!"); // var allStructs = VisionAssembly.GetTypesOfBase().ToList(); // // foreach (var @struct in allStructs) // { // var ctor = @struct.GetConstructor(Type.EmptyTypes); // if (ctor == null) continue; // var created = ctor.Invoke(new object[] { }); // var command = (NetCommand)@struct.GetDeclaredMethod("GetCommand").Invoke(created, null); // Structs.Add(command, @struct); // // Log.Write(LogType.EngineLog, LogLevel.Debug, $"Added struct: (Command: {command}, Struct: {@struct.Name}"); // } } public static bool TryGetHandler(NetCommand command, out NetPacketHandlerDelegate handler, out NetConnectionDestination[] destinations) { var result = Handlers.TryGetValue(command, out var both); if (result) { handler = both.Item2; destinations = both.Item1; return true; } handler = null; destinations = null; return false; } } }