-
Notifications
You must be signed in to change notification settings - Fork 10
/
NetRouter.cs
100 lines (84 loc) · 2.75 KB
/
NetRouter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Terraria.ModLoader;
namespace MechTransfer
{
internal static class NetRouter
{
private class TypeSpecificComparer<T> : IEqualityComparer<T>
{
public bool Equals(T x, T y)
{
return x.GetType().FullName == y.GetType().FullName;
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
}
private static byte prefix = 0;
private static bool bigIds = false;
private static bool inited = false;
private static INetHandler[] handlers;
private static Dictionary<INetHandler, int> handlersInverse;
private static List<INetHandler> loadList = new List<INetHandler>();
public static void AddHandler(INetHandler handler)
{
if (inited)
throw new InvalidOperationException();
loadList.Add(handler);
}
public static void Init(byte prefix)
{
if (inited)
throw new InvalidOperationException();
NetRouter.prefix = prefix;
handlers = loadList.OrderBy(x => x.GetType().FullName).Distinct(new TypeSpecificComparer<INetHandler>()).ToArray();
handlersInverse = new Dictionary<INetHandler, int>();
for (int i = 0; i < handlers.Length; i++)
{
handlersInverse.Add(handlers[i], i);
}
loadList = null;
inited = true;
if (handlers.Length > 256)
bigIds = true;
}
public static void RouteMessage(BinaryReader reader, int WhoAmI)
{
if (!inited)
throw new InvalidOperationException();
int target;
if (bigIds)
target = reader.ReadUInt16();
else
target = reader.ReadByte();
handlers[target].HandlePacket(reader, WhoAmI);
}
public static ModPacket GetPacketTo(INetHandler target, Mod mod)
{
int id;
if (!handlersInverse.TryGetValue(target, out id))
throw new ArgumentException();
ModPacket packet = mod.GetPacket();
if (prefix != 0)
packet.Write(prefix);
if (bigIds)
packet.Write((UInt16)id);
else
packet.Write((byte)id);
return packet;
}
public static void Unload()
{
prefix = 0;
bigIds = false;
inited = false;
handlers = null;
handlersInverse = null;
loadList = new List<INetHandler>();
}
}
}