-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathServer.cs
1102 lines (917 loc) · 40.1 KB
/
Server.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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Godot;
using System;
using System.IO;
using System.Collections.Generic;
using ProtoBuf;
using redhatgamedev.srt.v1;
using Serilog;
public partial class Server : Node
{
int DebugUIRefreshTime = 1; // 1000ms = 1sec
double DebugUIRefreshTimer = 0.0f;
Random rnd = new Random();
//levelSwitch = new LoggingLevelSwitch();
Serilog.Core.LoggingLevelSwitch levelSwitch = new Serilog.Core.LoggingLevelSwitch();
public Serilog.Core.Logger _serilogger;
AMQPserver MessageInterface;
[Export]
Godot.Collections.Dictionary<String, Node2D> playerObjects = new Godot.Collections.Dictionary<string, Node2D>();
// the "width" of a hex is 2 * size
[Export]
public Int32 SectorSize = 1600;
public Layout HexLayout;
int HexRatio;
// starting ring radius is zero - just one sector
[Export]
public int RingRadius = 0;
// the sector map will only store the number of players in each sector
// it only gets updated when a new player joins
[Export]
Godot.Collections.Dictionary<String, int> sectorMap = new Godot.Collections.Dictionary<string, int>();
[Export]
Godot.Collections.Dictionary<String, Node2D> sectorNodes = new Godot.Collections.Dictionary<String, Node2D>();
[Export]
public Int32 StarFieldRadiusPixels;
public Int32 PreviousStarFieldRadiusPixels = 1600;
private float NewStarFieldRadiusRatio = 1.0f;
// The starfield's center may shift during play at small ring sizes due to the
// way that sectors are added
[Export]
Vector2 StarFieldCenter = new Vector2(0, 0);
[Export]
float CameraMinZoom = 4f;
[Export]
float CameraMaxZoom = 0.1f;
[Export]
float CameraZoomStepSize = 0.1f;
Vector2 CameraCurrentZoom = new Vector2(1, 1);
Queue<Security> PlayerJoinQueue = new Queue<Security>();
public Queue<String> PlayerRemoveQueue = new Queue<String>();
public Queue<Security> SecurityEventQueue = new Queue<Security>();
public Queue<Command> GameEventQueue = new Queue<Command>();
/* PLAYER DEFAULTS AND CONFIG */
float PlayerDefaultThrust = 1f;
float PlayerDefaultMaxSpeed = 5;
float PlayerDefaultRotationThrust = 1.5f;
int PlayerDefaultHitPoints = 100;
int PlayerDefaultMissileSpeed = 300;
float PlayerDefaultMissileLife = 2;
int PlayerDefaultMissileDamage = 25;
int PlayerDefaultMissileReloadTime = 2;
/* END PLAYER DEFAULTS AND CONFIG */
// SCENE PRELOADS
PackedScene PlayerPackedScene = (PackedScene)ResourceLoader.Load("res://Player.tscn");
PackedScene SectorPackedScene = (PackedScene)ResourceLoader.Load("res://Sector.tscn");
// END SCENE PRELOADS
Label RingSize;
Label StarFieldRadiusSize;
Node SectorMap;
Node Players;
StarFieldRadius StarFieldRing;
VBoxContainer theCanvas;
LineEdit playerID;
Tree uiPlayerTree;
Camera2D rtsCamera;
Camera2D currentCamera;
/* debuggy stuff for messaging */
long messageByteTotals;
float messageByteTimer;
int messageByteTimerTimeMax = 1;
long frameCounter;
int framePortion;
/* snapshot interpolation things */
public UInt32 sequenceNumber = 1;
// number of ms to wait before sending updates
long frameTimerMs = 50;
long lastSentTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
long GetEventMessageBytes(GameEvent gameEvent)
{
MemoryStream st = new MemoryStream();
Serializer.Serialize<GameEvent>(st, gameEvent);
return st.Length;
}
void SendGameUpdates()
{
long timeNow = DateTimeOffset.Now.ToUnixTimeMilliseconds();
long timeDiff = timeNow - lastSentTime;
if (timeDiff < frameTimerMs)
{
_serilogger.Verbose($"Server.cs: NOT sending message - since last message sent: {timeDiff}ms");
return;
}
_serilogger.Verbose("Server.cs: Sending updates about game state to clients");
lastSentTime = timeNow;
int x = 0;
// begin to build the GameEvent update
GameEvent updateEvent = _GetNewGameEvent(GameEvent.GameEventType.GameEventTypeUpdate);
Godot.Collections.Array<Node> players = _GetNodesFromGroup("player_ships");
Godot.Collections.Array<Node> missiles = GetTree().GetNodesInGroup("missiles");
if (players.Count == 0 && missiles.Count == 0)
{
_serilogger.Verbose("Server.cs: No players or missiles in the game");
return;
}
// iterate over the player ships and then add their objects to the GameObjects List
foreach (PlayerShip player in players)
{
x += 1;
_serilogger.Verbose($"Server.cs: Adding player to game event: {player.uuid}");
// create the buffer for the specific player
GameEvent.GameObject gameObject = player.CreatePlayerGameObjectBuffer();
// add the buffer to the GameObjects List
updateEvent.GameObjects.Add(gameObject);
}
x = 0;
// TODO: we never send a create message for the missile
// iterate over the missiles and then add their objects to the GameObjects List
foreach (SpaceMissile missile in GetTree().GetNodesInGroup("missiles"))
{
x += 1;
_serilogger.Verbose($"Server.cs: Adding missile to game event: {missile.uuid}");
// create the buffer for the missile
GameEvent.GameObject gameObject = missile.CreateMissileGameObjectBuffer(missile.MyPlayer.uuid);
// add the buffer to the GameObjects List
updateEvent.GameObjects.Add(gameObject);
}
// send the update event
MessageInterface.SendGameEvent(updateEvent);
// add byte totals to counter
messageByteTotals += GetEventMessageBytes(updateEvent);
_serilogger.Verbose($"Server.cs: Message bytes after update in frame {frameCounter}.{framePortion}.{x}: {messageByteTotals}");
}
// called from the player model
// should this be handled IN the player model itself?
// TODO: this seems to assume all removes are destroys, but what about simple leaves?
public void RemovePlayer(String UUID)
{
_serilogger.Debug($"Server.cs: Removing player: {UUID}");
// playerObjects stores the base node which is the Area2D.
// we need the PlayerShip child.
Node2D thePlayerToRemove = playerObjects[UUID];
PlayerShip thePlayer = thePlayerToRemove.GetNode<PlayerShip>("PlayerShip");
// create the buffer for the specific player and send it
GameEvent gameEvent = _GetNewGameEvent(GameEvent.GameEventType.GameEventTypeDestroy);
GameEvent.GameObject gameObject = new GameEvent.GameObject();
gameObject = thePlayer.CreatePlayerGameObjectBuffer();
gameEvent.GameObjects.Add(gameObject);
// TODO: should this get wrapped with a try or something?
playerObjects.Remove(UUID);
thePlayerToRemove.QueueFree();
// send the player create event message
MessageInterface.SendGameEvent(gameEvent);
}
public void RemoveMissile(SpaceMissile missile)
{
_serilogger.Debug($"Server.cs: Removing missile: {missile.uuid}");
// TODO: should this get wrapped with a try or something?
missile.QueueFree();
// create the buffer for the missile and send it
GameEvent gameEvent = _GetNewGameEvent(GameEvent.GameEventType.GameEventTypeDestroy);
GameEvent.GameObject gameObject = new GameEvent.GameObject();
gameObject = missile.CreateMissileGameObjectBuffer(missile.MyPlayer.uuid);
gameEvent.GameObjects.Add(gameObject);
// send the player create event message
MessageInterface.SendGameEvent(gameEvent);
}
Hex TraverseSectors()
{
Hex theCenter = new Hex(0, 0, 0);
_serilogger.Debug($"Server.cs: Traversing the sectors");
// based around the function from
// https://www.redblobgames.com/grids/hexagons/#rings
// need to iterate over all the rings
for (int currentRing = 1; currentRing <= RingRadius; currentRing++)
{
_serilogger.Debug($"Server.cs: Traversing ring {currentRing}");
// pick the 0th sector in a ring
Hex theSector = theCenter.Add(Hex.directions[4].Scale(currentRing));
_serilogger.Debug($"Server.cs: starting with sector {theSector.q},{theSector.r}");
// traverse the ring
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < currentRing; j++)
{
string theKey = $"{theSector.q},{theSector.r}";
_serilogger.Debug($"Server.cs: Checking sector {theKey}");
if (sectorMap.ContainsKey(theKey))
{
// the sector map has the sector we're looking at, so verify how many
// players are in it. if there are less than two players, use it.
if (sectorMap[theKey] < 2)
{
_serilogger.Debug($"Server.cs: Less than two players ({sectorMap[theKey]}) in {theKey}, so choosing this one");
return theSector;
}
}
else
{
// the sector map doesn't have the key for the sector we're looking
// at. this means the sector definitely has zero players in it.
_serilogger.Debug($"Server.cs: {theKey} not found in sectorMap, so choosing this one");
return theSector;
}
// if we get here, it means that the current sector is full, so move
// to the next neighbor
_serilogger.Debug($"Server.cs: {theKey} is full with {sectorMap[theKey]} players, moving on");
theSector = theSector.Neighbor(i);
}
}
}
// we got to the end of the rings without finding a sector, so make a new
// ring and return that ring's first sector
_serilogger.Debug($"Server.cs: Completed traversing ring {RingRadius}, incrementing and returning 0th sector of new ring");
RingRadius++;
_serilogger.Debug($"Server.cs: New ringradius is {RingRadius}");
Hex hexToReturn = theCenter.Add(Hex.directions[4].Scale(RingRadius));
_serilogger.Debug($"Server.cs: 0th sector of new ring is {hexToReturn.q},{hexToReturn.r}");
return hexToReturn;
}
void UpdateSectorMap()
{
// re-initilize the sector map
// clear the dictionary for rebuild
sectorMap.Clear();
_serilogger.Debug($"Server.cs: Updating sector map");
// delete all of the drawn sectors unless there's no players
Godot.Collections.Array<Node> players = _GetNodesFromGroup("player_ships");
if (players.Count != 0) {
_serilogger.Debug($"Server.cs: There are players in the player_ships group, so clearing the sector nodes");
sectorNodes.Clear();
foreach (Node sector in _GetNodesFromGroup("sectors"))
{
sector.QueueFree();
}
}
_serilogger.Debug($"Server.cs: Currently {players.Count} players in 'player_ships' group");
foreach (PlayerShip player in players)
{
_serilogger.Debug($"Server.cs: Checking where {player.uuid} is in sector map");
FractionalHex theHex = HexLayout.PixelToHex(new Point(player.GlobalPosition.X, player.GlobalPosition.Y));
Hex theRoundedHex = theHex.HexRound();
// the key can be axial coordinates
String theSectorKey = $"{theRoundedHex.q},{theRoundedHex.r}";
_serilogger.Debug($"Server.cs: player {player.uuid} sector is {theSectorKey}");
// check if the key exists in the dict
if (sectorMap.ContainsKey(theSectorKey))
{
// increment it if it does
sectorMap[theSectorKey] += 1;
_serilogger.Debug($"Server.cs: {theSectorKey}: {sectorMap[theSectorKey]}");
}
else
{
// initialize it to 1 if it doesn't
_serilogger.Debug($"Server.cs: {theSectorKey} didn't exist, initializing to 1");
sectorMap[theSectorKey] = 1;
_serilogger.Debug($"Server.cs: {theSectorKey}: {sectorMap[theSectorKey]}");
}
}
}
void DrawSectorMap()
{
// recreate the sector nodes for all the present keys
_serilogger.Debug($"Server.cs: Iterating over sectormap's keys to place sector nodes");
foreach (string sector in sectorMap.Keys)
{
_serilogger.Debug($"Server.cs: Current sector is {sector}");
String[] sector_parts = sector.Split(',');
// q + r + s must equal zero
int q = sector_parts[0].ToInt();
int r = sector_parts[1].ToInt();
int s = 0 - q - r;
_CreateSector(new Hex(q,r,s));
}
}
void DrawStarFieldRing()
{
StarFieldRing.radius = StarFieldRadiusPixels;
if (StarFieldRadiusPixels != PreviousStarFieldRadiusPixels)
{
_serilogger.Debug($"Server.cs: StarFieldRing applying scale {StarFieldRing.Scale}");
StarFieldRing.ApplyScale(new Vector2(NewStarFieldRadiusRatio, NewStarFieldRadiusRatio));
PreviousStarFieldRadiusPixels = StarFieldRadiusPixels;
}
}
public void InstantiateMissile(SpaceMissile missile)
{
// this only sends the missile creation event buffer
_serilogger.Debug($"Server.cs: Sending missile creation message for missile {missile.uuid} player {missile.MyPlayer.uuid}");
// create a GameEvent for a missile
GameEvent egeb = _GetNewGameEvent(GameEvent.GameEventType.GameEventTypeCreate);
egeb.GameObjects.Add(missile.CreateMissileGameObjectBuffer(missile.MyPlayer.uuid));
// send the missile create event message
MessageInterface.SendGameEvent(egeb);
}
void InstantiatePlayer(String UUID)
{
// Update the sector map in preparation for traversing the rings, expanding
// the radius, and etc. need to do this before adding the new player object
// because we don't know where that player will go until we traverse the
// existing sectors, and because the physics process will kick in as soon
// as the node is created
_serilogger.Debug($"Server.cs: Instantiating player {UUID}");
UpdateSectorMap();
// start with the center
Hex theSector = new Hex(0, 0, 0);
// C# has no preload, so you have to always use ResourceLoader.Load<PackedScene>().
Area2D playerShipThingInstance = (Area2D)PlayerPackedScene.Instantiate();
PlayerShip newPlayer = playerShipThingInstance.GetNode<PlayerShip>("PlayerShip");
newPlayer.uuid = UUID;
// assign the configured values
newPlayer.Thrust = PlayerDefaultThrust;
newPlayer.MaxSpeed = PlayerDefaultMaxSpeed;
newPlayer.RotationThrust = PlayerDefaultRotationThrust;
newPlayer.HitPoints = PlayerDefaultHitPoints;
newPlayer.MissileSpeed = PlayerDefaultMissileSpeed;
newPlayer.MissileLife = PlayerDefaultMissileLife;
newPlayer.MissileDamage = PlayerDefaultMissileDamage;
_serilogger.Debug($"Server.cs: Adding {UUID} to playerObjects");
playerObjects.Add(UUID, playerShipThingInstance);
newPlayer.AddToGroup("player_ships");
_serilogger.Debug($"Server.cs: Current count of playerObjects: {playerObjects.Count}");
// if there are more than two players, it means we are now at the point
// where we have to start calculating ring things
if (playerObjects.Count > 2)
{
// if the ring radius is zero, and we have more than two players, we need
// to increase it, otherwise things will already blow up
if (RingRadius == 0)
{
_serilogger.Debug($"Server.cs: playerObjects count > 2 and ringradius == 0 so incrementing");
RingRadius++;
}
// it's possible that we have insufficient players in sector 0,0,0, so
// check that first for funzos
int qty;
if (sectorMap.TryGetValue("0,0", out qty))
{
if (qty < 2)
{
// do nothing since we already assigned the sector to use to 0,0,0
_serilogger.Debug($"Server.cs: Insufficient players in sector 0 so will add player there");
}
else
{
theSector = TraverseSectors();
}
}
}
_serilogger.Debug($"Server.cs: Selected sector for player {UUID} is {theSector.q},{theSector.r}");
// increment whatever sector this new player is going into
string sector_key = theSector.q + "," + theSector.r;
if (sectorMap.ContainsKey(sector_key))
{
sectorMap[sector_key] += 1;
}
else
{
sectorMap[sector_key] = 1;
}
_serilogger.Debug($"Server.cs: Sector {theSector.q},{theSector.r} now has {sectorMap[sector_key]}");
// reset the starfield radius - should also move the center
_CalcStarFieldRadius();
DrawStarFieldRing();
// now that the sector to insert the player has been selected, find its
// pixel center
Point theSectorCenter = HexLayout.HexToPixel(theSector);
_serilogger.Debug($"Server.cs: Center of selected sector: {theSectorCenter.x},{theSectorCenter.y}");
// TODO: need to ensure players are not on top of one another for real. we
// will spawn two players into a sector to start, so we should check if
// there's already a player in the sector first. if there is, we should
// place the new player equidistant from the already present player
// badly randomize start position
int theMin = (int)(SectorSize * 0.3);
int xOffset = rnd.Next(-1 * theMin, theMin);
int yOffset = rnd.Next(-1 * theMin, theMin);
int finalX = (Int32)theSectorCenter.x + xOffset;
int finalY = (Int32)theSectorCenter.y + yOffset;
_serilogger.Debug($"Server.cs: Placing player at {finalX},{finalY}");
newPlayer.GlobalPosition = new Vector2(x: (Int32)theSectorCenter.x + xOffset, y: (Int32)theSectorCenter.y + yOffset);
// connect the ship thing input signal so that we can catch when a ship was clicked in the debug UI
playerShipThingInstance.InputEvent += (viewport, theEvent, shapeIdx) => _on_ShipThings_input_event(viewport, theEvent, shapeIdx, newPlayer); // there is a closure around newPlayer now
Players.AddChild(playerShipThingInstance);
_serilogger.Information($"Server.cs: Added player {UUID} instance!");
// create a GameEvent for the player joining
GameEvent egeb = _GetNewGameEvent(GameEvent.GameEventType.GameEventTypeCreate);
egeb.GameObjects.Add(newPlayer.CreatePlayerGameObjectBuffer());
// send the player create event message
MessageInterface.SendGameEvent(egeb);
DrawSectorMap();
}
void ProcessMoveCommand(Command cb)
{
_serilogger.Verbose("Server.cs: Processing move command!");
String playerUUID = cb.Uuid;
Node2D playerRoot;
if (false == playerObjects.TryGetValue(playerUUID, out playerRoot))
{
_serilogger.Debug($"Server.cs: ProcessMoveCommand failed to get playerRoot from playerObjects! uuid specified: {playerUUID}");
return;
}
PlayerShip movePlayer = playerRoot.GetNode<PlayerShip>("PlayerShip");
// process thrust and rotation
Vector2 thrust = new Vector2(cb.InputX, cb.InputY);
// push the thrust input onto the player's array
movePlayer.MovementQueue.Enqueue(thrust);
_serilogger.Verbose("Server.cs: ProcessMoveCommand movePlayer.MovementQueue.Count is " + movePlayer.MovementQueue.Count);
}
void ProcessShootCommand(Command cb)
{
_serilogger.Debug("Server.cs: Processing shoot command!");
// find the PlayerShip
String playerUUID = cb.Uuid;
Node2D playerRoot;
if (false == playerObjects.TryGetValue(playerUUID, out playerRoot))
{
_serilogger.Debug($"Server.cs: ProcessShootCommand failed to get playerRoot from playerObjects! uuid specified: {playerUUID}");
return;
}
PlayerShip movePlayer = playerRoot.GetNode<PlayerShip>("PlayerShip");
// TODO: should we perform a check here to see if we should bother firing
// the missile, or leave that to the playership.firemissile method alone?
String missileUUID;
// check if a missile uuid was suggested and, if not, generate one
if (cb.MissileUuid == "")
{
_serilogger.Debug("supplied missileUUID was null - generating");
missileUUID = System.Guid.NewGuid().ToString();
}
else
{
missileUUID = cb.MissileUuid;
}
_serilogger.Debug($"missile uuid is: {missileUUID}");
movePlayer.FireMissile(missileUUID);
}
void ProcessPlayerLeave(Security securityBuffer)
{
// find the player object
Node2D playerShip;
if (playerObjects.TryGetValue(securityBuffer.Uuid, out playerShip))
{
// we were able to find an object, so do the leave
_serilogger.Debug($"Server.cs: Leaving player with UUID: {securityBuffer.Uuid}");
// TODO: should this be a specific leave instead of destroying a player?
RemovePlayer(securityBuffer.Uuid);
}
}
void ProcessPlayerJoins()
{
while (PlayerJoinQueue.Count > 0)
{
Security scb = PlayerJoinQueue.Dequeue();
InstantiatePlayer(scb.Uuid);
}
}
void ProcessPlayerRemoval()
{
while (PlayerRemoveQueue.Count > 0)
{
RemovePlayer(PlayerRemoveQueue.Dequeue());
}
}
void ProcessGameEvents()
{
while (GameEventQueue.Count > 0)
{
_serilogger.Verbose($"Server.cs: ProcessGameEvents::GameEventQueue.Count > 0 and is {GameEventQueue.Count}");
Command commandBuffer = GameEventQueue.Dequeue();
switch (commandBuffer.command_type)
{
case Command.CommandType.CommandTypeMove:
_serilogger.Verbose("Server.cs: Move command received");
ProcessMoveCommand(commandBuffer);
break;
case Command.CommandType.CommandTypeShoot:
_serilogger.Verbose("Server.cs: Shoot command received");
ProcessShootCommand(commandBuffer);
break;
case Command.CommandType.CommandTypeUnspecified:
_serilogger.Error("Server.cs: Unspecified command received");
break;
}
}
}
void ProcessSecurityEvents()
{
while (SecurityEventQueue.Count > 0)
{
_serilogger.Debug($"Server.cs: ProcessSecurityEvents::SecurityEventQueue.Count > 0 and is {SecurityEventQueue.Count}");
Security securityBuffer = SecurityEventQueue.Dequeue();
switch (securityBuffer.security_type)
{
case Security.SecurityType.SecurityTypeUnspecified:
_serilogger.Error("Server.cs: Received an unspecified security event");
break;
case Security.SecurityType.SecurityTypeAnnounce:
_serilogger.Debug($"Server.cs: Received a client announce request from {securityBuffer.Uuid}");
SendAnnounceDetails(securityBuffer.Uuid);
break;
case Security.SecurityType.SecurityTypeJoin:
_serilogger.Debug($"Server.cs: Got player join for UUID: {securityBuffer.Uuid}");
// TODO: buffer this because sometimes it collides with sending game
// updates and an exception is fired because the player collection is
// modified during looping over it
PlayerJoinQueue.Enqueue(securityBuffer);
break;
case Security.SecurityType.SecurityTypeLeave:
_serilogger.Debug($"Server.cs: Got player leave for UUID: {securityBuffer.Uuid}");
ProcessPlayerLeave(securityBuffer);
break;
}
}
}
void ProcessInputEvent(Vector2 velocity, Vector2 shoot)
{
// if there is no player in the dictionary, do nothing
// this catches accidental keyboard hits
if (!playerObjects.ContainsKey(playerID.Text)) { return; }
// there was some kind of input, so construct a message to send to the server
//CommandBuffer cb = new CommandBuffer();
//cb.Type = CommandBuffer.CommandBufferType.Rawinput;
//RawInputCommandBuffer ricb = new RawInputCommandBuffer();
//ricb.Type = RawInputCommandBuffer.RawInputCommandBufferType.Dualstick;
//ricb.Uuid = textField.Text;
//DualStickRawInputCommandBuffer dsricb = new DualStickRawInputCommandBuffer();
//if ( (velocity.Length() > 0) || (shoot.Length() > 0) )
if (velocity.Length() > 0)
{
_serilogger.Verbose("Server.cs: velocity length is greater than zero - move");
Command cb = new Command();
cb.command_type = Command.CommandType.CommandTypeMove;
cb.Uuid = playerID.Text;
cb.InputX = (int)velocity.X;
cb.InputY = (int)velocity.Y;
MessageInterface.SendCommand(cb);
}
if (shoot.Length() > 0)
{
_serilogger.Verbose("Server.cs: shoot length is greater than zero - shoot");
Command cb = new Command();
cb.command_type = Command.CommandType.CommandTypeShoot;
cb.Uuid = playerID.Text;
cb.InputX = (int)shoot.X;
cb.InputY = (int)shoot.Y;
MessageInterface.SendCommand(cb);
}
}
// Configuration and Related
public void SendAnnounceDetails(String UUID)
{
// create the announce message
Security announceMessage = new Security();
announceMessage.security_type = Security.SecurityType.SecurityTypeAnnounce;
announceMessage.Uuid = UUID;
announceMessage.ShipThrust = PlayerDefaultThrust;
announceMessage.MaxSpeed = PlayerDefaultMaxSpeed;
announceMessage.RotationThrust = PlayerDefaultRotationThrust;
announceMessage.HitPoints = PlayerDefaultHitPoints;
announceMessage.MissileSpeed = PlayerDefaultMissileSpeed;
announceMessage.MissileLife = PlayerDefaultMissileLife;
announceMessage.MissileDamage = PlayerDefaultMissileDamage;
announceMessage.MissileReload = PlayerDefaultMissileReloadTime;
_serilogger.Debug($"Server.cs: Sending announce details to client {UUID}");
MessageInterface.SendSecurity(announceMessage);
}
public void LoadConfig()
{
_serilogger.Information("Server.cs: Configuring");
var serverConfig = new ConfigFile();
// save the config file load status to err to check which value to use (config or env) later
Error err = serverConfig.Load("Config/server.cfg");
int DesiredLogLevel = 3;
// if the file was loaded successfully, read the vars
if (err == Error.Ok)
{
SectorSize = (Int32)serverConfig.GetValue("game", "sector_size");
// player settings
// https://stackoverflow.com/questions/24447387/cast-object-containing-int-to-float-results-in-invalidcastexception
PlayerDefaultThrust = (float)serverConfig.GetValue("player", "thrust");
PlayerDefaultMaxSpeed = (float)serverConfig.GetValue("player", "max_speed");
PlayerDefaultRotationThrust = (float)serverConfig.GetValue("player", "rotation_thrust");
PlayerDefaultHitPoints = (int)serverConfig.GetValue("player", "hit_points");
PlayerDefaultMissileSpeed = (int)serverConfig.GetValue("player", "missile_speed");
PlayerDefaultMissileLife = (float)serverConfig.GetValue("player", "missile_life");
PlayerDefaultMissileDamage = (int)serverConfig.GetValue("player", "missile_damage");
PlayerDefaultMissileReloadTime = (int)serverConfig.GetValue("player", "missile_reload");
DesiredLogLevel = (int)serverConfig.GetValue("game", "log_level");
}
// pull values from env -- will get nulls if any vars are not set
String envSectorSize = System.Environment.GetEnvironmentVariable("SRT_SECTOR_SIZE");
String envPlayerThrust = System.Environment.GetEnvironmentVariable("SRT_PLAYER_THRUST");
String envPlayerSpeed = System.Environment.GetEnvironmentVariable("SRT_PLAYER_SPEED");
String envPlayerRotation = System.Environment.GetEnvironmentVariable("SRT_PLAYER_ROTATION");
String envPlayerHealth = System.Environment.GetEnvironmentVariable("SRT_PLAYER_HEALTH");
String envMissileSpeed = System.Environment.GetEnvironmentVariable("SRT_MISSILE_SPEED");
String envMissileLife = System.Environment.GetEnvironmentVariable("SRT_MISSILE_LIFE");
String envMissileDamage = System.Environment.GetEnvironmentVariable("SRT_MISSILE_DAMAGE");
String envMissileReloadTime = System.Environment.GetEnvironmentVariable("SRT_MISSILE_RELOAD_TIME");
String envLogLevel = System.Environment.GetEnvironmentVariable("SRT_LOG_LEVEL");
// override any loaded config with env
if (envSectorSize != null) SectorSize = Int32.Parse(envSectorSize);
if (envPlayerThrust != null) PlayerDefaultThrust = float.Parse(envPlayerThrust);
if (envPlayerSpeed != null) PlayerDefaultMaxSpeed = float.Parse(envPlayerSpeed);
if (envPlayerRotation != null) PlayerDefaultRotationThrust = float.Parse(envPlayerSpeed);
if (envPlayerHealth != null) PlayerDefaultHitPoints = int.Parse(envPlayerHealth);
if (envMissileSpeed != null) PlayerDefaultMissileSpeed = int.Parse(envMissileSpeed);
if (envMissileLife != null) PlayerDefaultMissileLife = float.Parse(envMissileLife);
if (envMissileDamage != null) PlayerDefaultMissileDamage = int.Parse(envMissileDamage);
if (envMissileReloadTime != null) PlayerDefaultMissileReloadTime = int.Parse(envMissileReloadTime);
if (envLogLevel != null) DesiredLogLevel = int.Parse(envLogLevel);
switch (DesiredLogLevel)
{
case 0:
_serilogger.Information("Server.cs: Setting minimum log level to: Fatal");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Fatal;
break;
case 1:
_serilogger.Information("Server.cs: Setting minimum log level to: Error");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Error;
break;
case 2:
_serilogger.Information("Server.cs: Setting minimum log level to: Warning");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Warning;
break;
case 3:
_serilogger.Information("Server.cs: Setting minimum log level to: Information");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Information;
break;
case 4:
_serilogger.Information("Server.cs: Setting minimum log level to: Debug");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
break;
case 5:
_serilogger.Information("Server.cs: Setting minimum log level to: Verbose");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Verbose;
break;
default:
_serilogger.Information("Server.cs: Unknown log level specified, defaulting to: Information");
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Debug;
break;
}
// output the config state
_serilogger.Information($"Server.cs: Sector Size: {SectorSize}");
_serilogger.Information($"Server.cs: Player Thrust: {PlayerDefaultThrust}");
_serilogger.Information($"Server.cs: Player Speed: {PlayerDefaultMaxSpeed}");
_serilogger.Information($"Server.cs: Player Rotation: {PlayerDefaultRotationThrust}");
_serilogger.Information($"Server.cs: Player HP: {PlayerDefaultHitPoints}");
_serilogger.Information($"Server.cs: Missile Speed: {PlayerDefaultMissileSpeed}");
_serilogger.Information($"Server.cs: Missile Life: {PlayerDefaultMissileLife}");
_serilogger.Information($"Server.cs: Missile Damage: {PlayerDefaultMissileDamage}");
_serilogger.Information($"Server.cs: Missile Reload Time: {PlayerDefaultMissileReloadTime}");
}
void UpdateDebugUI()
{
// clear the list and then iterate over all players to rebuild it
uiPlayerTree.Clear();
TreeItem UIPlayerTreeRoot = uiPlayerTree.CreateItem();
Godot.Collections.Array<Node> players = _GetNodesFromGroup("player_ships");
foreach (PlayerShip player in players)
{
TreeItem playerTreeItem = uiPlayerTree.CreateItem(UIPlayerTreeRoot);
playerTreeItem.SetText(0, player.uuid);
}
RingSize.Text = RingRadius.ToString();
StarFieldRadiusSize.Text = StarFieldRadiusPixels.ToString();
}
// Godot Builtins
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
levelSwitch.MinimumLevel = Serilog.Events.LogEventLevel.Information;
_serilogger = new LoggerConfiguration().MinimumLevel.ControlledBy(levelSwitch).WriteTo.Console().CreateLogger();
_serilogger.Information("Server.cs: Space Ring Things (SRT) Game Server");
_serilogger.Information("Server.cs: Attempting AMQP initialization");
MessageInterface = new AMQPserver();
MessageInterface.Name = "AMQP_Server";
AddChild(MessageInterface);
_serilogger.Information("Server.cs: Beginning game server");
LoadConfig();
// initialize the starfield size to the initial sector size
// the play area is clamped
StarFieldRadiusPixels = SectorSize;
PreviousStarFieldRadiusPixels = SectorSize;
// initialize the hexboard layout
HexLayout = new Layout(Layout.flat, new Point(SectorSize, SectorSize), new Point(0, 0));
// grab needed elements for later
rtsCamera = GetNode<Camera2D>("RTS-Camera2D");
theCanvas = GetNode<VBoxContainer>("DebugUI/DebugStack");
playerID = theCanvas.GetNode<LineEdit>("PlayerID");
uiPlayerTree = theCanvas.GetNode<Tree>("CurrentPlayerTree");
RingSize = theCanvas.GetNode<Label>("RingSizeContainer/RingSize");
StarFieldRadiusSize = theCanvas.GetNode<Label>("StarfieldSizeContainer/StarfieldRadiusSize");
SectorMap = GetNode("SectorMap");
Players = GetNode("Players");
StarFieldRing = GetNode<StarFieldRadius>("StarFieldRadius");
DrawStarFieldRing();
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(double delta)
{
ProcessSecurityEvents();
ProcessGameEvents();
ProcessPlayerRemoval();
// look for any inputs, subsequently sent a control message
var velocity = Vector2.Zero; // The player's movement direction.
var shoot = Vector2.Zero; // the player's shoot status
if (Input.IsActionPressed("rotate_right"))
{
velocity.X += 1;
}
if (Input.IsActionPressed("rotate_left"))
{
velocity.X -= 1;
}
if (Input.IsActionPressed("thrust_forward"))
{
velocity.Y += 1;
}
if (Input.IsActionPressed("thrust_reverse"))
{
velocity.Y -= 1;
}
if (Input.IsActionPressed("fire"))
{
shoot.Y = 1;
}
if ((velocity.Length() > 0) || (shoot.Length() > 0))
{
// TODO: this should probably be putting things on the queue instead
ProcessInputEvent(velocity, shoot);
}
ProcessPlayerJoins();
SendGameUpdates();
// https://gdscript.com/solutions/godot-timing-tutorial/
// check if we should update the debug UI, which itself should only be done if
// we are in a graphical mode
// TODO: only if in graphical debug mode
// TODO: should also probably use timer node
DebugUIRefreshTimer += delta;
if (DebugUIRefreshTimer >= DebugUIRefreshTime)
{
// update the UI tree
DebugUIRefreshTimer = 0;
_serilogger.Verbose($"Server.cs: Updating UI tree");
UpdateDebugUI();
}
}
// Internal Signals
void _on_FocusAPlayer_pressed()
{
// loosely based on: https://godotengine.org/qa/116981/object-follow-mouse-in-radius
// get the UUID of the text box and set that ship's camera to active
if (playerObjects.ContainsKey(playerID.Text))
{
Node2D playerForCamera = playerObjects[playerID.Text];
Camera2D playerCamera = playerForCamera.GetNode<Camera2D>("PlayerShip/Camera2D");
if (!playerCamera.IsCurrent())
{
// clear the RTS camera's current
// rtsCamera.ClearCurrent();
playerCamera.MakeCurrent();
playerCamera.GetParent<PlayerShip>().isFocused = true;
currentCamera = playerCamera;
}
}
}
void _on_UnFocusAPlayer_pressed()
{
// currentCamera.ClearCurrent();
currentCamera.GetParent<PlayerShip>().isFocused = false;
currentCamera = null;
rtsCamera.MakeCurrent();
}
// TODO: improve via signal connection passing in the tree as an arg
void _on_CurrentPlayerTree_item_selected()
{
// figure out which tree item was selected
_serilogger.Debug($"Server.cs: Handling debug UI tree clicked");
TreeItem selected = uiPlayerTree.GetSelected();
_serilogger.Debug($"Server.cs: Tree item selected: {selected.GetText(0)}");
// update the debug UI text field to match the selected item
// this causes the debug UI to re-focus on the selected item
LineEdit textField = theCanvas.GetNode<LineEdit>("PlayerID");
textField.Text = selected.GetText(0);
}
// TODO: should move debug to its own scene that's optionally loaded
void _on_JoinAPlayer_pressed()
{
_serilogger.Debug($"Server.cs: Join button pressed for UUID: {playerID.Text}");
// don't do anything if this UUID already exists
if (playerObjects.ContainsKey(playerID.Text))
{
_serilogger.Debug($"Server.cs: UUID already exists, doing nothing: {playerID.Text}");
return;
}
_serilogger.Debug($"Server.cs: Sending join with UUID: {playerID.Text}");
// construct a join message from the text in the debug field
//SecurityCommandBuffer scb = new SecurityCommandBuffer();
Security scb = new Security();
scb.Uuid = playerID.Text;
scb.security_type = Security.SecurityType.SecurityTypeJoin;
MessageInterface.SendSecurityDebug(scb);
}
void _on_DeleteAPlayer_pressed()
{
_serilogger.Debug($"Server.cs: Delete button pressed for UUID: {playerID.Text}");
// check if the playerobject dictionary has an entry for the uuid in the textfield
Node2D selectedPlayerNode2D;
if (playerObjects.TryGetValue(playerID.Text, out selectedPlayerNode2D))
{
// it does, so remove that player
_serilogger.Debug($"Server.cs: Removing player with UUID: {playerID.Text}");
RemovePlayer(playerID.Text);
}
}
void _on_AddRandomPlayer_pressed()
{
_serilogger.Debug($"Server.cs: Add random button pressed");
string newPlayerUUID = System.Guid.NewGuid().ToString().Remove(0, 29);
_serilogger.Information($"Server.cs: Add random player {newPlayerUUID}");