-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathGame.cs
More file actions
1075 lines (930 loc) · 36.5 KB
/
Game.cs
File metadata and controls
1075 lines (930 loc) · 36.5 KB
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.Diagnostics;
using C7Engine;
using C7GameData;
using Serilog;
using C7Engine.Pathing;
using System.Collections.Generic;
using System.Linq;
using C7Engine.AI;
public partial class Game : Node2D {
[Signal] public delegate void TurnEndedEventHandler();
[Signal] public delegate void ShowSpecificAdvisorEventHandler();
[Signal] public delegate void NewAutoselectedUnitEventHandler();
[Signal] public delegate void NoMoreAutoselectableUnitsEventHandler();
[Signal] public delegate void ShowCityScreenEventHandler();
private ILogger log = LogManager.ForContext<Game>();
enum GameState {
PreGame,
PlayerTurn,
ComputerTurn
}
public Player controller; // Player that's controlling the UI.
private MapView mapView;
public AnimationManager civ3AnimData;
public AnimationTracker animTracker;
GameState CurrentState = GameState.PreGame;
// CurrentlySelectedUnit is a reference directly into the game state so be careful of race conditions. TODO: Consider storing a GUID instead.
public MapUnit CurrentlySelectedUnit = MapUnit.NONE; //The selected unit. May be changed by clicking on a unit or the next unit being auto-selected after orders are given for the current one.
private bool HasCurrentlySelectedUnit() => CurrentlySelectedUnit != MapUnit.NONE;
// When the game is in "goto" mode, the current destination and the cost of getting
// there, in turns.
//
// Otherwise null.
public class GotoInfo {
public Tile destinationTile = null;
public int moveCost = -1;
public TilePath path = null;
public HashSet<System.Numerics.Vector2> pathCoords;
public bool attackingMove = false;
public Player requiresWarDeclarationOnPlayer = null;
};
public GotoInfo gotoInfo = null;
// Normally if the currently selected unit (CSU) becomes fortified, we advance to the next autoselected unit. If this flag is set, we won't do
// that. This is useful so that the unit autoselector can be prevented from interfering with the player selecting fortified units.
public bool KeepCSUWhenFortified = false;
// When in observer mode, the number of turns to play before prompting the
// user to advance the turn manually. This allows for more rapid debugging
// without pressing the spacebar repeatedly.
public int turnsLeftToFastForward = 0;
[Export]
Control Toolbar;
private bool IsMovingCamera;
private Vector2 OldPosition;
Stopwatch loadTimer = new Stopwatch();
GlobalSingleton Global;
[Export]
private PopupOverlay popupOverlay;
[Export]
private CityScreen cityScreen;
[Export]
private Advisors advisor;
[Export]
private Diplomacy diplomacy;
[Export]
private VSlider slider;
[Export]
private AnimationPlayer animationPlayer;
[Export]
private DoubleClickHandler doubleClickHandler;
[Export]
private PalaceScreen palaceScreen;
bool errorOnLoad = false;
public override void _EnterTree() {
loadTimer.Start();
}
// Called when the node enters the scene tree for the first time.
// The catch should always catch any error, as it's the general catch
// that gives an error if we fail to load for some reason.
public override void _Ready() {
Global = GetNode<GlobalSingleton>("/root/GlobalSingleton");
try {
// Ensure we clear out our image caches, as scenarios and games will
// use the same filenames but have different content for them.
Util.ClearCaches();
var animSoundPlayer = new AudioStreamPlayer();
AddChild(animSoundPlayer);
civ3AnimData = new AnimationManager(animSoundPlayer);
animTracker = new AnimationTracker(civ3AnimData);
controller = CreateGame.createGame(Global.LoadGamePath, GlobalSingleton.DefaultBicPath, (scenarioSearchPath) => {
// WHen the game loading logic tries to load the PediaIcons file, set the
// scenario search path and then use our Civ3MediaPath searching logic to
// find the correct version of the file.
//
// This weird bit of indirection is necessary because the C7GameData project
// can't depend on the C7 project without a circular dependency, and the
// search logic has a Godot dependency, so it doesn't make sense to live
// in the C7GameData project.
//
// This also helps ensure the weird stateful behavior of the Util class works,
// since the search path/mod path is a static global variable - we want to
// be sure it is always set properly, so doing it during game creation
// is reasonable.
Util.setModPath(scenarioSearchPath);
log.Debug("RelativeModPath ", scenarioSearchPath);
return Util.Civ3MediaPath("Text/PediaIcons.txt");
}); // Spawns engine thread
Global.ResetLoadGamePath();
InitializeMapView();
//TODO: What was this supposed to do? It throws errors and occasinally causes crashes now, because _OnViewportSizeChanged doesn't exist
// GetTree().Root.Connect("size_changed",new Callable(this,"_OnViewportSizeChanged"));
// Hide slideout bar on startup
_on_SlideToggle_toggled(false);
log.Information("Now in game!");
loadTimer.Stop();
TimeSpan stopwatchElapsed = loadTimer.Elapsed;
log.Information("Game scene load time: " + Convert.ToInt32(stopwatchElapsed.TotalMilliseconds) + " ms");
} catch (Exception ex) {
errorOnLoad = true;
string message = ex.Message;
string[] stack = ex.StackTrace.Split("\r\n"); //for some reason it is returned with \r\n in the string as one line. let's make it readable!
foreach (string line in stack) {
message = message + "\r\n" + line;
}
popupOverlay.ShowPopup(new ErrorMessage(message), PopupOverlay.PopupCategory.Advisor);
log.Error(ex, "Unexpected error in Game.cs _Ready");
}
}
private void InitializeMapView() {
EngineStorage.ReadGameData((GameData gameData) => {
GameMap map = gameData.map;
Vector2? cameraLocation = null;
if (mapView != null) {
cameraLocation = mapView.cameraLocation;
RemoveChild(mapView);
}
mapView = new MapView(this, map.numTilesWide, map.numTilesTall, map.wrapHorizontally, map.wrapVertically);
AddChild(mapView);
mapView.cameraZoom = (float)1.0;
mapView.gridLayer.visible = false;
if (!cameraLocation.HasValue) {
// Set initial camera location. If the UI controller has any cities, focus on their capital. Otherwise, focus on their
// starting settler.
if (controller.cities.Count > 0) {
City capital = controller.cities.Find(c => c.IsCapital());
if (capital != null)
mapView.centerCameraOnTile(capital.location);
} else {
MapUnit startingSettler =
controller.units.Find(u => u.unitType.actions.Contains(UnitAction.BuildCity));
if (startingSettler != null)
mapView.centerCameraOnTile(startingSettler.location);
}
} else {
mapView.cameraLocation = cameraLocation.Value;
}
// Allow the city screen to control whether tile assignments
// are visible and map UI locations back to map locations.
cityScreen.tileAssignmentLayer = mapView.tileAssignmentLayer;
cityScreen.mapView = mapView;
cityScreen.citizenTypes = gameData.citizenTypes;
// Allow the domestic advisor to trigger popups.
advisor.domesticAdvisor.SetPopupOverlay(popupOverlay);
});
}
public void processEngineMessages() {
EngineStorage.ReadGameData((GameData gameData) => { processEngineMessagesLocked(gameData); });
}
// Must only be called while holding the game data mutex
public void processEngineMessagesLocked(GameData gameData) {
MessageToUI msg;
while (EngineStorage.messagesToUI.TryDequeue(out msg)) {
switch (msg) {
case MsgStartUnitAnimation mSUA:
MapUnit unit = gameData.GetUnit(mSUA.unitID);
if (unit != null && (controller.tileKnowledge.isActiveTile(unit.location) || controller.tileKnowledge.isActiveTile(unit.previousLocation))) {
// TODO: This needs to be extended so that the player is shown when AIs found cities, when they move units
// (optionally, depending on preferences) and generalized so that modders can specify whether custom
// animations should be shown to the player.
if (mSUA.action == MapUnit.AnimatedAction.ATTACK1)
ensureLocationIsInView(unit.location);
animTracker.startAnimation(unit, mSUA.action, mSUA.completionEvent, mSUA.ending);
} else {
if (mSUA.completionEvent != null) {
mSUA.completionEvent();
}
}
break;
case MsgStartEffectAnimation mSEA:
int X, Y;
gameData.map.tileIndexToCoords(mSEA.tileIndex, out X, out Y);
Tile tile = gameData.map.tileAt(X, Y);
if (tile != Tile.NONE && controller.tileKnowledge.isActiveTile(tile))
animTracker.startAnimation(tile, mSEA.effect, mSEA.completionEvent, mSEA.ending);
else {
if (mSEA.completionEvent != null)
mSEA.completionEvent();
}
break;
case MsgStartTurn mST:
OnPlayerStartTurn();
break;
case MsgShowCityScreen mSCS:
ShowCityScreenForCity(gameData, mSCS.city);
break;
case MsgCityCreated mCC:
ShowCityScreenForCity(gameData, mCC.city);
break;
case MsgCityDestroyed mCD:
mapView.cityLayer.UpdateAfterCityDestruction(mCD.city);
break;
case MsgCivilizationDestroyed mCivD:
popupOverlay.ShowPopup(new CivilizationDestroyed(mCivD.civilization), PopupOverlay.PopupCategory.Advisor);
// Break out of fast forward mode after interesting events.
turnsLeftToFastForward = 0;
break;
case MsgShowMilitaryAdvisorPopup mSMAP:
if (!popupOverlay.Visible) {
popupOverlay.ShowPopup(
new InformationalPopup(mSMAP.message, AdvisorHead.Advisor.Military, mSMAP.happy ? AdvisorHead.Mood.Happy : AdvisorHead.Mood.Angry),
PopupOverlay.PopupCategory.Advisor);
}
break;
case MsgUpdateUiAfterMove mUUAM:
// The unit finished moving and still has moves left, so we need to
// mark it as the selected unit again.
//
// Among other things, this will refresh the UI and ensure that the
// unit action buttons are correct.
if (CurrentlySelectedUnit != MapUnit.NONE) {
setSelectedUnit(CurrentlySelectedUnit);
}
break;
case MsgShowScienceAdvisor mSSA:
// F6 is the science advisor.
// TODO: Move the F* key strings to a set of constants/enum.
EmitSignal(SignalName.ShowSpecificAdvisor, "F6");
break;
case MsgUpdateUiAfterDomesticChange mUUASC:
// F1 is the domestic advisor.
// TODO: Move the F* key strings to a set of constants/enum.
// Ensure the citizen moods are correct before displaying
// them.
foreach (City c in controller.cities) {
c.RecalculateCitizenMoods(gameData);
}
EmitSignal(SignalName.ShowSpecificAdvisor, "F1");
break;
case MsgDisplayHurryProductionPopup mDHPP:
if (mDHPP.details.errorMessage != null) {
popupOverlay.ShowPopup(
new InformationalPopup(mDHPP.details.errorMessage),
PopupOverlay.PopupCategory.Advisor);
} else {
popupOverlay.ShowPopup(
new ConfirmationPopup(message: mDHPP.details.costMessage,
yesText: "Yes I'm sure!",
noText: "Maybe you're right. Nevermind.",
yesAction: () => {
new MsgDoHurryProduction(mDHPP.city).send();
}),
PopupOverlay.PopupCategory.Advisor);
}
break;
case MsgWarDeclaration mWD:
popupOverlay.ShowPopup(
new InformationalPopup($"The {mWD.aggressor.civilization.noun} declared war on the {mWD.opponent.civilization.noun}"),
PopupOverlay.PopupCategory.Advisor);
// Break out of the fast forward mode when something
// interesting happens.
turnsLeftToFastForward = 0;
break;
case MsgShowTemporaryPopup mSTP:
TemporaryPopup popup = new(mSTP.message, 1);
popup.SetPosition(mapView.screenLocationOfTile(mSTP.location, true) + new Vector2(0, -64));
AddChild(popup);
popup.ShowPopup();
break;
}
}
}
// Instead of Game calling animTracker.update periodically (this used to happen in _Process), this method gets called as necessary to bring
// the animations up to date. Right now it's called from UnitLayer right before it draws the units on the map. This method also processes all
// waiting messages b/c some of them might pertain to animations. TODO: Consider processing only the animation messages here.
// Must only be called while holding the game data mutex
public void updateAnimations(GameData gameData) {
processEngineMessagesLocked(gameData);
animTracker.update();
}
public override void _Process(double delta) {
ProcessActions();
processEngineMessages();
if (!errorOnLoad) {
if (CurrentState == GameState.PlayerTurn) {
// If the selected unit is unfortified, prepare to autoselect the next one if it becomes fortified
if ((CurrentlySelectedUnit != MapUnit.NONE) && (!CurrentlySelectedUnit.isFortified))
KeepCSUWhenFortified = false;
// Advance off the currently selected unit to the next one if it's out of moves or HP and not playing an
// animation we want to watch, or if it's fortified and we aren't set to keep fortified units selected.
if ((CurrentlySelectedUnit != MapUnit.NONE) &&
(((!CurrentlySelectedUnit.movementPoints.canMove || CurrentlySelectedUnit.hitPointsRemaining <= 0) &&
!animTracker.getUnitAppearance(CurrentlySelectedUnit).DeservesPlayerAttention()) ||
(CurrentlySelectedUnit.isFortified && !KeepCSUWhenFortified) ||
CurrentlySelectedUnit.isAutomated))
EngineStorage.ReadGameData((GameData gameData) => {
GetNextAutoselectedUnit(gameData);
});
}
}
}
// If "location" is not already near the center of the screen, moves the camera to bring it into view.
public void ensureLocationIsInView(Tile location) {
if (controller.tileKnowledge.isTileKnown(location) && location != Tile.NONE) {
Vector2 relativeScreenLocation = mapView.screenLocationOfTile(location, true) / mapView.getVisibleAreaSize();
if (relativeScreenLocation.DistanceTo(new Vector2((float)0.5, (float)0.5)) > 0.30)
mapView.centerCameraOnTile(location);
}
}
public void SetAnimationsEnabled(bool enabled) {
new MsgSetAnimationsEnabled(enabled).send();
animTracker.endAllImmediately = !enabled;
}
/**
* Currently (11/14/2021), all unit selection goes through here.
* Both code paths are in Game.cs for now, so it's local, but we may
* want to change it event driven.
*
* Returns whether the selected unit has remaining moves.
**/
public bool setSelectedUnit(MapUnit unit) {
unit.availableActions = UnitInteractions.GetAvailableActions(unit);
if ((unit.path?.PathLength() ?? -1) > 0) {
log.Debug("cancelling path for " + unit);
unit.path = TilePath.NONE;
}
// Allow cancellation of active worker jobs by clicking on the unit.
if (unit.WorkerJob != null) {
unit.resetWorkerJob();
}
// Allow cancellation automation via clicking on the unit.
if (unit.isAutomated) {
unit.isAutomated = false;
unit.currentAI = null;
}
this.CurrentlySelectedUnit = unit;
this.KeepCSUWhenFortified = unit.isFortified; // If fortified, make sure the autoselector doesn't immediately skip past the unit
if (unit != MapUnit.NONE) {
ensureLocationIsInView(unit.location);
}
if (unit != MapUnit.NONE && !unit.movementPoints.canMove) {
return false;
}
// Also emit the signal for a new unit being selected, so other areas such as Game Status and Unit Buttons can update
if (CurrentlySelectedUnit != MapUnit.NONE) {
ParameterWrapper<MapUnit> wrappedUnit = new ParameterWrapper<MapUnit>(CurrentlySelectedUnit);
EmitSignal(SignalName.NewAutoselectedUnit, wrappedUnit);
return true;
} else {
EmitSignal(SignalName.NoMoreAutoselectableUnits);
return false;
}
}
private void _onEndTurnButtonPressed() {
if (CurrentState == GameState.PlayerTurn) {
OnPlayerEndTurn();
} else {
log.Information("It's not your turn!");
}
}
private void OnPlayerStartTurn() {
EngineStorage.ReadGameData((GameData gameData) => {
log.Information("Starting player turn");
// If the player can now pick a new government, force them to do so.
// When the popup is closed we call OnPlayerStartTurn again. This isn't
// ideal, but we don't yet have a general purpose "show a popup and
// wait for the player to acknowledge it" system.
if (controller.government.transitionType && TurnHandling.GetTurnNumber() >= controller.inAnarchyUntilTurn) {
popupOverlay.ShowPopup(
new GovernmentSelection(controller, controller.GetAvailableGovernments(gameData)),
PopupOverlay.PopupCategory.Info);
}
// If the player can pick a new tech to research, prompt them to do so
// once they have a city.
if (controller.cities.Count > 0
&& controller.currentlyResearchedTech == null
&& controller.GetAvailableTechsToResearch(gameData).Count > 0) {
popupOverlay.ShowPopup(
new ScienceSelection(controller),
PopupOverlay.PopupCategory.Info);
}
// Allow fast forwarding in observer mode.
if (gameData.observerMode && turnsLeftToFastForward > 0) {
--turnsLeftToFastForward;
new MsgEndTurn().send();
return;
}
CurrentState = GameState.PlayerTurn;
GetNextAutoselectedUnit(gameData);
});
}
private void OnPlayerEndTurn() {
if (CurrentState != GameState.PlayerTurn) {
return;
}
// Prompt the user if they would have a city riot when the turn ended.
EngineStorage.ReadGameData((GameData gameData) => {
foreach (City city in controller.cities) {
if (!controller.isHuman) {
continue;
}
City.Mood cityMood = city.RecalculateCitizenMoods(gameData);
if (cityMood == City.Mood.Unhappy) {
popupOverlay.ShowPopup(
new ConfirmationPopup(
$"{city.name} will riot! Are you sure?",
"Yes, let them riot!",
"No. Maybe you are right, advisor.",
() => {
DoActualEndTurn();
}),
PopupOverlay.PopupCategory.Advisor);
return;
}
}
});
DoActualEndTurn();
}
private void DoActualEndTurn() {
log.Information("Ending player turn");
EmitSignal(SignalName.TurnEnded);
log.Information("Starting computer turn");
CurrentState = GameState.ComputerTurn;
new MsgEndTurn().send(); // Triggers actual backend processing
}
public void _on_QuitButton_pressed() {
// This apparently exits the whole program
// GetTree().Quit();
// ChangeSceneToFile deletes the current scene and frees its memory, so this is quitting to main menu
GetTree().ChangeSceneToFile("res://UIElements/MainMenu/main_menu.tscn");
}
public void _on_Zoom_value_changed(float value) {
mapView.setCameraZoomFromMiddle(value);
}
public void AdjustZoomSlider(int numSteps, Vector2 zoomCenter) {
double newScale = slider.Value + slider.Step * (double)numSteps;
if (newScale < slider.MinValue)
newScale = slider.MinValue;
else if (newScale > slider.MaxValue)
newScale = slider.MaxValue;
// Note we must set the camera zoom before setting the new slider value since setting the value will trigger the callback which will
// adjust the zoom around a center we don't want.
mapView.setCameraZoom((float)newScale, zoomCenter);
slider.Value = newScale;
}
public void _on_RightButton_pressed() {
mapView.cameraLocation += new Vector2(128, 0);
}
public void _on_LeftButton_pressed() {
mapView.cameraLocation += new Vector2(-128, 0);
}
public void _on_UpButton_pressed() {
mapView.cameraLocation += new Vector2(0, -64);
}
public void _on_DownButton_pressed() {
mapView.cameraLocation += new Vector2(0, 64);
}
public override void _Input(InputEvent @event) {
if (@event is InputEventKey e && e.Pressed && !e.IsAction(C7Action.UnitGoto)) {
this.setGotoMode(false);
}
}
public override void _UnhandledInput(InputEvent @event) {
// Don't handle mouse actions if UI elements are visible
if (popupOverlay.Visible || cityScreen.Visible || advisor.Visible || diplomacy.Visible || palaceScreen.Visible) {
IsMovingCamera = false;
return;
}
// Control node must not be in the way and/or have mouse pass enabled
if (@event is InputEventMouseButton eventMouseButton) {
HandleMouseButtonInput(eventMouseButton);
} else if (@event is InputEventMouseMotion eventMouseMotion) {
HandleMouseMotionInput(eventMouseMotion);
} else if (@event is InputEventKey eventKeyDown && eventKeyDown.Pressed) {
HandleKeyboardInput(eventKeyDown);
} else if (@event is InputEventMagnifyGesture magnifyGesture) {
HandleMagnifyGesture(magnifyGesture);
}
}
private void HandleMouseButtonInput(InputEventMouseButton eventMouseButton) {
if (eventMouseButton.ButtonIndex == MouseButton.Left) {
HandleLeftMouseButton(eventMouseButton);
} else if (eventMouseButton.ButtonIndex == MouseButton.Right && !eventMouseButton.IsPressed()) {
HandleRightMouseButton(eventMouseButton);
} else if (eventMouseButton.ButtonIndex == MouseButton.WheelUp) {
GetViewport().SetInputAsHandled();
AdjustZoomSlider(1, GetViewport().GetMousePosition());
} else if (eventMouseButton.ButtonIndex == MouseButton.WheelDown) {
GetViewport().SetInputAsHandled();
AdjustZoomSlider(-1, GetViewport().GetMousePosition());
}
}
private void HandleLeftMouseButton(InputEventMouseButton eventMouseButton) {
GetViewport().SetInputAsHandled();
if (eventMouseButton.IsPressed()) {
OldPosition = eventMouseButton.Position;
IsMovingCamera = true;
if (CanDoubleClick(eventMouseButton)) {
doubleClickHandler.Accept(eventMouseButton);
} else {
OnSingleLeftMouseButtonClick(eventMouseButton);
}
} else {
IsMovingCamera = false;
}
}
private Tile PositionToTile(Vector2 position) {
Tile tile = null;
EngineStorage.ReadGameData((GameData gameData) => {
tile = mapView.tileOnScreenAt(gameData.map, position);
});
return tile;
}
private bool CanDoubleClick(InputEventMouseButton eventMouseButton) {
Tile tile = PositionToTile(eventMouseButton.Position);
return gotoInfo == null && tile?.cityAtTile?.owner == controller;
}
private void OnSingleLeftMouseButtonClick(InputEventMouseButton eventMouseButton) {
if (gotoInfo != null) {
HandleGotoClick(gotoInfo);
setGotoMode(false);
} else {
// Select unit on tile at mouse location
HandleUnitSelection(eventMouseButton);
}
}
private void OnDoubleLeftMouseButtonClick(InputEventMouseButton eventMouseButton) {
Tile tile = PositionToTile(eventMouseButton.Position);
if (tile?.cityAtTile?.owner == controller) {
EngineStorage.ReadGameData((GameData gameData) => {
ShowCityScreenForCity(gameData, tile.cityAtTile);
});
}
}
private void HandleUnitSelection(InputEventMouseButton eventMouseButton) {
Tile tile = PositionToTile(eventMouseButton.Position);
if (tile == null) {
return;
}
// TODO: This should really be the top unit.
MapUnit to_select = tile.unitsOnTile.FirstOrDefault();
if (to_select == null || to_select.owner != controller) {
return;
}
bool canMove = setSelectedUnit(to_select);
if (!canMove) {
TemporaryPopup popup = new("This unit has already moved.", 1);
popup.SetPosition(eventMouseButton.Position + new Vector2(0, -64));
AddChild(popup);
popup.ShowPopup();
}
}
private void HandleRightMouseButton(InputEventMouseButton eventMouseButton) {
setGotoMode(false);
Tile tile = PositionToTile(eventMouseButton.Position);
if (tile != null) {
HandleRightClickOnTile(tile, eventMouseButton);
} else {
log.Debug("Didn't click on any tile");
}
}
private void HandleRightClickOnTile(Tile tile, InputEventMouseButton eventMouseButton) {
bool shiftDown = Input.IsKeyPressed(Godot.Key.Shift);
// Handle the shortcut of shift+right clicking a city to get the change production menu.
if (shiftDown && tile.cityAtTile?.owner == controller)
new RightClickChooseProductionMenu(this, tile.cityAtTile).Open(eventMouseButton.Position);
else if (!shiftDown && tile.unitsOnTile.Count > 0)
// There are units on this title, so open that menu.
new RightClickTileMenu(this, tile).Open(eventMouseButton.Position);
else if (!shiftDown && tile.cityAtTile?.owner == controller)
// There are no units, but this is the player's city.
new RightClickCityMenu(this, tile).Open(eventMouseButton.Position);
LogTileDetails(tile);
}
private void LogTileDetails(Tile tile) {
string yield = tile.YieldString(controller);
log.Debug($"({tile.XCoordinate}, {tile.YCoordinate}): {tile.overlayTerrainType.DisplayName} {yield}");
if (tile.cityAtTile != null) {
LogCityDetails(tile.cityAtTile);
}
if (tile.unitsOnTile.Count > 0) {
LogUnitDetails(tile.unitsOnTile);
}
}
private void LogCityDetails(City city) {
log.Debug($" {city.name}, production {city.shieldsStored} of {city.owner.ShieldCost(city.itemBeingProduced)}");
foreach (CityResident resident in city.residents) {
log.Debug($" Resident working at {resident.tileWorked}");
}
}
private void LogUnitDetails(List<MapUnit> unitsOnTile) {
foreach (MapUnit unit in unitsOnTile) {
log.Debug(" Unit on tile: " + unit);
if (unit.currentAI != null) {
log.Debug(" Strategy: " + unit.currentAI.SummarizePlan());
}
}
}
private void HandleMouseMotionInput(InputEventMouseMotion eventMouseMotion) {
if (IsMovingCamera) {
GetViewport().SetInputAsHandled();
mapView.cameraLocation += OldPosition - eventMouseMotion.Position;
OldPosition = eventMouseMotion.Position;
} else if (gotoInfo != null) {
gotoInfo = GetGotoInfo(eventMouseMotion.Position);
}
}
private void HandleKeyboardInput(InputEventKey eventKeyDown) {
if (eventKeyDown.Keycode == Godot.Key.O && eventKeyDown.ShiftPressed && eventKeyDown.IsCommandOrControlPressed() && eventKeyDown.AltPressed) {
ToggleObserverMode();
}
if (eventKeyDown.Keycode == Godot.Key.G && eventKeyDown.ShiftPressed && eventKeyDown.IsCommandOrControlPressed() && eventKeyDown.AltPressed) {
ToggleGridCoordinates();
}
if (eventKeyDown.Keycode == Godot.Key.T && eventKeyDown.ShiftPressed && eventKeyDown.IsCommandOrControlPressed() && eventKeyDown.AltPressed) {
ToggleC7Graphics();
}
if (eventKeyDown.Keycode == Godot.Key.F1) {
EmitSignal(SignalName.ShowSpecificAdvisor, "F1");
}
if (eventKeyDown.Keycode == Godot.Key.F3) {
EmitSignal(SignalName.ShowSpecificAdvisor, "F3");
}
if (eventKeyDown.Keycode == Godot.Key.F6) {
EmitSignal(SignalName.ShowSpecificAdvisor, "F6");
}
if (eventKeyDown.Keycode == Godot.Key.F9) {
palaceScreen.Show();
}
if (eventKeyDown.Keycode == Godot.Key.C && HasCurrentlySelectedUnit()) {
mapView.centerCameraOnTile(CurrentlySelectedUnit.location);
}
if (eventKeyDown.Keycode == Godot.Key.H) {
City capital = controller.cities.Find(c => c.IsCapital());
if (capital != null) {
mapView.centerCameraOnTile(capital.location);
}
}
}
private void ToggleObserverMode() {
EngineStorage.ReadGameData((GameData gameData) => {
gameData.observerMode = !gameData.observerMode;
if (gameData.observerMode) {
SetObserverModeOn(gameData);
} else {
SetObserverModeOff(gameData);
}
});
}
private void SetObserverModeOn(GameData gameData) {
foreach (Player player in gameData.players) {
player.isHuman = false;
}
SetAnimationsEnabled(false);
popupOverlay.ShowPopup(
new TextDialog("How many turns to fast forward through?",
"Turns: ", "100",
BoxContainer.AlignmentMode.Begin,
(string turns) => { turnsLeftToFastForward = int.Parse(turns); }),
PopupOverlay.PopupCategory.Advisor);
}
private void SetObserverModeOff(GameData gameData) {
foreach (Player player in gameData.players) {
if (player.id == EngineStorage.uiControllerID) {
player.isHuman = true;
}
}
}
private void ToggleGridCoordinates() {
EngineStorage.ReadGameData((GameData gameData) => {
gameData.showGridCoordinates = !gameData.showGridCoordinates;
});
}
private void ToggleC7Graphics() {
TextureLoader.ToggleModernGraphics();
InitializeMapView();
}
private void HandleMagnifyGesture(InputEventMagnifyGesture magnifyGesture) {
// UI slider has the min/max zoom settings for now
double newScale = mapView.cameraZoom * magnifyGesture.Factor;
if (newScale < slider.MinValue)
newScale = slider.MinValue;
else if (newScale > slider.MaxValue)
newScale = slider.MaxValue;
mapView.setCameraZoom((float)newScale, magnifyGesture.Position);
// Update the UI slider
slider.Value = newScale;
}
private void ProcessActions() {
Godot.Collections.Array<StringName> actions = InputMap.GetActions();
foreach (StringName action in actions) {
if (Input.IsActionJustPressed(action)) {
ProcessAction(action.ToString());
}
}
}
private void ProcessAction(string currentAction) {
if (currentAction == C7Action.Escape && popupOverlay.ShowingPopup) {
popupOverlay.OnHidePopup();
return;
}
if (currentAction == C7Action.Escape && cityScreen.Visible) {
cityScreen.Hide();
return;
}
if (currentAction == C7Action.Escape && palaceScreen.Visible) {
palaceScreen.Hide();
return;
}
if (currentAction == C7Action.Escape && advisor.Visible) {
advisor.Hide();
return;
}
if (currentAction == C7Action.Escape && diplomacy.Visible) {
diplomacy.Hide();
return;
}
// never poll for actions if UI elements are visible
if (popupOverlay.Visible || cityScreen.Visible || advisor.Visible || diplomacy.Visible || palaceScreen.Visible) {
return;
}
if (currentAction == C7Action.EndTurn && !this.HasCurrentlySelectedUnit()) {
log.Verbose("end_turn key pressed");
this.OnPlayerEndTurn();
}
if (this.HasCurrentlySelectedUnit()) {
TileDirection? dir = C7Action.ToTileDirection(currentAction);
if (dir.HasValue) {
new MsgMoveUnit(CurrentlySelectedUnit.id, dir.Value).send();
}
}
if (currentAction == C7Action.ToggleGrid) {
this.mapView.gridLayer.visible = !this.mapView.gridLayer.visible;
}
if (currentAction == C7Action.Escape && this.gotoInfo == null) {
log.Debug("Got request for escape/quit");
popupOverlay.ShowPopup(new EscapeQuitPopup(), PopupOverlay.PopupCategory.Info);
}
if (currentAction == C7Action.ToggleZoom) {
if (mapView.cameraZoom != 1) {
mapView.setCameraZoomFromMiddle(1.0f);
slider.Value = 1.0f;
} else {
mapView.setCameraZoomFromMiddle(0.5f);
slider.Value = 0.5f;
}
}
if (currentAction == C7Action.ToggleAnimations) {
SetAnimationsEnabled(false);
} else if (Input.IsActionJustReleased(C7Action.ToggleAnimations)) {
SetAnimationsEnabled(true);
}
// actions with unit buttons
if (currentAction == C7Action.UnitHold) {
new ActionToEngineMsg(() => CurrentlySelectedUnit?.skipTurn()).send();
}
if (currentAction == C7Action.UnitWait) {
EngineStorage.ReadGameData((GameData gameData) => {
UnitInteractions.waitUnit(gameData, CurrentlySelectedUnit.id);
GetNextAutoselectedUnit(gameData);
});
}
if (currentAction == C7Action.UnitFortify) {
new MsgSetFortification(CurrentlySelectedUnit.id, true).send();
}
if (currentAction == C7Action.UnitDisband) {
popupOverlay.ShowPopup(
new ConfirmationPopup(
$"Disband {CurrentlySelectedUnit.unitType.name}? Pardon me but these are OUR people. Do \nyou really want to disband them?",
"Yes, we need to!",
"No. Maybe you are right, advisor.",
() => {
new ActionToEngineMsg(() => CurrentlySelectedUnit?.disband()).send();
}),
PopupOverlay.PopupCategory.Advisor);
}
// unit_goto's behavior is more complicated than other actions - it
// toggles the go to state, but must be detoggled in _*Input methods if
// it is not the input being pressed.
if (currentAction == C7Action.UnitGoto) {
setGotoMode(true);
}
if (currentAction == C7Action.UnitExplore && CurrentlySelectedUnit != MapUnit.NONE) {
new ActionToEngineMsg(() => CurrentlySelectedUnit?.explore()).send();
}
if (currentAction == C7Action.UnitAutomate && CurrentlySelectedUnit != MapUnit.NONE) {
new ActionToEngineMsg(() => CurrentlySelectedUnit?.automate()).send();
}
if (currentAction == C7Action.UnitSentry) {
// unimplemented
}
if (currentAction == C7Action.UnitSentryEnemyOnly) {
// unimplemented
}
if (currentAction == C7Action.UnitBuildCity && CurrentlySelectedUnit != MapUnit.NONE && (CurrentlySelectedUnit?.canBuildCity() ?? false)) {
EngineStorage.ReadGameData((GameData gameData) => {
MapUnit currentUnit = gameData.GetUnit(CurrentlySelectedUnit.id);
log.Debug(currentUnit.Describe());
if (currentUnit.canBuildCity()) {
popupOverlay.ShowPopup(new BuildCityDialog(controller.GetNextCityName()),
PopupOverlay.PopupCategory.Advisor);
}
});
}
Terraform terraform = C7Action.ToTerraform(currentAction);
if (terraform != null
&& CurrentlySelectedUnit != MapUnit.NONE
&& CurrentlySelectedUnit.canPerformTerraformAction(terraform)) {
new MsgStartWorkerJob(CurrentlySelectedUnit?.id, terraform).send();
}
}
private void GetNextAutoselectedUnit(GameData gameData) {
this.setSelectedUnit(UnitInteractions.getNextSelectedUnit(gameData));
}
private void setGotoMode(bool isOn) {
if (isOn) {
gotoInfo = new();
} else {
gotoInfo = null;
}
}
private void HandleGotoClick(GotoInfo info) {
if (info == null || info.moveCost == -1) {
return;
}
EngineStorage.ReadGameData((GameData gameData) => {
int currentTurn = gameData.turn;
// If this move would require declaring war, display a popup that checks
// if the player really wants to declare war. If they do, declare the
// war for them, clear out the player, and call this method again.
if (info.requiresWarDeclarationOnPlayer != null) {
GotoInfo stashed = info;
popupOverlay.ShowPopup(new WarConfirmation(stashed.requiresWarDeclarationOnPlayer,
() => {
controller.DeclareWarOn(info.requiresWarDeclarationOnPlayer, currentTurn);
stashed.requiresWarDeclarationOnPlayer = null;
HandleGotoClick(stashed);
}), PopupOverlay.PopupCategory.Advisor);
return;
}
new MsgSetUnitPath(CurrentlySelectedUnit.id, info.path).send();
});
}
private GotoInfo GetGotoInfo(Vector2 mousePos) {
GotoInfo result = new();
// We're in "goto" mode and moved the mouse over a tile.
//
// Figure out which tile it was.
EngineStorage.ReadGameData((GameData gameData) => {
Tile tile = mapView.tileOnScreenAt(gameData.map, mousePos);
result.destinationTile = tile;
// Figure out what unit is in goto mode. If the tile we're hovering over is
// different than the tile the unit is on, calculate the path to move there.
MapUnit unit = tile == null ? null : gameData.GetUnit(CurrentlySelectedUnit.id);
if (unit != null && unit.location != tile) {