NetworkManager.cs 14.5 KB
Newer Older
Ben W's avatar
Ben W committed
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using DarkRift;
using DarkRift.Server.Unity;
using DarkRift.Client.Unity;
using DarkRift.Client;
using System;
using DarkRift.Server;

class NetworkManager : MonoBehaviour
{
    public static Action<PlayerManager> PlayerJoined;
    public static Action<PlayerManager> PlayerDisconnected;

    public static bool IsServer = false;
    public static UnityClient Client { get => _instance._client; }
    private static NetworkManager _instance;

    public bool EnableDebugMessages = true;
    public List<GameObject> NetworkedPrefabs = new List<GameObject>();

    [SerializeField] private GameObject _playerPrefab;
    private UnityClient _client;

    #region Server Variables
    [Header("Server Variables")]
    private const string _spawnPointTag = "Respawn";
    private const string _nodeSpawnPointTag = "Node Spawn";
    private const ushort _clientID = ushort.MaxValue;

    [SerializeField] private float _nodeSpawnTimer = 1f;
    [SerializeField] private List<Transform> _nodeSpawns;
    [SerializeField] private bool _nodeTimerRunning = true;
    [SerializeField] private int _nodeTarget = 3;
    [SerializeField] private GameObject _nodePrefab;
    private WaitForSeconds _nodeDelay;
    private List<IClient> _clients = new List<IClient>();
    private GameObject[] _spawnPoints;
    private ushort _nextUID;

    #endregion

Ben W's avatar
Ben W committed
45
46
    public static string ConnectIP = "127.0.0.1";

Ben W's avatar
Ben W committed
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
    public static Dictionary<ushort, NetworkedBehaviour> NetworkedObjects = new Dictionary<ushort, NetworkedBehaviour>();
    public static Dictionary<ushort, PlayerManager> PlayersManagers = new Dictionary<ushort, PlayerManager>();

    private void Start()
    {
        _instance = this;
        DontDestroyOnLoad(this);
        SceneManager.sceneLoaded += SceneLoaded;

        Gather1.Server.MasterPlugin.ClientConnected += ServerClientConnected;
        Gather1.Server.MasterPlugin.ClientDisconnected += ServerClientDisconnected;
    }

    private void SceneLoaded(Scene arg0, LoadSceneMode arg1)
    {
        if (arg0.buildIndex != 1)
            return;

        GameObject[] objects = GameObject.FindGameObjectsWithTag("Manager");

        if (IsServer)
        {
            for (int i = 0; i < objects.Length; i++)
            {
                if (objects[i].name == "Server Manager")
                {
                    ServerFindSpawnPoints();
                    ServerFindNodeSpawnPoints();
                    XmlUnityServer server = objects[i].GetComponent<XmlUnityServer>();
                    server.Create();
                    Debug.Log("Server Started");

                    ServerSpawnPlayer(ServerGetRandomSpawnPoint(), ServerGetUID(),
                        _playerPrefab.name, _clientID);
                    _nodeDelay = new WaitForSeconds(_nodeSpawnTimer);
                    StartCoroutine(ServerNodeSpawnTimer());
                    return;
                }
            }
        }

        for (int i = 0; i < objects.Length; i++)
        {
            if (objects[i].name == "Client Manager")
            {
                _client = objects[i].GetComponent<UnityClient>();
                _client.MessageReceived += ClientMessageReceived;
Ben W's avatar
Ben W committed
94
                _client.Connect(ConnectIP, 4296, false);
Ben W's avatar
Ben W committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
                ClientRequestPlayer();
                Debug.Log("Connect Finished");
            }
        }
    }

    #region Server Methods

    public static void ServerSendMessageToAll(Message message, SendMode sendmode)
    {
        for (int i = 0; i < _instance._clients.Count; i++)
        {
            _instance._clients[i].SendMessage(message, sendmode);
        }
    }

    public static void ServerSendMessageToAll(NetworkTags tag, DarkRiftWriter writer, SendMode sendMode)
    {
        using (Message message = Message.Create((ushort)tag, writer))
        {
            ServerSendMessageToAll(message, sendMode);
        }
    }

    private void ServerClientConnected(object sender, ClientConnectedEventArgs args)
    {
        args.Client.MessageReceived += ServerClientMessageReceived;
        _clients.Add(args.Client);
    }

    private void ServerClientDisconnected(object sender, ClientDisconnectedEventArgs args)
    {
        Debug.Log("Removing Player");
        _clients.Remove(args.Client);

        RemovePlayer(args.Client.ID);

        using (DarkRiftWriter writer = DarkRiftWriter.Create())
        {
            writer.Write(args.Client.ID);
            using (Message message = Message.Create((ushort)NetworkTags.PlayerDisconnected, writer))
            {
                ServerSendMessageToAll(message, SendMode.Reliable);
            }
        }
    }

    private void ServerClientMessageReceived(object sender, DarkRift.Server.MessageReceivedEventArgs args)
    {
        using (Message message = args.GetMessage())
        using (DarkRiftReader reader = message.GetReader())
        {
            switch (message.Tag)
            {
                case (ushort)NetworkTags.RequestPlayer:
                    ServerRequestPlayer(reader, args);
                    break;
                case (ushort)NetworkTags.MoveObject:
                case (ushort)NetworkTags.ToolHide:
                case (ushort)NetworkTags.ToolSwitch:
                case (ushort)NetworkTags.HitNodeRequest:
                    ushort uid = reader.ReadUInt16();
                    // Validate?

                    if (NetworkedObjects.TryGetValue(uid, out NetworkedBehaviour behaviour))
                    {
                        behaviour.MessageReceived.Invoke(message, reader);
                    }
                    break;
            }
        }
    }

    private void ServerRequestPlayer(DarkRiftReader reader, DarkRift.Server.MessageReceivedEventArgs args)
    {
        // Validate stuff
        // ToDo: Get Client ID from server not client

        ServerSendExistingObjects(args.Client);

        ushort clientID = reader.ReadUInt16();
        string prefabName = reader.ReadString();
        Transform spawn = ServerGetRandomSpawnPoint();
        ushort uid = ServerGetUID();

        ServerSpawnPlayer(spawn, uid, prefabName, clientID);

        using (DarkRiftWriter writer = DarkRiftWriter.Create())
        {

            writer.Write(prefabName);
            writer.Write(uid);

            writer.Write(spawn.position.x);
            writer.Write(spawn.position.y);
            writer.Write(spawn.position.z);

            writer.Write(spawn.rotation.eulerAngles.x);
            writer.Write(spawn.rotation.eulerAngles.y);
            writer.Write(spawn.rotation.eulerAngles.z);

            writer.Write(clientID);

            using (Message message = Message.Create((ushort)NetworkTags.SpawnPrefab, writer))
            {
                ServerSendMessageToAll(message, SendMode.Reliable);
            }
        }

    }

    private void ServerFindSpawnPoints()
    {
        _spawnPoints = GameObject.FindGameObjectsWithTag(_spawnPointTag);
        Debug.Log($"Found {_spawnPoints.Length} spawn points");
    }

    private Transform ServerGetRandomSpawnPoint()
    {
        return _spawnPoints[UnityEngine.Random.Range(0, _spawnPoints.Length - 1)].transform;
    }

    public static ushort ServerGetUID()
    {
        ushort id = _instance._nextUID;
        _instance._nextUID++;
        return id;
    }

    private bool ServerSpawnPrefab(string prefabName, ushort uid,
        out GameObject networkObject, out NetworkedBehaviour behaviour)
    {
        GameObject prefab = GetNetworkPrefab(prefabName);
        if (prefab == null)
        {
            networkObject = null;
            behaviour = null;
            return false;
        }

        networkObject = Instantiate(prefab);
        behaviour = networkObject.GetComponent<NetworkedBehaviour>();
        behaviour.UID = uid;
        NetworkedObjects.Add(uid, behaviour);
        return true;
    }

    private void ServerSpawnPlayer(Transform spawn, ushort uid, string prefabName, ushort clientID)
    {
        bool suscessful = ServerSpawnPrefab(prefabName, uid,
            out GameObject networkObject, out NetworkedBehaviour behaviour);

        if (!suscessful)
            return;

        networkObject.transform.position = spawn.position;
        networkObject.transform.rotation = Quaternion.Euler(spawn.eulerAngles);


        PlayerManager player = behaviour as PlayerManager;
        player.Prefab = GetNetworkPrefab(prefabName);
        player.OwnerID = clientID;
        player.IsOwner = _clientID == clientID;
        networkObject.name = $"({clientID}) Player";
        player.EnableCompoents();
        PlayersManagers.Add(clientID, player);
    }

    private void ServerSendExistingObjects(IClient client)
    {
        foreach (NetworkedBehaviour item in NetworkedObjects.Values)
        {
            if (item.Prefab == null)
                continue;

            item.InitilizeData(out Message message, out DarkRiftWriter writer);
            client.SendMessage(message, SendMode.Reliable);
            message.Dispose();
            writer.Dispose();
        }
    }

    private void ServerFindNodeSpawnPoints()
    {
        GameObject[] gameObjects = GameObject.FindGameObjectsWithTag(_nodeSpawnPointTag);
        _nodeSpawns = new List<Transform>(gameObjects.Length);

        Debug.Log("Found " + gameObjects.Length);

        for (int i = 0; i < gameObjects.Length; i++)
        {
            Debug.Log($"{i} {gameObjects.Length} {_nodeSpawns.Count}");
            _nodeSpawns.Add(gameObjects[i].transform);
        }
    }

    private Transform ServerFindRandomNodeSpawn()
    {
        Transform spawn = _nodeSpawns[UnityEngine.Random.Range(0, _nodeSpawns.Count - 1)];
        int maxTries = 10;
        int currentTry = 0;

        while (spawn.childCount != 0 && currentTry < maxTries)
        {
            spawn = _nodeSpawns[UnityEngine.Random.Range(0, _nodeSpawns.Count - 1)];
            currentTry++;
        }

        return spawn;
    }

    private IEnumerator ServerNodeSpawnTimer()
    {
        while (_nodeTimerRunning)
        {
            ServerSpawnNodes();
            yield return _nodeDelay;
        }
    }

    private void ServerSpawnNodes()
    {
        int nodes = 0;

        for (int i = 0; i < _nodeSpawns.Count; i++)
        {
            if (_nodeSpawns[i].childCount > 0)
                nodes++;
        }

        if (nodes >= _nodeTarget)
            return;

        ServerSpawnNetworkedObject(_nodePrefab, Vector3.zero, new Vector3(90, 348.4829f), ServerFindRandomNodeSpawn());
    }

    private GameObject ServerSpawnNetworkedObject(GameObject prefab, Vector3 position, Vector3 rotation, Transform parent = null)
    {
        GameObject gameObject = Instantiate(prefab, parent);
        gameObject.transform.localPosition = position;
        gameObject.transform.localRotation = Quaternion.Euler(rotation);
        NetworkedBehaviour behaviour = gameObject.GetComponent<NetworkedBehaviour>();

        if (behaviour == null)
        {
            Debug.LogError($"{prefab.name} doesn't have NetworkedBehaviour");
            return null;
        }

        ushort uid = ServerGetUID();
        NetworkedObjects.Add(uid, behaviour);
        behaviour.UID = uid;
        behaviour.Prefab = prefab;


        behaviour.InitilizeData(out Message message, out DarkRiftWriter writer);

        ServerSendMessageToAll(message, SendMode.Reliable);

        message.Dispose();
        writer.Dispose();

        return gameObject;
    }

    #endregion

    #region Client Methods

    private void ClientRequestPlayer()
    {
        using (DarkRiftWriter writer = DarkRiftWriter.Create())
        {
            writer.Write(Client.ID);
            writer.Write(_playerPrefab.name);
            SendMessage(NetworkTags.RequestPlayer, writer, SendMode.Reliable);
        }
    }

    private void ClientMessageReceived(object sender, DarkRift.Client.MessageReceivedEventArgs args)
    {
        if (EnableDebugMessages)
            Debug.Log($"Received Message {args.Tag}");

        using (Message message = args.GetMessage())
        using (DarkRiftReader reader = message.GetReader())
        {
            switch (message.Tag)
            {
                case (ushort)NetworkTags.SpawnPrefab:
                    ClientSpawnPrefab(reader);
                    break;
                case (ushort)NetworkTags.PlayerDisconnected:
                    ClientPlayerDisconnected(reader);
                    break;
                case (ushort)NetworkTags.MoveObject:
                case (ushort)NetworkTags.ToolHide:
                case (ushort)NetworkTags.ToolSwitch:
                case (ushort)NetworkTags.HitNode:
                    ushort uid = reader.ReadUInt16();
                    if (NetworkedObjects.TryGetValue(uid, out NetworkedBehaviour behaviour))
                    {
                        behaviour.MessageReceived.Invoke(message, reader);
                    }
                    break;
            }
        }
    }

    private void ClientSpawnPrefab(DarkRiftReader reader)
    {
        string prefabName = reader.ReadString();
        GameObject prefab = GetNetworkPrefab(prefabName);

        if (prefab == null)
            return;

        GameObject networkObject = Instantiate(prefab);
        NetworkedBehaviour behaviour = networkObject.GetComponent<NetworkedBehaviour>();
        behaviour.Initialize(reader);
    }

    private void ClientPlayerDisconnected(DarkRiftReader reader)
    {
        ushort clientID = reader.ReadUInt16();
        RemovePlayer(clientID);
    }

    #endregion

    #region Helper Methods

    private GameObject GetNetworkPrefab(string prefabName)
    {
        GameObject prefab = null;

        for (int i = 0; i < NetworkedPrefabs.Count; i++)
        {
            if (NetworkedPrefabs[i].name == prefabName)
                prefab = NetworkedPrefabs[i];
        }

        if (prefab == null)
        {
            Debug.LogError($"Couldn't find \"{prefabName}\" in NetworkedPrefabs");
        }

        return prefab;
    }

    private void RemovePlayer(ushort id)
    {
        if (PlayersManagers.TryGetValue(id, out PlayerManager manager))
        {
            Destroy(manager.gameObject);
            PlayersManagers.Remove(id);
        }
        else
            Debug.LogError("Tried to remove player but not in our list");
    }

    public static void SendMessage(NetworkTags tag, DarkRiftWriter writer, SendMode sendMode)
    {
        using (Message message = Message.Create((ushort)tag, writer))
        {
            if (IsServer)
                ServerSendMessageToAll(message, sendMode);
            else
                _instance._client.SendMessage(message, sendMode);
        }
    }



    #endregion
}