forked from electronicarts/CnC_Generals_Zero_Hour
-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathGameState.cpp
More file actions
1680 lines (1323 loc) · 47.2 KB
/
GameState.cpp
File metadata and controls
1680 lines (1323 loc) · 47.2 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
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: GameState.cpp ////////////////////////////////////////////////////////////////////////////
// Author: Colin Day, September 2002
// Desc: Game state singleton from which to load and save the game state
///////////////////////////////////////////////////////////////////////////////////////////////////
// INCLUDES ///////////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h"
#include "Common/file.h"
#include "Common/FileSystem.h"
#include "Common/GameEngine.h"
#include "Common/GameState.h"
#include "Common/GameStateMap.h"
#include "Common/GlobalData.h"
#include "Common/LatchRestore.h"
#include "Common/MapObject.h"
#include "Common/PlayerList.h"
#include "Common/RandomValue.h"
#include "Common/Radar.h"
#include "Common/Team.h"
#include "Common/WellKnownKeys.h"
#include "Common/XferLoad.h"
#include "Common/XferSave.h"
#include "GameClient/CampaignManager.h"
#include "GameClient/GadgetListBox.h"
#include "GameClient/GameClient.h"
#include "GameClient/GameText.h"
#include "GameClient/MapUtil.h"
#include "GameClient/MessageBox.h"
#include "GameClient/InGameUI.h"
#include "GameClient/ParticleSys.h"
#include "GameClient/TerrainVisual.h"
#include "GameLogic/GameLogic.h"
#include "GameLogic/GhostObject.h"
#include "GameLogic/PartitionManager.h"
#include "GameLogic/ScriptEngine.h"
#include "GameLogic/SidesList.h"
#include "GameLogic/TerrainLogic.h"
// PUBLIC DATA ////////////////////////////////////////////////////////////////////////////////////
GameState *TheGameState = nullptr;
// PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////
static const Char *SAVE_FILE_EOF = "SG_EOF";
static const Char *SAVE_GAME_EXTENSION = ".sav";
static const Char *ZERO_NAME_ONLY = "00000000";
static const Int MAX_SAVE_FILE_NUMBER = 99999999;
///////////////////////////////////////////////////////////////////////////////////////////////////
#define GAME_STATE_BLOCK_STRING "CHUNK_GameState" // block of save game data with game info data
#define CAMPAIGN_BLOCK_STRING "CHUNK_Campaign" // block of game data that has campaign info
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
SaveGameInfo::SaveGameInfo()
{
date.day = 0;
date.dayOfWeek = 0;
date.hour = 0;
date.milliseconds = 0;
date.minute = 0;
date.month = 0;
date.second = 0;
date.year = 0;
missionNumber = 0;
saveFileType = SAVE_FILE_TYPE_NORMAL;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
SaveGameInfo::~SaveGameInfo()
{
}
// ------------------------------------------------------------------------------------------------
/** Is this date newer than the other one passed in? */
// ------------------------------------------------------------------------------------------------
Bool SaveDate::isNewerThan( SaveDate *other )
{
// year
if( year > other->year )
return TRUE;
else if( year < other->year )
return FALSE;
else
{
// month
if( month > other->month )
return TRUE;
else if( month < other->month )
return FALSE;
else
{
// day
if( day > other->day )
return TRUE;
else if( day < other->day )
return FALSE;
else
{
// hour
if( hour > other->hour )
return TRUE;
else if( hour < other->hour )
return FALSE;
else
{
// minute
if( minute > other->minute )
return TRUE;
else if( minute < other->minute )
return FALSE;
else
{
// second
if( second > other->second )
return TRUE;
else if( second < other->second )
return FALSE;
else
{
// millisecond
if( milliseconds > other->milliseconds )
return TRUE;
else
return FALSE;
}
}
}
}
}
}
}
// ------------------------------------------------------------------------------------------------
/** Find a snapshot block info that matches the token passed in */
// ------------------------------------------------------------------------------------------------
GameState::SnapshotBlock *GameState::findBlockInfoByToken( AsciiString token, SnapshotType which )
{
// sanity
if( token.isEmpty() )
return nullptr;
// search for match our list
SnapshotBlock *blockInfo;
SnapshotBlockListIterator it;
for( it = m_snapshotBlockList[which].begin(); it != m_snapshotBlockList[which].end(); ++it )
{
// get info
blockInfo = &(*it);
// check for match
if( blockInfo->blockName == token )
return blockInfo;
}
// not found
return nullptr;
}
// TheSuperHackers @tweak Use the user's default locale instead of the system default to match Windows regional settings.
// This allows regional formats such as Europe (English) to use 24-hour and DD/MM/YYYY formats in-game.
UnicodeString getUnicodeDateBuffer(SYSTEMTIME timeVal)
{
// setup date buffer for local region date format
#define DATE_BUFFER_SIZE 256
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
UnicodeString displayDateBuffer;
if (GetVersionEx(&osvi))
{ //check if we're running Win9x variant since they may need different characters
if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
char dateBuffer[ DATE_BUFFER_SIZE ];
GetDateFormat( LOCALE_USER_DEFAULT,
DATE_SHORTDATE,
&timeVal,
nullptr,
dateBuffer, sizeof(dateBuffer) );
displayDateBuffer.translate(dateBuffer);
return displayDateBuffer;
}
}
wchar_t dateBuffer[ DATE_BUFFER_SIZE ];
GetDateFormatW( LOCALE_USER_DEFAULT,
DATE_SHORTDATE,
&timeVal,
nullptr,
dateBuffer, ARRAY_SIZE(dateBuffer) );
displayDateBuffer.set(dateBuffer);
return displayDateBuffer;
//displayDateBuffer.format( L"%ls", dateBuffer );
}
UnicodeString getUnicodeTimeBuffer(SYSTEMTIME timeVal)
{
// setup time buffer for local region time format
UnicodeString displayTimeBuffer;
OSVERSIONINFO osvi;
osvi.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
if (GetVersionEx(&osvi))
{ //check if we're running Win9x variant since they may need different characters
if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
char timeBuffer[ DATE_BUFFER_SIZE ];
GetTimeFormat( LOCALE_USER_DEFAULT,
TIME_NOSECONDS|TIME_FORCE24HOURFORMAT|TIME_NOTIMEMARKER,
&timeVal,
nullptr,
timeBuffer, sizeof(timeBuffer) );
displayTimeBuffer.translate(timeBuffer);
return displayTimeBuffer;
}
}
// setup time buffer for local region time format
#define TIME_BUFFER_SIZE 256
wchar_t timeBuffer[ TIME_BUFFER_SIZE ];
GetTimeFormatW( LOCALE_USER_DEFAULT,
TIME_NOSECONDS,
&timeVal,
nullptr,
timeBuffer,
ARRAY_SIZE(timeBuffer) );
displayTimeBuffer.set(timeBuffer);
return displayTimeBuffer;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
GameState::GameState()
{
m_availableGames = nullptr;
m_isInLoadGame = FALSE;
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
GameState::~GameState()
{
// clear our snapshot block list
for (Int i=0; i<SNAPSHOT_MAX; ++i)
m_snapshotBlockList[i].clear();
// make certain that the post process list is clean
m_snapshotPostProcessList.clear();
// clear any available game
clearAvailableGames();
}
// ------------------------------------------------------------------------------------------------
/** Init the game state subsystem */
// ------------------------------------------------------------------------------------------------
void GameState::init()
{
// add all the snapshot objects to our list of data blocks for save game files
addSnapshotBlock( GAME_STATE_BLOCK_STRING, TheGameState, SNAPSHOT_SAVELOAD );
addSnapshotBlock( CAMPAIGN_BLOCK_STRING, TheCampaignManager, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_GameStateMap", TheGameStateMap, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_TerrainLogic", TheTerrainLogic, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_TeamFactory", TheTeamFactory, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_Players", ThePlayerList, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_GameLogic", TheGameLogic, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_Radar", TheRadar, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_ScriptEngine", TheScriptEngine, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_SidesList", TheSidesList, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_TacticalView", TheTacticalView, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_GameClient", TheGameClient, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_InGameUI", TheInGameUI, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_Partition", ThePartitionManager, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_ParticleSystem", TheParticleSystemManager, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_TerrainVisual", TheTerrainVisual, SNAPSHOT_SAVELOAD );
addSnapshotBlock( "CHUNK_GhostObject", TheGhostObjectManager, SNAPSHOT_SAVELOAD );
// add all the snapshot objects to our list of data blocks for deep CRCs of logic
addSnapshotBlock( "CHUNK_TeamFactory", TheTeamFactory, SNAPSHOT_DEEPCRC_LOGICONLY );
addSnapshotBlock( "CHUNK_Players", ThePlayerList, SNAPSHOT_DEEPCRC_LOGICONLY );
addSnapshotBlock( "CHUNK_GameLogic", TheGameLogic, SNAPSHOT_DEEPCRC_LOGICONLY );
addSnapshotBlock( "CHUNK_ScriptEngine", TheScriptEngine, SNAPSHOT_DEEPCRC_LOGICONLY );
addSnapshotBlock( "CHUNK_SidesList", TheSidesList, SNAPSHOT_DEEPCRC_LOGICONLY );
addSnapshotBlock( "CHUNK_Partition", ThePartitionManager, SNAPSHOT_DEEPCRC_LOGICONLY );
m_isInLoadGame = FALSE;
}
// ------------------------------------------------------------------------------------------------
/** Reset */
// ------------------------------------------------------------------------------------------------a
void GameState::reset()
{
// clear the post process snapshot list
m_snapshotPostProcessList.clear();
// clear any available game
clearAvailableGames();
m_isInLoadGame = FALSE;
}
// ------------------------------------------------------------------------------------------------
/** Clear any available games entries */
// ------------------------------------------------------------------------------------------------
void GameState::clearAvailableGames()
{
AvailableGameInfo *gameInfo;
while( m_availableGames )
{
gameInfo = m_availableGames->next;
delete m_availableGames;
m_availableGames = gameInfo;
}
}
// ------------------------------------------------------------------------------------------------
/** Add a snapshot and block name pair to the systems used to load and save */
// ------------------------------------------------------------------------------------------------
void GameState::addSnapshotBlock( AsciiString blockName, Snapshot *snapshot, SnapshotType which )
{
// sanity
if( blockName.isEmpty() || snapshot == nullptr )
{
DEBUG_CRASH(( "addSnapshotBlock: Invalid parameters" ));
return;
}
// add to the list
SnapshotBlock blockInfo;
blockInfo.snapshot = snapshot;
blockInfo.blockName = blockName;
m_snapshotBlockList[which].push_back( blockInfo );
}
// ------------------------------------------------------------------------------------------------
/** Given the filename of a save file, find the highest filename number */
// ------------------------------------------------------------------------------------------------
static void findHighFileNumber( AsciiString filename, void *userData )
{
// sanity
if( filename.isEmpty() )
return;
// sanity check for ".sav" at the end of the filename
if( filename.endsWithNoCase( SAVE_GAME_EXTENSION ) == FALSE )
return;
// strip off the extension at the end of the filename
AsciiString nameOnly = filename;
nameOnly.truncateBy( strlen( SAVE_GAME_EXTENSION ) );
// convert filename (which is only numbers) to a number
Int fileNumber = atoi( nameOnly.str() );
//
// atoi will return zero if the string could not be converted, if the filename is
// not literally "00000000.sav" then that means the conversion could not be done so
// we should reject this filename from further processing
//
if( fileNumber == 0 && nameOnly.compare( ZERO_NAME_ONLY ) != 0 )
return;
// compare against the file number we're keeping tally of in the user data parameter
Int *highFileNumber = (Int *)userData;
if( fileNumber >= *highFileNumber )
*highFileNumber = fileNumber;
}
// ------------------------------------------------------------------------------------------------
/** Given the save files on disk, find the "next" filename to use when saving a game */
// ------------------------------------------------------------------------------------------------
AsciiString GameState::findNextSaveFilename( UnicodeString desc )
{
// works, but needs approval from mgmt (srj)
// GS activating for patch
#define COCKBEER_DONT_USE_NORMAL_FILE_NAMES_THANKS
#ifdef USE_NORMAL_FILE_NAMES_THANKS
Int i;
AsciiString adesc;
for (i = 0; i < desc.getLength(); ++i)
{
char c = (char)desc.getCharAt(i);
if (isalnum(c))
adesc.concat(c);
else
adesc.concat('_');
}
for (i = 1; i <= 9999; ++i)
{
AsciiString leaf;
leaf.format("%s_%04d%s", adesc.str(), i, SAVE_GAME_EXTENSION);
AsciiString path = getFilePathInSaveDirectory(leaf);
if( _access( path.str(), 0 ) == -1 )
return leaf; // note that this returns the leaf, not the full path
}
#else
//
// This method has code to support two modes of finding the next filename, one of
// them starts with a filename of 00000000.sav and counts up the number looking for
// a file that doesn't exist and therefore a filename we can use (LOWEST_NUMBER).
// The other method iterates all save files and returns a filename that is one larger
// than the largest filename number encountered (HIGHEST_NUMBER)
//
enum FindNextFileType { LOWEST_NUMBER = 0, HIGHEST_NUMBER = 1 };
FindNextFileType searchType = LOWEST_NUMBER;
if( searchType == HIGHEST_NUMBER )
{
// iterate all the save files in the directory and find the highest file number
Int highFileNumber = -1;
iterateSaveFiles( findHighFileNumber, &highFileNumber );
// check for a filename that is too big (this is unlikely but theoretically possible)
if( highFileNumber + 1 > MAX_SAVE_FILE_NUMBER )
return AsciiString::TheEmptyString;
// construct filename with a number higher than the highest one we found
AsciiString filename;
filename.format( "%08d%s", highFileNumber + 1, SAVE_GAME_EXTENSION );
return filename;
}
else if( searchType == LOWEST_NUMBER )
{
AsciiString filename;
AsciiString fullPath;
Int i = 0;
while( TRUE )
{
// construct filename (########.sav)
filename.format( "%08d%s", i, SAVE_GAME_EXTENSION );
// construct full path to file given the filename
fullPath = getFilePathInSaveDirectory(filename);
// if file does not exist we're all good
if( _access( fullPath.str(), 0 ) == -1 )
return filename;
// test the text filename
i++;
// check for at the max limit (this is highly unlikely but possible)
if( i > MAX_SAVE_FILE_NUMBER )
return AsciiString::TheEmptyString;
}
}
else
{
DEBUG_CRASH(( "GameState::findNextSaveFilename - Unknown file search type '%d'", searchType ));
return AsciiString::TheEmptyString;
}
#endif
// no appropriate filename could be found, return the empty string
return AsciiString::TheEmptyString;
}
// ------------------------------------------------------------------------------------------------
/** Save the current state of the engine in a save file
* NOTE: filename is a *filename only* */
// ------------------------------------------------------------------------------------------------
SaveCode GameState::saveGame( AsciiString filename, UnicodeString desc,
SaveFileType saveType, SnapshotType which )
{
// if there is no filename, this is a new file being created, find an appropriate filename
if( filename.isEmpty() )
filename = findNextSaveFilename( desc );
if( filename.isEmpty() )
{
DEBUG_CRASH(( "GameState::saveGame - Unable to find valid filename for save game" ));
return SC_NO_FILE_AVAILABLE;
}
// make absolutely sure the save directory exists
CreateDirectory( getSaveDirectory().str(), nullptr );
// construct path to file
AsciiString filepath = getFilePathInSaveDirectory(filename);
// save description as current description in the game state
m_gameInfo.description = desc;
// open the save file
XferSave xferSave;
try {
xferSave.open( filepath );
} catch(...) {
// print error message to the user
TheInGameUI->message( "GUI:Error" );
DEBUG_LOG(( "Error opening file '%s'", filepath.str() ));
return SC_ERROR;
}
// save our save file type
SaveGameInfo *gameInfo = getSaveGameInfo();
gameInfo->saveFileType = saveType;
// save our mission map name if applicable
if( saveType == SAVE_FILE_TYPE_MISSION )
gameInfo->missionMapName = TheCampaignManager->getCurrentMap();
else
gameInfo->missionMapName.clear();
// set the pristine map to the current campaign map
// this is now done during startNewGame()
// gameInfo->pristineMapName = TheCampaignManager->getCurrentMap();
// write the save file
try
{
// save file
xferSaveData( &xferSave, which );
}
catch( ... )
{
UnicodeString ufilepath;
ufilepath.translate(filepath);
UnicodeString msg;
msg.format( TheGameText->fetch("GUI:ErrorSavingGame"), ufilepath.str() );
MessageBoxOk(TheGameText->fetch("GUI:Error"), msg, nullptr);
// close the file and get out of here
xferSave.close();
return SC_ERROR;
}
// close the file
xferSave.close();
// print message to the user for game successfully saved
UnicodeString msg = TheGameText->fetch( "GUI:GameSaveComplete" );
TheInGameUI->message( msg );
return SC_OK;
}
// ------------------------------------------------------------------------------------------------
/** A mission save */
// ------------------------------------------------------------------------------------------------
SaveCode GameState::missionSave()
{
// get campaign
Campaign *campaign = TheCampaignManager->getCurrentCampaign();
// get mission #
Int missionNumber = TheCampaignManager->getCurrentMissionNumber() + 1;
// format a string for the mission save description
UnicodeString format = TheGameText->fetch( "GUI:MissionSave" );
UnicodeString desc;
desc.format( format, TheGameText->fetch( campaign->m_campaignNameLabel ).str(), missionNumber );
// do an automatic mission save
return saveGame( "", desc, SAVE_FILE_TYPE_MISSION );
}
// ------------------------------------------------------------------------------------------------
/** Load the save game pointed to by filename */
// ------------------------------------------------------------------------------------------------
SaveCode GameState::loadGame( AvailableGameInfo gameInfo )
{
// sanity check for file
if( doesSaveGameExist( gameInfo.filename ) == FALSE )
return SC_FILE_NOT_FOUND;
// clear game data just like loading from the debug map load screen for mission saves
if( gameInfo.saveGameInfo.saveFileType == SAVE_FILE_TYPE_MISSION )
{
if (TheGameLogic->isInGame())
TheGameLogic->clearGameData( FALSE );
}
//
// clear the save directory of any temporary "scratch pad" maps that were extracted
// from any previously loaded save game files
//
TheGameStateMap->clearScratchPadMaps();
// construct path to file
AsciiString filepath = getFilePathInSaveDirectory(gameInfo.filename);
// open the save file
XferLoad xferLoad;
xferLoad.open( filepath );
// clear out the game engine
TheGameEngine->reset();
// lock creation of new ghost objects
TheGhostObjectManager->saveLockGhostObjects( TRUE );
LatchRestore<Bool> inLoadGame(m_isInLoadGame, TRUE);
// load the save data
Bool error = FALSE;
try
{
// load file
xferSaveData( &xferLoad, SNAPSHOT_SAVELOAD );
}
catch( ... )
{
error = TRUE;
}
// close the file
xferLoad.close();
// un-savelock the ghost objects
TheGhostObjectManager->saveLockGhostObjects( FALSE );
try
{
// do the post-process from a save game load
gameStatePostProcessLoad();
}
catch (...)
{
error = TRUE;
}
// check for error
if( error == TRUE )
{
// clear it out, again
if (TheGameLogic->isInGame())
TheGameLogic->clearGameData( FALSE );
TheGameEngine->reset();
// print error message to the user
UnicodeString ufilepath;
ufilepath.translate(filepath);
UnicodeString msg;
msg.format( TheGameText->fetch("GUI:ErrorLoadingGame"), ufilepath.str() );
MessageBoxOk(TheGameText->fetch("GUI:Error"), msg, nullptr);
return SC_INVALID_DATA; // you can't use a naked "throw" outside of a catch statement!
}
//
// when loading a mission save, we want to do as much normal loading stuff as we
// can cause we don't have any real save game data to load other than the
// game state map info and campaign manager stuff
//
if( getSaveGameInfo()->saveFileType == SAVE_FILE_TYPE_MISSION )
{
InitRandom(0);
TheWritableGlobalData->m_pendingFile = getSaveGameInfo()->missionMapName;
GameMessage *msg = TheMessageStream->appendMessage( GameMessage::MSG_NEW_GAME );
msg->appendIntegerArgument(GAME_SINGLE_PLAYER);
msg->appendIntegerArgument(TheCampaignManager->getGameDifficulty());
msg->appendIntegerArgument(TheCampaignManager->getRankPoints());
// remove the mission save data, we've got all we need and have started the load
SaveGameInfo *gameInfo = getSaveGameInfo();
gameInfo->saveFileType = SAVE_FILE_TYPE_NORMAL;
gameInfo->missionMapName.clear();
}
return SC_OK;
}
//-------------------------------------------------------------------------------------------------
AsciiString GameState::getSaveDirectory() const
{
AsciiString tmp = TheGlobalData->getPath_UserData();
tmp.concat("Save\\");
return tmp;
}
//-------------------------------------------------------------------------------------------------
AsciiString GameState::getFilePathInSaveDirectory(const AsciiString& leaf) const
{
AsciiString tmp = getSaveDirectory();
tmp.concat(leaf);
return tmp;
}
//-------------------------------------------------------------------------------------------------
Bool GameState::isInSaveDirectory(const AsciiString& path) const
{
return FileSystem::isPathInDirectory(path, getSaveDirectory());
}
// ------------------------------------------------------------------------------------------------
AsciiString GameState::getMapLeafName(const AsciiString& in) const
{
const char* p = strrchr(in.str(), '\\');
if (p)
{
//
// p points to the last '\' (if found), however, if a '\' was found there better
// be another character beyond it, otherwise the map filename would actually
// be a *directory* Just move to the first character beyond it so we are looking
// at the name only
//
++p;
DEBUG_ASSERTCRASH( p != nullptr && *p != 0, ("GameState::xfer - Illegal map name encountered") );
return p;
}
else
{
return in;
}
}
// ------------------------------------------------------------------------------------------------
static const char* findLastBackslashInRangeInclusive(const char* start, const char* end)
{
while (end >= start)
{
if (*end == '\\')
return end;
--end;
}
return nullptr;
}
// ------------------------------------------------------------------------------------------------
static AsciiString getMapLeafAndDirName(const AsciiString& in)
{
const char* start = in.str();
const char* end = in.str() + in.getLength() - 1;
const char* p = findLastBackslashInRangeInclusive(start, end);
if (p)
{
const char* p2 = findLastBackslashInRangeInclusive(start, p-1);
if (p2)
{
// we have something like:
// maps\foo\foo.map
// c:\mydocs\c&cdata\maps\foo\foo.map
return p2 + 1;
}
else
{
// we have something like:
// save\foo.map
return in;
}
}
else
{
DEBUG_CRASH(("Illegal map-dir-name... should have at least one backslash"));
return in;
}
}
// ------------------------------------------------------------------------------------------------
static AsciiString removeExtension(const AsciiString& in)
{
if (const char* end = in.reverseFind('.'))
{
const char* begin = in.str();
return AsciiString(begin, end - begin);
}
return in;
}
// ------------------------------------------------------------------------------------------------
const char* PORTABLE_SAVE = "Save\\";
const char* PORTABLE_MAPS = "Maps\\";
const char* PORTABLE_USER_MAPS = "UserData\\Maps\\";
// ------------------------------------------------------------------------------------------------
AsciiString GameState::realMapPathToPortableMapPath(const AsciiString& in) const
{
AsciiString prefix;
if (in.startsWithNoCase(getSaveDirectory()))
{
prefix = PORTABLE_SAVE;
prefix.concat(getMapLeafName(in));
}
else if (in.startsWithNoCase(TheMapCache->getMapDir()))
{
prefix = PORTABLE_MAPS;
prefix.concat(getMapLeafAndDirName(in));
}
else if (in.startsWithNoCase(TheMapCache->getUserMapDir()))
{
prefix = PORTABLE_USER_MAPS;
prefix.concat(getMapLeafAndDirName(in));
}
else
{
DEBUG_CRASH(("Map file was not found in any of the expected directories; this is impossible"));
//throw INI_INVALID_DATA;
// uncaught exceptions crash us. better to just use a bad path.
prefix = in;
}
prefix.toLower();
return prefix;
}
// ------------------------------------------------------------------------------------------------
AsciiString GameState::portableMapPathToRealMapPath(const AsciiString& in) const
{
AsciiString prefix;
// The directory where the real map path should be contained in.
AsciiString containingBasePath;
if (in.startsWithNoCase(PORTABLE_SAVE))
{
// the save dir ends with "\\"
prefix = getSaveDirectory();
containingBasePath = prefix;
prefix.concat(getMapLeafName(in));
}
else if (in.startsWithNoCase(PORTABLE_MAPS))
{
// the map dir DOES NOT end with "\\", must add it
prefix = TheMapCache->getMapDir();
prefix.concat("\\");
containingBasePath = prefix;
prefix.concat(getMapLeafAndDirName(in));
}
else if (in.startsWithNoCase(PORTABLE_USER_MAPS))
{
// the map dir DOES NOT end with "\\", must add it
prefix = TheMapCache->getUserMapDir();
prefix.concat("\\");
containingBasePath = prefix;
prefix.concat(getMapLeafAndDirName(in));
}
else
{
DEBUG_CRASH(("Map file was not found in any of the expected directories; this is impossible"));
// Empty string represents a failure, either caused by an invalid prefix or a relative path leading outside the base path.
return AsciiString::TheEmptyString;
}
if (!FileSystem::isPathInDirectory(prefix, containingBasePath))
{
DEBUG_LOG(("Normalized file path for '%s' was outside the expected base path of '%s'.", prefix.str(), containingBasePath.str()));
return AsciiString::TheEmptyString;
}
prefix.toLower();
return prefix;
}
// ------------------------------------------------------------------------------------------------
/** Does the save game file exist */
// ------------------------------------------------------------------------------------------------
Bool GameState::doesSaveGameExist( AsciiString filename )
{
// construct full path to file
AsciiString filepath = getFilePathInSaveDirectory(filename);
// open file
XferLoad xfer;
try
{
// try to open it
xfer.open( filepath );
}
catch( ... )
{
// unable to open file, it must not be here
return FALSE;
}
// close the file, we don't want to to anything with it right now
xfer.close();
return TRUE;
}
// ------------------------------------------------------------------------------------------------
/** Get save game info from the filename specified */
// ------------------------------------------------------------------------------------------------
void GameState::getSaveGameInfoFromFile( AsciiString filename, SaveGameInfo *saveGameInfo )
{
AsciiString token;
Int blockSize;
Bool done = FALSE;
SnapshotBlock *blockInfo;
// sanity
if( filename.isEmpty() == TRUE || saveGameInfo == nullptr )
{
DEBUG_CRASH(( "GameState::getSaveGameInfoFromFile - Illegal parameters" ));
return;
}
// open file for partial loading
XferLoad xferLoad;
xferLoad.open( filename );
//
// disable post processing cause we're not really doing a load of game data that
// needs post processing and we don't want to keep track of any snapshots we loaded
//
xferLoad.setOptions( XO_NO_POST_PROCESSING );