/
Game.cpp
2130 lines (1725 loc) · 59.4 KB
/
Game.cpp
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "Rendering/GL/myGL.h"
#include <SDL_keyboard.h>
#include "Game.h"
#include "GameJobDispatcher.h"
#include "Benchmark.h"
#include "Camera.h"
#include "CameraHandler.h"
#include "ChatMessage.h"
#include "CommandMessage.h"
#include "ConsoleHistory.h"
#include "GameHelper.h"
#include "GameSetup.h"
#include "GlobalUnsynced.h"
#include "LoadScreen.h"
#include "SelectedUnitsHandler.h"
#include "WaitCommandsAI.h"
#include "WordCompletion.h"
#include "IVideoCapturing.h"
#include "InMapDraw.h"
#include "InMapDrawModel.h"
#include "SyncedActionExecutor.h"
#include "SyncedGameCommands.h"
#include "UnsyncedActionExecutor.h"
#include "UnsyncedGameCommands.h"
#include "Game/Players/Player.h"
#include "Game/Players/PlayerHandler.h"
#include "Game/UI/PlayerRoster.h"
#include "Game/UI/PlayerRosterDrawer.h"
#include "Game/UI/UnitTracker.h"
#include "ExternalAI/EngineOutHandler.h"
#include "ExternalAI/IAILibraryManager.h"
#include "ExternalAI/SkirmishAIHandler.h"
#include "Rendering/WorldDrawer.h"
#include "Rendering/Env/IWater.h"
#include "Rendering/Fonts/CFontTexture.h"
#include "Rendering/Fonts/glFont.h"
#include "Rendering/CommandDrawer.h"
#include "Rendering/LineDrawer.h"
#include "Rendering/GlobalRendering.h"
#include "Rendering/Env/Particles/ProjectileDrawer.h"
#include "Rendering/DebugDrawerAI.h"
#include "Rendering/HUDDrawer.h"
#include "Rendering/IconHandler.h"
#include "Rendering/TeamHighlight.h"
#include "Rendering/UnitDrawer.h"
#include "Rendering/Map/InfoTexture/IInfoTextureHandler.h"
#include "Rendering/Textures/ColorMap.h"
#include "Rendering/Textures/NamedTextures.h"
#include "Lua/LuaInputReceiver.h"
#include "Lua/LuaHandle.h"
#include "Lua/LuaGaia.h"
#include "Lua/LuaRules.h"
#include "Lua/LuaOpenGL.h"
#include "Lua/LuaParser.h"
#include "Lua/LuaSyncedRead.h"
#include "Lua/LuaUI.h"
#include "Lua/LuaUtils.h"
#include "Map/MapDamage.h"
#include "Map/MapInfo.h"
#include "Map/ReadMap.h"
#include "Sim/Features/FeatureDef.h"
#include "Sim/Features/FeatureDefHandler.h"
#include "Sim/Features/FeatureHandler.h"
#include "Sim/Misc/CategoryHandler.h"
#include "Sim/Misc/DamageArrayHandler.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/GroundBlockingObjectMap.h"
#include "Sim/Misc/BuildingMaskMap.h"
#include "Sim/Misc/LosHandler.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/Misc/InterceptHandler.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/SideParser.h"
#include "Sim/Misc/SmoothHeightMesh.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Misc/Wind.h"
#include "Sim/Misc/ResourceHandler.h"
#include "Sim/MoveTypes/MoveDefHandler.h"
#include "Sim/Path/IPathManager.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Projectiles/Projectile.h"
#include "Sim/Projectiles/ProjectileHandler.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/Scripts/CobEngine.h"
#include "Sim/Units/Scripts/UnitScriptEngine.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Units/UnitDefHandler.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "UI/CommandColors.h"
#include "UI/EndGameBox.h"
#include "UI/GameInfo.h"
#include "UI/GameSetupDrawer.h"
#include "UI/GuiHandler.h"
#include "UI/InfoConsole.h"
#include "UI/KeyBindings.h"
#include "UI/KeyCodes.h"
#include "UI/MiniMap.h"
#include "UI/MouseHandler.h"
#include "UI/QuitBox.h"
#include "UI/ResourceBar.h"
#include "UI/SelectionKeyHandler.h"
#include "UI/ShareBox.h"
#include "UI/TooltipConsole.h"
#include "UI/ProfileDrawer.h"
#include "UI/Groups/GroupHandler.h"
#include "System/Config/ConfigHandler.h"
#include "System/EventHandler.h"
#include "System/Exceptions.h"
#include "System/Sync/FPUCheck.h"
#include "System/GlobalConfig.h"
#include "System/myMath.h"
#include "Net/GameServer.h"
#include "Net/Protocol/NetProtocol.h"
#include "System/SpringApp.h"
#include "System/Util.h"
#include "System/Input/KeyInput.h"
#include "System/FileSystem/FileSystem.h"
#include "System/FileSystem/VFSHandler.h"
#include "System/LoadSave/LoadSaveHandler.h"
#include "System/LoadSave/DemoRecorder.h"
#include "System/Log/ILog.h"
#include "System/Platform/Watchdog.h"
#include "System/Sound/ISound.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/DumpState.h"
#include "System/TimeProfiler.h"
#undef CreateDirectory
CONFIG(bool, WindowedEdgeMove).defaultValue(true).description("Sets whether moving the mouse cursor to the screen edge will move the camera across the map.");
CONFIG(bool, FullscreenEdgeMove).defaultValue(true).description("see WindowedEdgeMove, just for fullscreen mode");
CONFIG(bool, ShowFPS).defaultValue(false).description("Displays current framerate.");
CONFIG(bool, ShowClock).defaultValue(true).headlessValue(false).description("Displays a clock on the top-right corner of the screen showing the elapsed time of the current game.");
CONFIG(bool, ShowSpeed).defaultValue(false).description("Displays current game speed.");
CONFIG(int, ShowPlayerInfo).defaultValue(1).headlessValue(0);
CONFIG(float, GuiOpacity).defaultValue(0.8f).minimumValue(0.0f).maximumValue(1.0f).description("Sets the opacity of the built-in Spring UI. Generally has no effect on LuaUI widgets. Can be set in-game using shift+, to decrease and shift+. to increase.");
CONFIG(std::string, InputTextGeo).defaultValue("");
CGame* game = NULL;
CR_BIND(CGame, (std::string(""), std::string(""), NULL))
CR_REG_METADATA(CGame, (
CR_IGNORED(finishedLoading),
CR_IGNORED(numDrawFrames),
CR_MEMBER(lastSimFrame),
CR_IGNORED(lastNumQueuedSimFrames),
CR_IGNORED(frameStartTime),
CR_IGNORED(lastSimFrameTime),
CR_IGNORED(lastDrawFrameTime),
CR_IGNORED(lastFrameTime),
CR_IGNORED(lastReadNetTime),
CR_IGNORED(lastNetPacketProcessTime),
CR_IGNORED(lastReceivedNetPacketTime),
CR_IGNORED(lastSimFrameNetPacketTime),
CR_IGNORED(updateDeltaSeconds),
CR_MEMBER(totalGameTime),
CR_MEMBER(userInputPrefix),
CR_IGNORED(chatSound),
CR_MEMBER(hideInterface),
CR_MEMBER(gameOver),
CR_IGNORED(gameDrawMode),
CR_IGNORED(windowedEdgeMove),
CR_IGNORED(fullscreenEdgeMove),
CR_MEMBER(showFPS),
CR_MEMBER(showClock),
CR_MEMBER(showSpeed),
CR_IGNORED(chatting),
CR_IGNORED(curKeyChain),
CR_IGNORED(playerTraffic),
CR_MEMBER(noSpectatorChat),
CR_MEMBER(gameID),
//CR_MEMBER(infoConsole),
//CR_MEMBER(consoleHistory),
CR_IGNORED(inputTextPosX),
CR_IGNORED(inputTextPosY),
CR_IGNORED(inputTextSizeX),
CR_IGNORED(inputTextSizeY),
CR_IGNORED(skipping),
CR_MEMBER(playing),
CR_IGNORED(msgProcTimeLeft),
CR_IGNORED(consumeSpeedMult),
CR_IGNORED(skipStartFrame),
CR_IGNORED(skipEndFrame),
CR_IGNORED(skipTotalFrames),
CR_IGNORED(skipSeconds),
CR_IGNORED(skipSoundmute),
CR_IGNORED(skipOldSpeed),
CR_IGNORED(skipOldUserSpeed),
CR_IGNORED(skipLastDrawTime),
CR_MEMBER(speedControl),
CR_IGNORED(infoConsole),
CR_IGNORED(consoleHistory),
CR_IGNORED(jobDispatcher),
CR_IGNORED(worldDrawer),
CR_IGNORED(defsParser),
CR_IGNORED(saveFile),
// from CGameController
CR_IGNORED(writingPos),
CR_IGNORED(ignoreNextChar),
CR_IGNORED(userInput),
CR_IGNORED(userPrompt),
CR_IGNORED(userWriting),
// Post Load
CR_POSTLOAD(PostLoad)
))
CGame::CGame(const std::string& mapName, const std::string& modName, ILoadSaveHandler* saveFile)
: gameDrawMode(gameNotDrawing)
, lastSimFrame(-1)
, lastNumQueuedSimFrames(-1)
, numDrawFrames(0)
, frameStartTime(spring_gettime())
, lastSimFrameTime(spring_gettime())
, lastDrawFrameTime(spring_gettime())
, lastFrameTime(spring_gettime())
, lastReadNetTime(spring_gettime())
, lastNetPacketProcessTime(spring_gettime())
, lastReceivedNetPacketTime(spring_gettime())
, lastSimFrameNetPacketTime(spring_gettime())
, updateDeltaSeconds(0.0f)
, totalGameTime(0)
, hideInterface(false)
, skipping(false)
, playing(false)
, chatting(false)
, noSpectatorChat(false)
, msgProcTimeLeft(0.0f)
, consumeSpeedMult(1.0f)
, skipStartFrame(0)
, skipEndFrame(0)
, skipTotalFrames(0)
, skipSeconds(0.0f)
, skipSoundmute(false)
, skipOldSpeed(0.0f)
, skipOldUserSpeed(0.0f)
, skipLastDrawTime(spring_gettime())
, speedControl(-1)
, infoConsole(NULL)
, consoleHistory(NULL)
, worldDrawer(NULL)
, defsParser(NULL)
, saveFile(saveFile)
, finishedLoading(false)
, gameOver(false)
{
game = this;
jobDispatcher = new JobDispatcher();
memset(gameID, 0, sizeof(gameID));
// set "Headless" in config overlay (not persisted)
configHandler->Set("Headless", (SpringVersion::IsHeadless()) ? 1 : 0, true);
//FIXME move to MouseHandler!
windowedEdgeMove = configHandler->GetBool("WindowedEdgeMove");
fullscreenEdgeMove = configHandler->GetBool("FullscreenEdgeMove");
showFPS = configHandler->GetBool("ShowFPS");
showClock = configHandler->GetBool("ShowClock");
showSpeed = configHandler->GetBool("ShowSpeed");
speedControl = configHandler->GetInt("SpeedControl");
playerRoster.SetSortTypeByCode((PlayerRoster::SortType)configHandler->GetInt("ShowPlayerInfo"));
CInputReceiver::guiAlpha = configHandler->GetFloat("GuiOpacity");
ParseInputTextGeometry("default");
ParseInputTextGeometry(configHandler->GetString("InputTextGeo"));
// clear left-over receivers in case we reloaded
commandConsole.ResetState();
wind.ResetState();
modInfo.ResetState();
modInfo.Init(modName.c_str());
// needed for LuaIntro (pushes LuaConstGame)
assert(mapInfo == nullptr);
mapInfo = new CMapInfo(gameSetup->MapFile(), gameSetup->mapName);
if (!sideParser.Load()) {
throw content_error(sideParser.GetErrorLog());
}
// after this, other components are able to register chat action-executors
SyncedGameCommands::CreateInstance();
UnsyncedGameCommands::CreateInstance();
// note: makes no sense to create this unless we have AI's
// (events will just go into the void otherwise) but it is
// unconditionally deref'ed in too many places
CEngineOutHandler::Create();
CResourceHandler::CreateInstance();
CCategoryHandler::CreateInstance();
CWordCompletion::CreateInstance();
}
CGame::~CGame()
{
#ifdef TRACE_SYNC
tracefile << "[" << __FUNCTION__ << "]";
#endif
ENTER_SYNCED_CODE();
LOG("[%s]1]", __FUNCTION__);
KillLua();
KillMisc();
KillRendering();
KillInterface();
KillSimulation();
LOG("[%s][2]", __FUNCTION__);
SafeDelete(saveFile); // ILoadSaveHandler, depends on vfsHandler via ~IArchive
SafeDelete(jobDispatcher);
LOG("[%s][3]", __FUNCTION__);
CWordCompletion::DestroyInstance();
CCategoryHandler::RemoveInstance();
CResourceHandler::FreeInstance();
LEAVE_SYNCED_CODE();
}
void CGame::AddTimedJobs()
{
{
JobDispatcher::Job j;
j.f = []() -> bool {
SCOPED_TIMER("CollectGarbage");
eventHandler.CollectGarbage();
CInputReceiver::CollectGarbage();
return true;
};
j.freq = GAME_SPEED;
j.name = "EventHandler::CollectGarbage";
// static initialization is done BEFORE Spring's time-epoch is set, so use notime
jobDispatcher->AddTimedJob(j, spring_notime + spring_time(j.startDirect ? 0 : (1000.0f / j.freq)));
}
{
JobDispatcher::Job j;
j.f = []() -> bool {
profiler.Update();
return true;
};
j.freq = 1;
j.name = "Profiler::Update";
jobDispatcher->AddTimedJob(j, spring_notime + spring_time(j.startDirect ? 0 : (1000.0f / j.freq)));
}
}
void CGame::LoadGame(const std::string& mapName, bool threaded)
{
// NOTE:
// this is needed for LuaHandle::CallOut*UpdateCallIn
// the main-thread is NOT the same as the load-thread
// when LoadingMT=1 (!!!)
Threading::SetGameLoadThread();
Watchdog::RegisterThread(WDT_LOAD);
if (!gu->globalQuit) LoadMap(mapName);
if (!gu->globalQuit) LoadDefs();
if (!gu->globalQuit) PreLoadSimulation();
if (!gu->globalQuit) PreLoadRendering();
if (!gu->globalQuit) PostLoadSimulation();
if (!gu->globalQuit) PostLoadRendering();
if (!gu->globalQuit) LoadInterface();
if (!gu->globalQuit) LoadLua();
if (!gu->globalQuit) LoadFinalize();
if (!gu->globalQuit) LoadSkirmishAIs();
if (!gu->globalQuit && saveFile) {
loadscreen->SetLoadMessage("Loading game");
saveFile->LoadGame();
}
finishedLoading = true;
Watchdog::DeregisterThread(WDT_LOAD);
AddTimedJobs();
}
void CGame::LoadMap(const std::string& mapName)
{
ENTER_SYNCED_CODE();
{
loadscreen->SetLoadMessage("Parsing Map Information");
// simulation components
helper = new CGameHelper();
readMap = CReadMap::LoadMap(mapName);
groundBlockingObjectMap = new CGroundBlockingObjectMap(mapDims.mapSquares);
buildingMaskMap = new BuildingMaskMap();
}
LEAVE_SYNCED_CODE();
}
void CGame::LoadDefs()
{
ENTER_SYNCED_CODE();
{
loadscreen->SetLoadMessage("Loading Radar Icons");
icon::iconHandler = new icon::CIconHandler();
}
{
ScopedOnceTimer timer("Game::LoadDefs (GameData)");
loadscreen->SetLoadMessage("Loading GameData Definitions");
defsParser = new LuaParser("gamedata/defs.lua", SPRING_VFS_MOD_BASE, SPRING_VFS_ZIP);
// customize the defs environment
defsParser->GetTable("Spring");
defsParser->AddFunc("GetModOptions", LuaSyncedRead::GetModOptions);
defsParser->AddFunc("GetMapOptions", LuaSyncedRead::GetMapOptions);
defsParser->EndTable();
// run the parser
if (!defsParser->Execute()) {
throw content_error("Defs-Parser: " + defsParser->GetErrorLog());
}
const LuaTable root = defsParser->GetRoot();
if (!root.IsValid()) {
throw content_error("Error loading gamedata definitions");
}
// bail now if any of these tables in invalid
// (makes searching for errors that much easier
if (!root.SubTable("UnitDefs").IsValid()) {
throw content_error("Error loading UnitDefs");
}
if (!root.SubTable("FeatureDefs").IsValid()) {
throw content_error("Error loading FeatureDefs");
}
if (!root.SubTable("WeaponDefs").IsValid()) {
throw content_error("Error loading WeaponDefs");
}
if (!root.SubTable("ArmorDefs").IsValid()) {
throw content_error("Error loading ArmorDefs");
}
if (!root.SubTable("MoveDefs").IsValid()) {
throw content_error("Error loading MoveDefs");
}
}
{
ScopedOnceTimer timer("Game::LoadDefs (Sound)");
loadscreen->SetLoadMessage("Loading Sound Definitions");
sound->LoadSoundDefs("gamedata/sounds.lua", SPRING_VFS_MOD_BASE);
chatSound = sound->GetSoundId("IncomingChat");
}
LEAVE_SYNCED_CODE();
}
void CGame::PreLoadSimulation()
{
ENTER_SYNCED_CODE();
loadscreen->SetLoadMessage("Creating Smooth Height Mesh");
smoothGround = new SmoothHeightMesh(float3::maxxpos, float3::maxzpos, SQUARE_SIZE * 2, SQUARE_SIZE * 40);
loadscreen->SetLoadMessage("Creating QuadField & CEGs");
moveDefHandler = new MoveDefHandler(defsParser);
quadField = new CQuadField(int2(mapDims.mapx, mapDims.mapy), CQuadField::BASE_QUAD_SIZE);
damageArrayHandler = new CDamageArrayHandler(defsParser);
explGenHandler = new CExplosionGeneratorHandler();
}
void CGame::PostLoadSimulation()
{
loadscreen->SetLoadMessage("Loading Weapon Definitions");
weaponDefHandler = new CWeaponDefHandler(defsParser);
loadscreen->SetLoadMessage("Loading Unit Definitions");
unitDefHandler = new CUnitDefHandler(defsParser);
featureDefHandler = new CFeatureDefHandler(defsParser);
CUnit::InitStatic();
CCommandAI::InitCommandDescriptionCache();
CUnitScriptEngine::InitStatic();
unitHandler = new CUnitHandler();
featureHandler = new CFeatureHandler();
projectileHandler = new CProjectileHandler();
loadscreen->SetLoadMessage("Loading Feature Definitions");
losHandler = new CLosHandler();
// pre-load the PFS, gets finalized after Lua
//
// features loaded from the map (and any terrain changes
// made by Lua while loading) would otherwise generate a
// queue of pending PFS updates, which should be consumed
// to avoid blocking regular updates from being processed
// but doing so was impossible without stalling the loading
// thread for *minutes* (in the worst-case scenario)
//
// the only disadvantage is that LuaPathFinder can not be
// used during Lua initialization anymore (not a concern)
//
// NOTE:
// the cache written to disk will reflect changes made by
// Lua which can vary each run with {mod,map}options, etc
// --> need a way to let Lua flush it or re-calculate map
// checksum (over heightmap + blockmap, not raw archive)
mapDamage = IMapDamage::GetMapDamage();
pathManager = IPathManager::GetInstance(modInfo.pathFinderSystem);
// load map-specific features
loadscreen->SetLoadMessage("Initializing Map Features");
featureDefHandler->LoadFeatureDefsFromMap();
if (saveFile == nullptr)
featureHandler->LoadFeaturesFromMap();
wind.LoadWind(mapInfo->atmosphere.minWind, mapInfo->atmosphere.maxWind);
inMapDrawerModel = new CInMapDrawModel();
inMapDrawer = new CInMapDraw();
syncedGameCommands->AddDefaultActionExecutors();
unsyncedGameCommands->AddDefaultActionExecutors();
LEAVE_SYNCED_CODE();
}
void CGame::PreLoadRendering()
{
geometricObjects = new CGeometricObjects();
worldDrawer = new CWorldDrawer();
// load components that need to exist before PostLoadSimulation
worldDrawer->LoadPre();
}
void CGame::PostLoadRendering() {
worldDrawer->LoadPost();
}
void CGame::LoadInterface()
{
{
ScopedOnceTimer timer("Game::LoadInterface (Camera&Mouse)");
camHandler = new CCameraHandler();
mouse = new CMouseHandler();
}
selectedUnitsHandler.Init(playerHandler->ActivePlayers());
// interface components
ReColorTeams();
cmdColors.LoadConfigFromFile("cmdcolors.txt");
{
ScopedOnceTimer timer("Game::LoadInterface (Console)");
consoleHistory = new CConsoleHistory;
for (int pp = 0; pp < playerHandler->ActivePlayers(); pp++) {
wordCompletion->AddWord(playerHandler->Player(pp)->name, false, false, false);
}
// add the Skirmish AIs instance names to word completion,
// for various things, eg chatting
const CSkirmishAIHandler::id_ai_t& ais = skirmishAIHandler.GetAllSkirmishAIs();
// add the available Skirmish AI libraries to word completion, for /aicontrol
const IAILibraryManager::T_skirmishAIKeys& aiLibs = aiLibManager->GetSkirmishAIKeys();
// add the available Lua AI implementations to word completion, for /aicontrol
const std::set<std::string>& luaAIShortNames = skirmishAIHandler.GetLuaAIImplShortNames();
for (const auto& ai: ais) {
wordCompletion->AddWord(ai.second.name + " ", false, false, false);
}
for (const auto& aiLib: aiLibs) {
wordCompletion->AddWord(aiLib.GetShortName() + " " + aiLib.GetVersion() + " ", false, false, false);
}
for (const std::string& sn: luaAIShortNames) {
wordCompletion->AddWord(sn + " ", false, false, false);
}
const auto& unitDefs = unitDefHandler->unitDefIDsByName;
const auto& featureDefs = featureDefHandler->GetFeatureDefs();
for (auto uit = unitDefs.cbegin(); uit != unitDefs.cend(); ++uit) {
wordCompletion->AddWord(uit->first + " ", false, true, false);
}
for (auto fit = featureDefs.cbegin(); fit != featureDefs.cend(); ++fit) {
wordCompletion->AddWord(fit->first + " ", false, true, false);
}
}
infoConsole = new CInfoConsole();
tooltip = new CTooltipConsole();
guihandler = new CGuiHandler();
minimap = new CMiniMap();
resourceBar = new CResourceBar();
keyCodes = new CKeyCodes();
keyBindings = new CKeyBindings();
keyBindings->Load("uikeys.txt");
selectionKeys = new CSelectionKeyHandler();
IInfoTextureHandler::Create();
for (int t = 0; t < teamHandler->ActiveTeams(); ++t) {
grouphandlers.push_back(new CGroupHandler(t));
}
// note: disable is needed in case user reloads before StartPlaying
GameSetupDrawer::Disable();
GameSetupDrawer::Enable();
}
void CGame::LoadLua()
{
// Lua components
ENTER_SYNCED_CODE();
loadscreen->SetLoadMessage("Loading LuaRules");
CLuaRules::LoadFreeHandler();
if (gs->useLuaGaia) {
loadscreen->SetLoadMessage("Loading LuaGaia");
CLuaGaia::LoadFreeHandler();
}
LEAVE_SYNCED_CODE();
loadscreen->SetLoadMessage("Loading LuaUI");
CLuaUI::LoadFreeHandler();
// last in, first served
luaInputReceiver = new LuaInputReceiver();
SafeDelete(defsParser);
}
void CGame::LoadSkirmishAIs()
{
if (gameSetup->hostDemo)
return;
// create a Skirmish AI if required
const CSkirmishAIHandler::ids_t& localAIs = skirmishAIHandler.GetSkirmishAIsByPlayer(gu->myPlayerNum);
if (!localAIs.empty()) {
loadscreen->SetLoadMessage("Loading Skirmish AIs");
for (auto ai = localAIs.begin(); ai != localAIs.end(); ++ai) {
skirmishAIHandler.CreateLocalSkirmishAI(*ai);
}
}
}
void CGame::LoadFinalize()
{
ENTER_SYNCED_CODE();
eventHandler.GamePreload();
LEAVE_SYNCED_CODE();
{
loadscreen->SetLoadMessage("[" + std::string(__FUNCTION__) + "] finalizing PFS");
ENTER_SYNCED_CODE();
const boost::uint64_t dt = pathManager->Finalize();
const boost::uint32_t cs = pathManager->GetPathCheckSum();
LEAVE_SYNCED_CODE();
loadscreen->SetLoadMessage(
"[" + std::string(__FUNCTION__) + "] finalized PFS " +
"(" + IntToString(dt, "%ld") + "ms, checksum " + IntToString(cs, "%08x") + ")"
);
}
if (CBenchmark::enabled) {
static CBenchmark benchmark;
// in case we reloaded (benchmark does not get deleted
// until program exit, so only data of the most recent
// run counts)
benchmark.ResetState();
}
lastReadNetTime = spring_gettime();
lastSimFrameTime = lastReadNetTime;
lastDrawFrameTime = lastReadNetTime;
updateDeltaSeconds = 0.0f;
}
void CGame::PostLoad()
{
GameSetupDrawer::Disable();
if (gameServer) {
gameServer->PostLoad(gs->frameNum);
}
}
void CGame::KillLua()
{
ENTER_SYNCED_CODE();
LOG("[%s][1]", __FUNCTION__);
CLuaGaia::FreeHandler();
LOG("[%s][2]", __FUNCTION__);
CLuaRules::FreeHandler();
LEAVE_SYNCED_CODE();
// kill LuaUI here, various handler pointers are invalid in ~GuiHandler
LOG("[%s][3]", __FUNCTION__);
CLuaUI::FreeHandler();
LOG("[%s][4]", __FUNCTION__);
LuaOpenGL::Free();
}
void CGame::KillMisc()
{
LOG("[%s][1]", __FUNCTION__);
CEndGameBox::Destroy();
CLoadScreen::DeleteInstance(); // make sure to halt loading, otherwise crash :)
IVideoCapturing::FreeInstance();
LOG("[%s][2]", __FUNCTION__);
// delete this first since AI's might call back into sim-components in their dtors
// this means the simulation *should not* assume the EOH still exists on game exit
CEngineOutHandler::Destroy();
// TODO move these to the end of this dtor, once all action-executors are registered by their respective engine sub-parts
UnsyncedGameCommands::DestroyInstance();
SyncedGameCommands::DestroyInstance();
}
void CGame::KillRendering()
{
LOG("[%s][1]", __FUNCTION__);
SafeDelete(infoTextureHandler);
SafeDelete(icon::iconHandler);
SafeDelete(geometricObjects);
SafeDelete(worldDrawer);
}
void CGame::KillInterface()
{
LOG("[%s][1]", __FUNCTION__);
SafeDelete(guihandler);
SafeDelete(minimap);
SafeDelete(resourceBar);
SafeDelete(tooltip); // CTooltipConsole*
SafeDelete(infoConsole);
SafeDelete(consoleHistory);
SafeDelete(keyBindings);
SafeDelete(keyCodes);
SafeDelete(selectionKeys); // CSelectionKeyHandler*
SafeDelete(luaInputReceiver);
SafeDelete(mouse); // CMouseHandler*
SafeDelete(inMapDrawerModel);
SafeDelete(inMapDrawer);
LOG("[%s][2]", __FUNCTION__);
SafeDelete(camHandler);
for (unsigned int i = 0; i < grouphandlers.size(); i++) {
SafeDelete(grouphandlers[i]);
}
grouphandlers.clear();
}
void CGame::KillSimulation()
{
LOG("[%s][1]", __FUNCTION__);
// Kill all teams that are still alive, in
// case the game did not do so through Lua.
//
// must happen after Lua (cause CGame is already
// null'ed and Died() causes a Lua event, which
// could issue Lua code that tries to access it)
for (int t = 0; t < teamHandler->ActiveTeams(); ++t) {
teamHandler->Team(t)->Died(false);
}
LOG("[%s][2]", __FUNCTION__);
if (unitHandler) unitHandler->DeleteScripts();
SafeDelete(featureHandler); // depends on unitHandler (via ~CFeature)
SafeDelete(unitHandler);
SafeDelete(projectileHandler);
LOG("[%s][3]", __FUNCTION__);
IPathManager::FreeInstance(pathManager);
SafeDelete(readMap);
SafeDelete(smoothGround);
SafeDelete(groundBlockingObjectMap);
SafeDelete(buildingMaskMap);
SafeDelete(losHandler);
SafeDelete(mapDamage);
SafeDelete(quadField);
SafeDelete(moveDefHandler);
SafeDelete(unitDefHandler);
SafeDelete(featureDefHandler);
SafeDelete(weaponDefHandler);
SafeDelete(damageArrayHandler);
SafeDelete(explGenHandler);
SafeDelete(helper);
SafeDelete((mapInfo = const_cast<CMapInfo*>(mapInfo)));
LOG("[%s][4]", __FUNCTION__);
CCommandAI::KillCommandDescriptionCache();
CUnitScriptEngine::KillStatic();
}
void CGame::ResizeEvent()
{
if (minimap != NULL) {
minimap->UpdateGeometry();
}
// reload water renderer (it may depend on screen resolution)
water = IWater::GetWater(water, water->GetID());
eventHandler.ViewResize();
}
int CGame::KeyPressed(int key, bool isRepeat)
{
if (!gameOver && !isRepeat) {
playerHandler->Player(gu->myPlayerNum)->currentStats.keyPresses++;
}
const CKeySet ks(key, false);
curKeyChain.push_back(key, spring_gettime(), isRepeat);
// Get the list of possible key actions
//LOG_L(L_DEBUG, "curKeyChain: %s", curKeyChain.GetString().c_str());
const CKeyBindings::ActionList& actionList = keyBindings->GetActionList(curKeyChain);
if (userWriting) {
for (const Action& action: actionList) {
if (ProcessKeyPressAction(key, action)) {
// the key was used, ignore it (ex: alt+a)
ignoreNextChar = keyCodes->IsPrintable(key);
break;
}
}
return 0;
}
// try the input receivers
for (CInputReceiver* recv: GetInputReceivers()) {
if (recv && recv->KeyPressed(key, isRepeat)) {
return 0;
}
}
// try our list of actions
for (const Action& action: actionList) {
if (ActionPressed(key, action, isRepeat)) {
return 0;
}
}
// maybe a widget is interested?
if (luaUI != NULL) {
for (const Action& action: actionList) {
luaUI->GotChatMsg(action.rawline, false);
}
}
return 0;
}
int CGame::KeyReleased(int k)
{
if (userWriting) {
if (
keyCodes->IsPrintable(k)
|| k == SDLK_RETURN || k == SDLK_BACKSPACE || k == SDLK_DELETE
|| k == SDLK_HOME || k == SDLK_END || k == SDLK_RIGHT || k == SDLK_LEFT
) {
return 0;
}
}
// try the input receivers
for (CInputReceiver* recv: GetInputReceivers()) {
if (recv && recv->KeyReleased(k)) {
return 0;
}
}
// try our list of actions
CKeySet ks(k, true);
const CKeyBindings::ActionList& al = keyBindings->GetActionList(ks);
for (const Action& action: al) {
if (ActionReleased(action)) {
return 0;
}
}
return 0;
}
bool CGame::Update()
{
//TODO move as much as possible unsynced code out of this function
good_fpu_control_registers("CGame::Update");
jobDispatcher->Update();
clientNet->Update();
// When video recording do step by step simulation, so each simframe gets a corresponding videoframe
// FIXME: SERVER ALREADY DOES THIS BY ITSELF
if (videoCapturing->IsCapturing() && playing && gameServer != NULL) {
gameServer->CreateNewFrame(false, true);
}
ENTER_SYNCED_CODE();
SendClientProcUsage();
ClientReadNet(); // this can issue new SimFrame()s
if (!gameOver) {
if (clientNet->NeedsReconnect()) {
clientNet->AttemptReconnect(SpringVersion::GetFull());
}
if (clientNet->CheckTimeout(0, gs->PreSimFrame())) {
GameEnd(std::vector<unsigned char>(), true);
}
}
LEAVE_SYNCED_CODE();
return true;
}
bool CGame::UpdateUnsynced(const spring_time currentTime)
{
// timings and frame interpolation
const spring_time deltaDrawFrameTime = currentTime - lastDrawFrameTime;
const float modGameDeltaTimeSecs = mix(deltaDrawFrameTime.toMilliSecsf() * 0.001f, 0.01f, skipping);
lastDrawFrameTime = currentTime;
globalRendering->lastFrameTime = deltaDrawFrameTime.toMilliSecsf();
gu->avgFrameTime = mix(gu->avgFrameTime, deltaDrawFrameTime.toMilliSecsf(), 0.05f);
{
// update game timings
gu->gameTime += modGameDeltaTimeSecs;
gu->modGameTime += (modGameDeltaTimeSecs * gs->speedFactor * (1 - gs->paused));
if (playing && !gameOver) {
totalGameTime += modGameDeltaTimeSecs;