-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGameplay.cs
1512 lines (1233 loc) · 70.2 KB
/
Gameplay.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
// Copyright 2024 Argus Labs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ArgusLabs.DF.Core.Communications;
using ArgusLabs.DF.Core.Configs;
using ArgusLabs.DF.Core.Space;
using ArgusLabs.DF.Input;
using ArgusLabs.DF.UI.Utilities;
using ArgusLabs.WorldEngineClient.Communications;
using Smonch.CyclopsFramework;
using Smonch.CyclopsFramework.Extensions;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.Pool;
using static Unity.Mathematics.math;
using Matrix4x4 = UnityEngine.Matrix4x4;
using Quaternion = UnityEngine.Quaternion;
using Vector2 = UnityEngine.Vector2;
using Vector3 = UnityEngine.Vector3;
namespace ArgusLabs.DF.Core.States
{
// Scope notes: This is instantiated in Bootstrap and nothing else has access, even through Bootstrap.
public sealed class Gameplay : CyclopsGameState
{
private const string ExplorerTag = "explorer";
private const string LeaderboardTag = "leaderboard";
private const string ZoomTag = "zoom";
private const float OrthoStepScale = 1.618f;
private const float MinOrthoSize = 1.618f;
// Dependencies
private readonly GameplayConfig _gameplayConfig;
private readonly EventManager _eventManager;
private readonly Player _player;
private readonly SpaceMap _map;
private DfInputActions.GameplayActions _gameplayInput;
private readonly Camera _spaceCamera;
private readonly OverlayController _overlay;
private readonly MeshAssetsConfig _transportShipConfig;
private readonly PlanetAssetsConfig[] _planetAssetConfigs;
private readonly WorldClock _worldClock;
private readonly GameInstanceInfo _worldInstanceInfo;
private CyclopsStateMachine _inputStateMachine;
private Planet _homePlanet;
private Sector _homeSector;
private Explorer _explorer;
private bool _isPlacingExplorer;
private Planet _hitTestResultPlanet;
private Vector2 _hitTestPosition;
private Vector2 _selectionWorldPosition;
private Planet _targetedPlanet;
private Planet _selectedPlanet;
private double _energyTransferScale = 1.0;
private float _zoomProgress;
private enum DebugMode
{
Inactive = 0,
Basic,
Extra,
BasicWithPlanets,
ExtraWithPlanets
}
private DebugMode _debugMode = DebugMode.Basic;
private RenderBatcher[] _renderBatchers;
private readonly HashSet<Planet> _planetsOnScreen = new(); //planets on screen means all planet that are on screen regardless of the lod
private readonly Dictionary<string, Player> _playersByPersonaTag = new();
private readonly HashSet<ulong> _clientEnergyTransferIds = new();
private readonly PlayerColorManager _playerColorManager = new (maxUniqueColors: 12); // TODO: Set this via config.
private readonly Queue<string> _errorMessageQueue = new();
private string _mostRecentErrorMessage = string.Empty;
private readonly float _squareDrawZoomLimit = 1000f; //square (grid pointer and explorer) won't be drawn when camera orthographic size is higher than this
// Note: Please cache these values if performance is ever a concern. This is fine for now.
private float LogMaxOrthoSize => Mathf.Log(MaxOrthoSize, 1.618f);
private float NormalizedOrthoSize => Mathf.InverseLerp(MinOrthoSize, LogMaxOrthoSize, Mathf.Log(_spaceCamera.orthographicSize, 1.618f));
private Vector2 MouseWorldPosition => _spaceCamera.ScreenToWorldPoint(Mouse.current.position.value);
private Vector2Int MouseGridPosition => Vector2Int.RoundToInt(MouseWorldPosition);
// We don't use this inefficiently but Rider won't stop complaining. This fixes it.
private Transform SpaceCameraTransform { get; }
private float ScreenScale => 1f / (.5f * (Screen.height / _spaceCamera.orthographicSize));
private float MaxOrthoSize => pow(OrthoStepScale, ceil(Mathf.Log(_map.WorldRadius, OrthoStepScale)));
private Bounds SpaceCameraWorldBounds
{
get
{
float height = 2f * _spaceCamera.orthographicSize;
float width = height * _spaceCamera.aspect;
return new Bounds(SpaceCameraTransform.position.XY(), new Vector2(width, height));
}
}
private Vector2 TargetedWorldPosition => _targetedPlanet?.Position ?? MouseWorldPosition;
private Planet SelectedPlanet
{
get => _selectedPlanet;
set
{
if ((_selectedPlanet is not null) && (_selectedPlanet == value))
return;
if (_selectedPlanet is not null)
_eventManager.GameplayEvents.PlanetDeselected?.Invoke();
_selectedPlanet = value;
if (_selectedPlanet is null)
return;
_eventManager.GameplayEvents.PlanetSelected?.Invoke(_selectedPlanet, _player.Owns(_selectedPlanet), _map[_selectedPlanet.Position].Environment);
Debug.Log($"Selected: {_selectedPlanet}");
}
}
public Gameplay(
GameplayConfig gameplayConfig,
EventManager eventManager,
Player player,
SpaceMap map,
DfInputActions.GameplayActions gameplayInput,
Camera spaceCamera,
OverlayController overlay,
MeshAssetsConfig transportShipConfig,
PlanetAssetsConfig[] planetAssetConfigs,
WorldClock worldClock,
GameInstanceInfo worldInstanceInfo)
{
_gameplayConfig = gameplayConfig;
_eventManager = eventManager;
_player = player;
_map = map;
_gameplayInput = gameplayInput;
_spaceCamera = spaceCamera;
_overlay = overlay;
_transportShipConfig = transportShipConfig;
_planetAssetConfigs = planetAssetConfigs;
_worldClock = worldClock;
_worldInstanceInfo = worldInstanceInfo;
// We don't use this inefficiently but Rider won't stop complaining. This fixes it.
SpaceCameraTransform = _spaceCamera.transform;
}
// Note: We're not handling re-entry. This state will enter and exit once only.
protected override void OnEnter()
{
Debug.Log($"{nameof(Gameplay)} {nameof(OnEnter)}");
// These RenderBatchers reduce draw calls by batching planets with the same material.
// This really means we're just batching planets of the same level.
_renderBatchers = new RenderBatcher[_planetAssetConfigs.Length];
for (int i = 0; i < _planetAssetConfigs.Length; ++i)
{
PlanetAssetsConfig cfg = _planetAssetConfigs[i];
var surfaceRenderParams = new RenderParams(cfg.SurfaceMaterial);
Mesh planetMesh = cfg.Mesh;
_renderBatchers[i] = new RenderBatcher(planetMesh, surfaceRenderParams);
}
// Instantiate and position the Explorer.
_explorer = new Explorer
{
Position = _player.HomePosition,
IsExploring = true
};
// Ensure current starting position is explored.
_homeSector = _map.Explore(_explorer.Position);
_eventManager.GeneralEvents.SectorChanged?.Invoke(_homeSector);
// It's ok if they no longer own this. They'll start here anyway.
_homePlanet = _homeSector.Planet;
_eventManager.GameplayEvents.PlanetControlChanged?.Invoke(_homePlanet, _player, Player.Alien);
// Translate camera to home world position.
PanSpaceCamera(_player.HomePosition);
FocusOnPlanet(_homePlanet);
_gameplayInput.Enable();
InitializeStates();
InitializeExplorer();
InitializePlanetSynchronization();
InitializeLeaderboard();
// Continuously show the current grid hovered by mouse
Engine.NextFrame.Loop(() =>
{
if (!_spaceCamera.pixelRect.Contains(Mouse.current.position.value))
return;
Sector sector = _map[MouseGridPosition];
_eventManager.GameplayEvents.GridHovered?.Invoke(sector);
}).AddTag("MouseOverSector");
Engine
.NextFrame.Sleep(_gameplayConfig.WorldClockResyncPeriod).AddTag("WorldClockResync")
.Next.Loop(_gameplayConfig.WorldClockResyncPeriod, float.MaxValue, _worldClock.Resync);
// Update And Render Space View ////////////////////////////////////
Engine.NextFrame.Loop(UpdatePlanets).AddTag(nameof(UpdatePlanets));
Engine.NextFrame.Loop(AlignView).AddTag(nameof(AlignView));
_eventManager.GameplayEvents.PlanetInfoClosed += () => SelectedPlanet = null;
_eventManager.GameplayEvents.PlanetIndexSelectPlanet += gridPos =>
{
SelectedPlanet = _map[gridPos].Planet;
if (SelectedPlanet is null)
return;
_selectionWorldPosition = gridPos;
FocusOnPlanet(SelectedPlanet);
};
_eventManager.GameplayEvents.EnergyTransferPercentUpdated += percent => _energyTransferScale = percent / 100.0;
// Occurs when we've received approval from the backend.
_eventManager.GameplayEvents.SendEnergyApproved += OnSendEnergyTransfer;
_eventManager.GameplayEvents.GameplayEntered?.Invoke();
}
protected override void OnExit()
{
// Clearing in this manner should be safe for this use case.
_eventManager.GameplayEvents.ExplorerStarting = null;
_eventManager.GameplayEvents.ExplorerStopping = null;
_eventManager.GameplayEvents.ExplorerStartRelocating = null;
_eventManager.GameplayEvents.ExplorerStopRelocating = null;
_eventManager.GameplayEvents.PlanetInfoClosed = null;
_eventManager.GameplayEvents.PlanetIndexSelectPlanet = null;
_eventManager.GameplayEvents.PlanetShown = null;
_eventManager.GameplayEvents.PlanetHidden = null;
_eventManager.GameplayEvents.PlanetSelected = null;
_eventManager.GameplayEvents.PlanetDeselected = null;
_eventManager.GameplayEvents.LeaderboardOpened = null;
_eventManager.GameplayEvents.LeaderboardClosed = null;
_gameplayInput.Move.Disable();
_eventManager.GameplayEvents.GameplayExited?.Invoke();
}
private void InitializeStates()
{
// State Actions
// The targeted planet is the one we're currently hovering over but may not have selected.
void TargetPlanet()
{
if (_targetedPlanet is not null)
_eventManager.GameplayEvents.PlanetHoverEnded?.Invoke();
_targetedPlanet = _hitTestResultPlanet;
if (_targetedPlanet is not null)
_eventManager.GameplayEvents.PlanetHoverStarted?.Invoke(_targetedPlanet, _player.Owns(_targetedPlanet));
}
void ShowHoveredGrid()
{
if (!(_spaceCamera.orthographicSize < _squareDrawZoomLimit) || !(Mouse.current.position.value.x > 0) || !(Mouse.current.position.value.x < Screen.width)
|| !(Mouse.current.position.value.y > 0) || !(Mouse.current.position.value.y < Screen.height)) return;
var targetWorldPosition = (Vector3)round(_spaceCamera.ScreenToWorldPoint(Mouse.current.position.value));
_overlay.DrawWorldSquare(new Vector3(targetWorldPosition.x, targetWorldPosition.y, 0), 1f, .1f, ColorPalette.Explorer);
}
void Zoom()
{
if (EventSystem.current.IsPointerOverGameObject())
return; //make zoom not working if mouse is on top of a ui component
float zoomDir = -sign(Mouse.current.scroll.value.y);
bool isZoomingOut = zoomDir > 0f;
if (!isZoomingOut && (MouseWorldPosition.sqrMagnitude > _map.WorldRadius * _map.WorldRadius))
return;
if (Mathf.Approximately(zoomDir, 0f))
return;
float scale = isZoomingOut ? OrthoStepScale : 1f / OrthoStepScale;
Vector3 cursorWorldPosition = _spaceCamera.ScreenToWorldPoint(Mouse.current.position.value);
Vector3 offset = (cursorWorldPosition - _spaceCamera.ViewportToWorldPoint(new Vector3(.5f, .5f, 0f)));
float desiredOrthoSize = _spaceCamera.orthographicSize * scale;
if (Mathf.Approximately(desiredOrthoSize, MinOrthoSize))
desiredOrthoSize = MinOrthoSize;
else if (Mathf.Approximately(desiredOrthoSize, MaxOrthoSize))
desiredOrthoSize = MaxOrthoSize;
if ((desiredOrthoSize <= MinOrthoSize) || (desiredOrthoSize >= MaxOrthoSize))
if (Engine.Exists(ZoomTag))
return;
desiredOrthoSize = clamp(desiredOrthoSize, MinOrthoSize, MaxOrthoSize);
if (Mathf.Approximately(desiredOrthoSize, _spaceCamera.orthographicSize))
return;
Vector3 cameraStartingPosition = SpaceCameraTransform.position;
Vector3 zoomTargetPosition = cameraStartingPosition + offset - (offset * scale);
float startingOrthoSize = _spaceCamera.orthographicSize;
Engine.NextFrame.Lerp(1.0 / 3.0, maxCycles: 1.0, bias: Easing.EaseOut5, f: t =>
{
SpaceCameraTransform.position = lerp(cameraStartingPosition, zoomTargetPosition, t);
_spaceCamera.orthographicSize = clamp(lerp(startingOrthoSize, desiredOrthoSize, t),
MinOrthoSize, MaxOrthoSize);
_eventManager.GameplayEvents.CameraZoomChanged?.Invoke(_spaceCamera.orthographicSize);
}).AddTag(ZoomTag)
.Next
.Add(() =>
{
if (_explorer.IsExploring)
Engine.Resume(ExplorerTag);
});
// Zooming is smooth when the explorer isn't running, so we're pausing the explorer while zooming.
// An improvement to the zooming method may prevent the excessive jitter as well, so perhaps we should try that instead of pausing the explorer.
Engine.Pause(ExplorerTag);
}
// Move handles camera positioning based on mouse and keyboard input. This includes zoom.
void Move()
{
if (EventSystem.current.IsPointerOverGameObject())
return;
if ((_targetedPlanet is not null || SelectedPlanet is not null) && Keyboard.current.fKey.wasPressedThisFrame)
{
Planet planet = _targetedPlanet ?? SelectedPlanet;
FocusOnPlanet(planet);
return;
}
if (Keyboard.current.hKey.isPressed)
{
FocusOnPlanet(_homePlanet);
return;
}
if (Keyboard.current.xKey.wasPressedThisFrame)
{
Focus((Vector2)_explorer.Position, 0.4f);
return;
}
//each frame camera can only be controlled by mouse OR keyboard, so we check if middle mouse is pressed first here
if ((Mouse.current.middleButton.isPressed && !Mouse.current.middleButton.wasPressedThisFrame) || (Mouse.current.rightButton.isPressed && !Mouse.current.rightButton.wasPressedThisFrame))
{
// middle mouse drag movement
Vector2 dragDelta = _spaceCamera.ScreenToWorldPoint(Mouse.current.position.ReadValueFromPreviousFrame())
- _spaceCamera.ScreenToWorldPoint(Mouse.current.position.value);
if (dragDelta.sqrMagnitude > 0f)
PanSpaceCamera(dragDelta);
}
else
{
//keyboard movement
Vector3 move = _gameplayInput.Move.ReadValue<Vector2>();
// If the mouse is moving, the user may be trying to move the mouse cursor out of the game window.
// So to prevent that annoyance, only scroll the viewport when the mouse cursor is still.
// Editor only. We're fullscreen in the browser.
if (Screen.fullScreen && (Mathf.Approximately(0f, Mouse.current.delta.value.sqrMagnitude) || !Application.isEditor))
{
// Test cursor against edge of screen.
Vector2 mpn = _spaceCamera.ScreenToViewportPoint(Mouse.current.position.value);
Vector3 dir = Vector3.zero;
float margin = .02f;
var aabb = new Rect(0f, 0f, 1f, 1f);
if (aabb.Contains(mpn))
{
if (mpn.x < margin || mpn.x > (1f - margin))
dir.x = saturate(round(mpn.x)) * 2f - 1f;
if (mpn.y < margin || mpn.y > (1f - margin))
dir.y = saturate(round(mpn.y)) * 2f - 1f;
move += dir;
}
}
move *= _spaceCamera.orthographicSize * Time.deltaTime * (2f - pow(NormalizedOrthoSize, 2f)) * 2f;
PanSpaceCamera(move);
}
}
// Assumes that we're selecting planets of course. If that changes, please update this.
void Select()
{
if (EventSystem.current.IsPointerOverGameObject() || !_gameplayInput.Select.IsPressed())
return;
SelectedPlanet = _hitTestResultPlanet;
_selectionWorldPosition = _hitTestPosition;
}
void Relocate()
{
//pressing anything during relocating will result in exiting the relocating state, including any ui component
if (!_gameplayInput.Select.WasPressedThisFrame())
return;
_isPlacingExplorer = false;
if (EventSystem.current.IsPointerOverGameObject())
return;
_selectionWorldPosition = round(MouseWorldPosition);
Vector2Int desiredExplorerPosition = Vector2Int.FloorToInt(_selectionWorldPosition);
if (!_map.IsValidPosition(desiredExplorerPosition))
{
_eventManager.GameplayEvents.ExplorerInvalidRelocationAttempted?.Invoke();
return;
}
_explorer.Reset();
_explorer.Position = desiredExplorerPosition;
_ = _map.Explore(_explorer.Position);
}
void DragForEnergyTransfer()
{
var line = new float4(_selectionWorldPosition, TargetedWorldPosition);
var energyTransferPointer = new EnergyLine { Line = line, Color = ColorPalette.LocalEnergyLine };
//checking energy sending distance should still uses their grid position, or otherwise the estimation will change with small mouse movement
Vector2Int srcCellPosition = Vector2Int.RoundToInt(_selectionWorldPosition);
Vector2Int dstCellPosition = Vector2Int.RoundToInt(TargetedWorldPosition);
Planet source = SelectedPlanet;
if (!_player.Owns(source))
return;
// This is validated at the state level, but checking anyway.
if (Engine.Exists(source.PendingEnergyTransferTag))
{
Debug.LogWarning($"Pending transfers should be filtered out at the state transition level.");
return;
}
double d = (srcCellPosition - dstCellPosition).magnitude; // <-- Yeah, that's a float. It's fine.
double energySent = source.EnergyLevel * _energyTransferScale; //the _energyTransferScale have been validated on the control ui
double travelCostPerUnit = source.EnergyCapacity * .95 / source.FullRange;
double travelCost = d * travelCostPerUnit + source.EnergyCapacity * .05;
int energyToBeReceived = (int)(energySent - travelCost);
double travelTimeInSeconds = d / source.Speed;
// This should probably use a delegate or take struct. 3 args is a bit clunky for an Action.
_eventManager.GameplayEvents.EnergyTransferPreview?.Invoke(
UIUtility.GetTransferInfoArmRotation(TargetedWorldPosition - _selectionWorldPosition),
TimeSpan.FromSeconds(travelTimeInSeconds),
energyToBeReceived);
bool mustExitEarly = false;
//give net transfer preview when hovering on a planet
if (_map[dstCellPosition].TryGetPlanet(out Planet destination))
{
// Return if planet is null or the source and destination match.
if (destination is null || destination == source)
{
mustExitEarly = true;
}
else
{
int netReceivedEnergy = _player.Owns(destination)
? energyToBeReceived
: Mathf.RoundToInt(energyToBeReceived / (float)destination.Defense * 100f);
_eventManager.GameplayEvents.EnergyTransferTargetHoverStart?.Invoke(destination.Id, _player.Owns(destination), netReceivedEnergy);
}
}
else
{
_eventManager.GameplayEvents.EnergyTransferTargetHoverStop?.Invoke();
mustExitEarly = true;
}
if ((_selectionWorldPosition - TargetedWorldPosition).magnitude > (float)source.GetCurrentRange(_energyTransferScale) || source.ExportShipRemaining == 0)
{
energyTransferPointer.Color = Color.red;
mustExitEarly = true;
}
if (Mouse.current.leftButton.isPressed && !Mouse.current.leftButton.wasReleasedThisFrame)
mustExitEarly = true;
if (mustExitEarly)
{
DrawCandidateTransfer(energyTransferPointer, 1f);
return;
}
_eventManager.GameplayEvents.EnergyTransferTargetHoverStop?.Invoke(); //mouse released, hover stop
line = new float4((Vector2)srcCellPosition, (Vector2)dstCellPosition); //use the rounded cell position so the line won't be weirdly hanging to a space where mouse is released
//create placeholder empty line that will automatically timeout.
var placeholderLine = new EnergyLine { Color = energyTransferPointer.Color, Line = line};
const double timeout = 15.0;
Engine
.NextFrame.Lerp(period: timeout, maxCycles: 1.0, _ => DrawCandidateTransfer(placeholderLine, .4f))
.AddTag(source.PendingEnergyTransferTag);
Debug.Log($"Expected prior to Receipt: energySent: {energySent}");
_eventManager.GameplayEvents.SendEnergyRequested?.Invoke(
source.Position,
destination.Position,
new SendEnergyMsg
{
energy = (int)energySent, // changed from: energyToBeReceived,
locationHashFrom = source.LocationHash, // _mapper.MimcHashValueAt(source.Position),
locationHashTo = destination.LocationHash, // _mapper.MimcHashValueAt(destination.Position),
maxDistance = (int)ceil((source.Position - destination.Position).magnitude),
perlinTo = destination.PerlinValue, // _mapper.PerlinValueAt(destination.Position),
radiusTo = _map.WorldRadius
});
}
void DrawCandidateTransfer(EnergyLine energyLine, float alpha)
{
//drawing the candidate line
float2 wa = energyLine.Line.xy;
float2 wb = energyLine.Line.zw;
_overlay.DrawWorldLine(wa, wb,
energyLine.Color.WithAlpha(alpha),
_gameplayConfig.TransferPreviewLineDashScale,
_gameplayConfig.TransferPreviewLineGapToDashRatio);
}
// Request an energy boost for debugging purposes only. Spamming this may not result in a significant energy boost, but feel free to try!
void OnEnergyBoostRequested(InputAction.CallbackContext context)
{
if (SelectedPlanet is null)
{
Debug.Log("Please select a planet before attempting to boost energy.");
return;
}
_eventManager.GameplayEvents.DebugEnergyBoosted?.Invoke(new LocationHashMsg { locationHash = SelectedPlanet.LocationHash });
}
InitializeDebugView(out Action<string> displayStateInfo, out Action monitorDebugTextToggles);
// Gameplay States /////////////////////////////////////////////////
// These are simple classic FSM style states, but the state machine supports stacking too.
// This free book has a great overview of state management: https://gameprogrammingpatterns.com/state.html
var navigation = new CyclopsState
{
Entered = () => _gameplayInput.EnergyBoost.performed += OnEnergyBoostRequested,
Updating = () =>
{
Zoom();
Move();
ShowHoveredGrid();
TargetPlanet();
Select();
monitorDebugTextToggles();
displayStateInfo("navigation");
},
Exited = () => _gameplayInput.EnergyBoost.performed -= OnEnergyBoostRequested
};
var energyTransfer = new CyclopsState
{
Entered = () => _eventManager.GameplayEvents.EnergyTransferStateEntered?.Invoke(),
Updating = () =>
{
Zoom();
Move();
TargetPlanet();
DragForEnergyTransfer();
monitorDebugTextToggles();
displayStateInfo("energyTransfer");
},
Exited = () =>
{
_eventManager.GameplayEvents.EnergyTransferStateExited?.Invoke();
DragForEnergyTransfer();
}
};
var explorerRelocation = new CyclopsState
{
Entered = () => _eventManager.GameplayEvents.RelocatingStateChanged?.Invoke(true),
Updating = () =>
{
Zoom();
Move();
ShowHoveredGrid();
Relocate();
monitorDebugTextToggles();
displayStateInfo("explorerRelocation");
},
Exited = () => _eventManager.GameplayEvents.RelocatingStateChanged?.Invoke(false)
};
// Transitions /////////////////////////////////////////////////////
var toEnergyTransfer = new CyclopsStateTransition
{
Target = energyTransfer,
Condition = () =>
{
bool result = _gameplayInput.Select.IsPressed()
&& (SelectedPlanet is not null)
&& (SelectedPlanet == _targetedPlanet)
&& _player.Owns(SelectedPlanet)
&& (!Engine.Exists(SelectedPlanet.PendingEnergyTransferTag));
return result;
}
};
navigation.AddTransition(toEnergyTransfer);
navigation.AddTransition(explorerRelocation, () => _isPlacingExplorer);
explorerRelocation.AddTransition(navigation, () => !_isPlacingExplorer);
energyTransfer.AddTransition(navigation, () =>
{
if (!_gameplayInput.Select.IsPressed())
return true;
if (SelectedPlanet is null)
return true;
return Engine.Exists(SelectedPlanet.PendingEnergyTransferTag);
});
// Start The State Machine /////////////////////////////////////////
// Fire it up.
_inputStateMachine = new CyclopsStateMachine();
_inputStateMachine.PushState(navigation);
// Engine drives the machine.
Engine.NextFrame.Loop(_inputStateMachine.Update).AddTag("InputStateMachine.Update");
}
private void InitializeExplorer()
{
// Explorer Loop - Tagged below with ExplorerTag for pause/resume/etc functionality.
Engine
.NextFrame
.Add(new ExplorerRoutine(_explorer, _map))
.AddTag(ExplorerTag);
Engine.NextFrame.Loop(() =>
{
if (_spaceCamera.orthographicSize < _squareDrawZoomLimit)
_overlay.DrawWorldSquare((Vector2)(_explorer.Position), 1f, .1f, ColorPalette.Explorer);
}).AddTag("DrawWorldSquare");
_eventManager.GameplayEvents.ExplorerStartRelocating += () => _isPlacingExplorer = true;
_eventManager.GameplayEvents.ExplorerStopRelocating += () => _isPlacingExplorer = false;
_eventManager.GameplayEvents.ExplorerStarting += () =>
{
Engine.Resume(ExplorerTag);
_explorer.IsExploring = true;
_eventManager.GameplayEvents.ExplorerMoveStateChanged?.Invoke(true);
};
_eventManager.GameplayEvents.ExplorerStopping += () =>
{
Engine.Pause(ExplorerTag);
_explorer.IsExploring = false;
_eventManager.GameplayEvents.ExplorerMoveStateChanged?.Invoke(false);
};
}
private void InitializePlanetSynchronization()
{
var planetSet = new HashSet<Planet>();
var planetQueue = new Queue<Planet>();
var planetBatch = new List<Planet>();
// Note: _synchronizedPlanets is cleared and populated with the space view.
// This will wait an extra frame to allow _synchronizedPlanets to catch up for the initial call.
Engine
.NextFrame.Nop()
.AddTag("SynchronizePlanets")
.Next.Loop(period: _gameplayConfig.PlanetUpdatePeriod, maxCycles: float.MaxValue, () =>
{
if (SelectedPlanet is not null && planetSet.Add(SelectedPlanet))
planetQueue.Enqueue(SelectedPlanet);
foreach (Planet planet in _planetsOnScreen)
{
if (planet.IsVisible && planetSet.Add(planet))
planetQueue.Enqueue(planet);
}
_player.ForEachPlanet(planet =>
{
if (planetSet.Add(planet))
planetQueue.Enqueue(planet);
});
planetBatch.Clear();
for (int i = 0; (i < _gameplayConfig.PlanetUpdateMaxBatchSize) && (planetQueue.Count > 0); ++i)
{
Planet planet = planetQueue.Dequeue();
planetSet.Remove(planet);
planetBatch.Add(planet);
}
if (planetBatch.Count == 0)
return;
//Debug.Log($"PlanetsUpdateRequested - Batch Size: {planetBatch.Count}");
_eventManager.GameplayEvents.PlanetsUpdateRequested?.Invoke(planetBatch);
});
bool isFirstSync = true; //flag to prevent notification from getting triggered from all the planets "reconquering" when player plays an existing progress
_eventManager.GameplayEvents.PlanetUpdateReceived += planetsData =>
{
foreach (PlanetData data in planetsData)
{
if (string.IsNullOrWhiteSpace(data.LocationHash))
{
Debug.LogWarning($"{data.LocationHash} is invalid.");
continue;
}
if (!_map.TryHashToPlanet(data.LocationHash, out Planet planet))
{
Debug.LogWarning($"Sector unknown. LocationHash: {data.LocationHash}");
continue;
}
if (planet is null)
{
Debug.LogError($"A planet should never be null in this situation. LocationHash: {data.LocationHash}");
continue;
}
//change ownership when the owner of a planet in local data is different than the one in payload
if (!string.IsNullOrWhiteSpace(data.OwnerPersonaTag) && planet.Owner.PersonaTag != data.OwnerPersonaTag)
{
Player prevOwner = planet.Owner;
if (!planet.Owner.IsAlien) //disclaim from the old owner
planet.Owner.Disclaim(planet);
if (data.OwnerPersonaTag == _player.PersonaTag) //ownership changed to local player
{
_player.Claim(planet);
}
else //ownership changes to other player
{
if (!_playersByPersonaTag.TryGetValue(data.OwnerPersonaTag, out Player otherPlayer))
{
otherPlayer = new Player { PersonaTag = data.OwnerPersonaTag };
_ = _playerColorManager.TryAssignColor(otherPlayer);
_playersByPersonaTag[data.OwnerPersonaTag] = otherPlayer;
}
otherPlayer.Claim(planet);
}
//when a planet ownership is changed, export ship is reset, and recheck friendly/hostile incoming transfer
planet.ExportShipRemaining = planet.MaxExportShipCount;
_eventManager.GameplayEvents.PlanetExportUpdated?.Invoke(planet);
_eventManager.GameplayEvents.PlanetIncomingTransferUpdated?.Invoke(planet);
_eventManager.GameplayEvents.PlanetControlChanged?.Invoke(planet, planet.Owner, prevOwner);
}
if (planet.TrySetEnergyLevel(data.EnergyLevel, data.WorldTick, _worldClock.TickToUtc(data.WorldTick)))
_eventManager.GameplayEvents.PlanetUpdated?.Invoke(planet);
// Note: Renamed because the name was hiding another variable.
foreach (EnergyTransfer incomingTransfer in data.energyTransfers)
{
if (_clientEnergyTransferIds.Contains(incomingTransfer.TransferId))
continue;
ulong id = incomingTransfer.TransferId;
//transfer with locally unexplored source is okay, and will be drawn as a shrinking ring
_map.TryHashToPlanet(incomingTransfer.SourceHash, out Planet source);
//energy transfer with undiscovered destination do not need to be drawn at all
if (!_map.TryHashToPlanet(incomingTransfer.DestinationHash, out Planet destination))
{
Debug.Log($"Will not display transfer {id} because the destination sector is locally unexplored.");
continue;
}
Vector2Int sourceGridPosition;
float travelDuration;
if (source is not null)
{
sourceGridPosition = source.Position;
travelDuration = incomingTransfer.TravelTimeInSeconds;
}
else
{
//fake source position for transfer with null source, 8 is the set size for the shrinking ring
sourceGridPosition = new Vector2Int(destination.Position.x + 8, destination.Position.y);
travelDuration = incomingTransfer.TravelTimeInSeconds;
}
int energyOnEmbark = Mathf.RoundToInt(incomingTransfer.EnergyOnEmbark);
float progress = incomingTransfer.Progress;
Player shipOwner;
if (incomingTransfer.OwnerPersonaTag == _player.PersonaTag)
{
shipOwner = _player;
}
else if (!_playersByPersonaTag.TryGetValue(incomingTransfer.OwnerPersonaTag, out shipOwner))
{
shipOwner = new Player { PersonaTag = incomingTransfer.OwnerPersonaTag };
_ = _playerColorManager.TryAssignColor(shipOwner);
_playersByPersonaTag[data.OwnerPersonaTag] = shipOwner;
}
var et = new ClientEnergyTransfer
{
Id = incomingTransfer.TransferId,
Source = source,
Destination = destination,
TravelDuration = travelDuration,
EnergyOnEmbark = energyOnEmbark,
Progress = progress,
ShipOwner = shipOwner
};
// Please note: We could be sending a null source planet and that's fine. It's in a sector that hasn't been discovered by the local player.
StartEnergyTransfer(et, transferStartScreenPosition: _spaceCamera.WorldToScreenPoint((Vector2)sourceGridPosition));
}
}
if (isFirstSync)
{
isFirstSync = false;
_eventManager.GameplayEvents.FirstUpdateDone?.Invoke();
}
};
}
private void InitializeLeaderboard()
{
// Set this on the next frame so that everything is setup properly.
Engine.NextFrame
.Add(() => _eventManager.GameplayEvents.InstanceNameUpdated?.Invoke(_worldInstanceInfo.Name))
.Next.Log($"Instance name is: '{_worldInstanceInfo.Name}'");
// Player leaderboard stat periodic update /////////////////////////
Engine
.NextFrame.Nop().AddTag("PlayerLeaderStatUpdate")
.Next.Loop(period: 5f, maxCycles: float.MaxValue, () =>
{
if (string.IsNullOrEmpty(_player.PersonaTag))
{
Debug.LogError("_player.PersonaTag is null or empty.");
return;
}
_eventManager.GameplayEvents.PlayerLeaderStatUpdateRequested?.Invoke(_player.PersonaTag);
});
// Leaderboard refresh (on update and every 5s) ////////////////////
Engine
.NextFrame.Nop().AddTag(LeaderboardTag)
.Next.Loop(period: 5f, maxCycles: float.MaxValue, () =>
{
_eventManager.GameplayEvents.LeaderboardUpdateRequested?.Invoke(_player.PersonaTag);
});
Engine.Pause(LeaderboardTag);
_eventManager.GameplayEvents.LeaderboardOpened += () => Engine.Resume(LeaderboardTag);
_eventManager.GameplayEvents.LeaderboardClosed += () => Engine.Pause(LeaderboardTag);
}
//zoomScale use planet scale
private void Focus(Vector3 position, float zoomScale)
{
position.z = SpaceCameraTransform.position.z;
SpaceCameraTransform.position = position;
_spaceCamera.orthographicSize = 5 + (zoomScale * 10);
_eventManager.GameplayEvents.CameraZoomChanged?.Invoke(_spaceCamera.orthographicSize);
}
private void FocusOnPlanet(Planet focusedPlanet)
{
Vector3 focusedPosition = (Vector2)focusedPlanet.Position;
focusedPosition.z = SpaceCameraTransform.position.z;
Focus(focusedPosition, focusedPlanet.Scale);
}
private void PanSpaceCamera(Vector2 offset) => SpaceCameraTransform.Translate(offset);
private void AlignView()
{
Vector3 originalPosition = SpaceCameraTransform.position;
Vector2 p = originalPosition.XY();
if (p.sqrMagnitude <= _map.WorldRadius * _map.WorldRadius)
return;
p = p.normalized * _map.WorldRadius;
var destination = new Vector3(p.x, p.y, originalPosition.z);
SpaceCameraTransform.position = Vector3.Lerp(originalPosition, destination, .5f * saturate(Time.deltaTime * 10f));
}
private void UpdatePlanets()
{
_planetsOnScreen.Clear();
// These 2 constants could probably be a bit more accessible.
const int maxVisiblePlanetsTarget = 256;
const int maxVisibleLod = 5;
float zoom = _spaceCamera.orthographicSize;
int minPlanetLevel = max(0, Mathf.CeilToInt(-9f + Mathf.Log(zoom, 1.618f)));
// Display world radius.
_overlay.DrawWorldRing(Vector3.zero, _map.WorldRadius, Color.red);
Bounds cameraWorldBounds = SpaceCameraWorldBounds;
float screenScale = ScreenScale;
_hitTestResultPlanet = null;
_map.Quadtree.WalkBfs(node =>
{
if (!node.Sector.HasPlanet)
return false;
Planet planet = node.Sector.Planet;
bool keep = _player.IsHomePlanet(planet) || (planet == SelectedPlanet);
// Since this isn't an LodScale value, 0 is the highest level.
planet.Lod = 0;
if (!keep)
{
float distanceFromVisibilitySquared = cameraWorldBounds.SqrDistance(new Vector2(planet.Position.x, planet.Position.y));
float fullRange = max(planet.Radius, planet.FullRange);
// If there's no chance of showing anything of this planet, then no need to continue processing this planet, but we do have to consider those below.
// Note: This could be a very large planet located on the far side of a quadrant that intersects camera bounds.
// Child quadrants might still contain viable planets.
if (distanceFromVisibilitySquared >= fullRange * fullRange)