summaryrefslogblamecommitdiffstats
path: root/game/code/data/gamedatamanager.cpp
blob: 2f83b9c6539e5021400f104b89bfb58ae60dd2e6 (plain) (tree)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285




































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                    
//===========================================================================
// Copyright (C) 2000 Radical Entertainment Ltd.  All rights reserved.
//
// Component:   GameDataManager
//
// Description: Implementation of the GameDataManager class.
//
// Authors:     Tony Chu
//
// Revisions		Date			Author	    Revision
//                  2002/09/16      TChu        Created for SRR2
//
//===========================================================================

//#define PRINT_RAW_DATA // to debug output
 
//===========================================================================
// Includes
//===========================================================================
#include <data/gamedatamanager.h>
#include <data/savegameinfo.h>
#include <data/memcard/memorycardmanager.h>
#include <string.h>

#ifndef WORLD_BUILDER
#include <memory/srrmemory.h>
#else
#define MEMTRACK_PUSH_GROUP(x)
#define MEMTRACK_POP_GROUP(x)
#define GMA_PERSISTENT 0
#define GMA_DEFAULT 0
#define GMA_TEMP 0
#endif

#include <radfile.hpp>
#include <raddebugwatch.hpp>
#include <radtime.hpp>

#ifdef RAD_PS2
    #include <radstring.hpp>
#endif
#ifdef RAD_PS2
const unsigned int MAX_GAME_DATA_SIZE = 8600; // in bytes (since ps2 have different byte packing)
#else
const unsigned int MAX_GAME_DATA_SIZE = 7500; // in bytes
#endif

// Static pointer to instance of singleton.
GameDataManager* GameDataManager::spInstance = NULL;

//===========================================================================
// Local Constants
//===========================================================================

#ifdef RAD_PS2
    const char* SAVED_GAME_TITLE = "The Simpsons:Hit & Run"; // there should be no space betw. "Simpsons:" and "Hit"
                                                             // due to line break inserted there
#endif

#ifdef RAD_XBOX
    // Xbox TCR Requirement!!!
    //
    #define ENABLE_MINIMUM_LOAD_SAVE_TIME
    const unsigned int MINIMUM_LOAD_SAVE_TIME = 2000; // in msec
#else
    #define ENABLE_MINIMUM_LOAD_SAVE_TIME
    const unsigned int MINIMUM_LOAD_SAVE_TIME = 1000; // in msec
#endif

#ifdef RAD_PS2
    const unsigned int MINIMUM_DELETE_TIME = 3000; // in msec
#else
    const unsigned int MINIMUM_DELETE_TIME = 1000; // in msec
#endif

#ifdef RAD_PS2
    /* Filename for PS2 saved games must be prefixed with the following:
     *
     * (BISLPS | BISLPM | BISCPS | BASLUS | BASCUS | BESLES | BESCES)-#####
     *
     * Example: "BASCUS-12345savegame.dat"
     *
     */
  #ifdef PAL
    #define PS2_FILENAME_PREFIX "BESLES-51897"
  #else
    #define PS2_FILENAME_PREFIX "BASLUS-20624"
  #endif
#else
    #define PS2_FILENAME_PREFIX ""
#endif

#ifdef DEBUGWATCH
    const char* WATCHER_NAMESPACE = "Game Data Manager";

    unsigned int g_wCurrentSlot = 0;

    static void LoadGameFromWatcher()
    {
        if( GetMemoryCardManager()->GetCurrentDrive() != NULL )
        {
            GetGameDataManager()->LoadGame( g_wCurrentSlot );
        }
        else
        {
            rTunePrintf( "*** Can't load game! No memory device selected!\n" );
        }
    }

    static void SaveGameFromWatcher()
    {
        if( GetMemoryCardManager()->GetCurrentDrive() != NULL )
        {
            GetGameDataManager()->SaveGame( g_wCurrentSlot );
        }
        else
        {
            rTunePrintf( "*** Can't save game! No memory device selected!\n" );
        }
    }
#endif

//===========================================================================
// Public Member Functions
//===========================================================================

//==============================================================================
// GameDataManager::CreateInstance
//==============================================================================
//
// Description: - Creates the Game Data Manager.
//
// Parameters:	None.
//
// Return:      Pointer to the GameDataManager.
//
// Constraints: This is a singleton so only one instance is allowed.
//
//==============================================================================
GameDataManager* GameDataManager::CreateInstance()
{
MEMTRACK_PUSH_GROUP( "GameDataManager" );
    spInstance = new GameDataManager;
    rAssert( spInstance != NULL );
MEMTRACK_POP_GROUP( "GameDataManager" );

    // create other singletons owned by GameDataManager
    //
    MemoryCardManager* pMemoryCardManager = MemoryCardManager::CreateInstance();
    rAssert( pMemoryCardManager != NULL );

    return spInstance;
}

//==============================================================================
// GameDataManager::DestroyInstance
//==============================================================================
//
// Description: Destroy the Game Data Manager.
//
// Parameters:	None.
//
// Return:      None.
//
//==============================================================================
void GameDataManager::DestroyInstance()
{
    // destroy other singletons owned by GameDataManager
    //
    MemoryCardManager::DestroyInstance();

    rAssert( spInstance != NULL );

    delete spInstance;
    spInstance = NULL;
}

//==============================================================================
// GameDataManager::GetInstance
//==============================================================================
//
// Description: - Access point for the GameDataManager singleton.  
//              - Creates the GameDataManager if needed.
//
// Parameters:	None.
//
// Return:      Pointer to the GameDataManager.
//
// Constraints: This is a singleton so only one instance is allowed.
//
//==============================================================================
GameDataManager* GameDataManager::GetInstance()
{
    rAssert( spInstance != NULL );

    return spInstance;
}

//===========================================================================
// GameDataManager::GameDataManager
//===========================================================================
// Description: 
//
// Constraints:	None.
//
// Parameters:	None.
//
// Return:      
//
//===========================================================================
GameDataManager::GameDataManager()
:   m_numRegisteredGameData( 0 ),
    m_gameDataBuffer( NULL ),
    m_gameDataSize( 0 ),
    m_gameDataLoadCallback( NULL ),
    m_gameDataSaveCallback( NULL ),
    m_gameDataDeleteCallback( NULL ),
#ifdef ENABLE_MINIMUM_LOAD_SAVE_TIME
    m_minimumLoadSaveTime( MINIMUM_LOAD_SAVE_TIME ),
#else
    m_minimumLoadSaveTime( 0 ),
#endif
    m_elapsedOperationTime( 0 ),
    m_isGameLoaded( false ),
    m_saveGameInfoHandler( NULL ),
    m_radFile( NULL ),
    m_currentFileOperation( FILE_OP_NONE )
{
    rAssertMsg( sizeof( GameDataByte ) == 1,
                "WARNING: *** Size of GameDataByte is not 1 byte! Is that OK??" );

    for( unsigned int i = 0; i < sizeof( m_registeredGameData ) / 
                                 sizeof( m_registeredGameData[ 0 ] ); i++ )
    {
        m_registeredGameData[ i ] = NULL;
    }

    // create the save game info handler, and register it before anything else
    //
    m_saveGameInfoHandler = new SaveGameInfo;
    rAssert( m_saveGameInfoHandler );
    this->RegisterGameData( m_saveGameInfoHandler,
                            SaveGameInfo::GetSize(),
                            "Save Game Info" );
}

//===========================================================================
// GameDataManager::~GameDataManager
//===========================================================================
// Description: 
//
// Constraints:	None.
//
// Parameters:	None.
//
// Return:      
//
//===========================================================================
GameDataManager::~GameDataManager()
{
#ifdef DEBUGWATCH
    ::radDbgWatchDelete( &g_wCurrentSlot );
#endif

    if( m_saveGameInfoHandler != NULL )
    {
        delete m_saveGameInfoHandler;
        m_saveGameInfoHandler = NULL;
    }

    for( unsigned int i = 0; i < m_numRegisteredGameData; i++ )
    {
        if( m_registeredGameData[ i ] != NULL )
        {
            delete m_registeredGameData[ i ];
            m_registeredGameData[ i ] = NULL;
        }
    }
}


void
GameDataManager::Init()
{
MEMTRACK_PUSH_GROUP( "GameDataManager" );
    // initialize memory card manager
    //
    GetMemoryCardManager()->Init( this );

#ifdef DEBUGWATCH
    ::radDbgWatchAddUnsignedInt( &g_wCurrentSlot,
                                 "Game Slot",
                                 WATCHER_NAMESPACE,
                                 NULL, NULL, 0, NUM_GAME_SLOTS - 1 );

    ::radDbgWatchAddFunction( "Load Game",
                              (RADDEBUGWATCH_CALLBACK)LoadGameFromWatcher,
                              NULL,
                              WATCHER_NAMESPACE );

    ::radDbgWatchAddFunction( "Save Game",
                              (RADDEBUGWATCH_CALLBACK)SaveGameFromWatcher,
                              NULL,
                              WATCHER_NAMESPACE );
#endif
MEMTRACK_POP_GROUP( "GameDataManager" );
}

void
GameDataManager::Update( unsigned int elapsedTime )
{
    if( m_currentFileOperation != FILE_OP_NONE )
    {
#ifdef ENABLE_MINIMUM_LOAD_SAVE_TIME
        if( m_elapsedOperationTime > m_minimumLoadSaveTime )
        {
            if( m_currentFileOperation == FILE_OP_LOAD_COMPLETED )
            {
                if( m_gameDataLoadCallback != NULL )
                {
                    m_gameDataLoadCallback->OnLoadGameComplete( Success );
                }

                m_currentFileOperation = FILE_OP_NONE;
            }

            if( m_currentFileOperation == FILE_OP_SAVE_COMPLETED )
            {
                if( m_gameDataSaveCallback != NULL )
                {
                    m_gameDataSaveCallback->OnSaveGameComplete( Success );
                }

                m_currentFileOperation = FILE_OP_NONE;
            }
        }
#endif // ENABLE_MINIMUM_LOAD_SAVE_TIME

        if( m_elapsedOperationTime > MINIMUM_DELETE_TIME )
        {
            if( m_currentFileOperation == FILE_OP_DELETE_COMPLETED )
            {
                if( m_gameDataDeleteCallback != NULL )
                {
                    m_gameDataDeleteCallback->OnDeleteGameComplete( m_lastError );
                    m_gameDataDeleteCallback = NULL;
                }

                m_currentFileOperation = FILE_OP_NONE;
            }
        }

        m_elapsedOperationTime += elapsedTime;
    }
}

void
GameDataManager::RegisterGameData( GameDataHandler* gdHandler,
                                   unsigned int numBytes,
                                   const char* name )
{
MEMTRACK_PUSH_GROUP( "GameDataManager" );
    rAssert( gdHandler != NULL );
    rAssert( numBytes >= 0 );

    rAssertMsg( m_numRegisteredGameData < MAX_NUM_GAME_DATA,
                "ERROR: *** Exceeded maximum number of registered game data!" );

#ifndef WORLD_BUILDER
    HeapMgr()->PushHeap( GMA_PERSISTENT );
#endif

    // create new game data
    //
    GameData* newGameData = new GameData;
    rAssert( newGameData );
    newGameData->m_gdHandler = gdHandler;
    newGameData->m_numBytes = numBytes;

#ifdef RAD_DEBUG
    if( name != NULL )
    {
        strncpy( newGameData->m_name, name, sizeof( newGameData->m_name ) );
    }
    else
    {
        strcpy( newGameData->m_name, "" );
    }

    rTunePrintf( ">> Registered Game Data [%d]: %s (%d bytes)\n",
                 m_numRegisteredGameData,
                 newGameData->m_name,
                 newGameData->m_numBytes );
#endif

    // add to registered list of game data
    //
    m_registeredGameData[ m_numRegisteredGameData ] = newGameData;
    m_numRegisteredGameData++;

    // update game data size
    //
    m_gameDataSize += numBytes;

    rReleasePrintf( ">> Total Game Data Size = %d bytes\n", m_gameDataSize );

//    rReleaseAssertMsg( m_gameDataSize <= MAX_GAME_DATA_SIZE,
//                       "ERROR: *** Max Game Data Size Exceeded!" );

#ifndef WORLD_BUILDER
    HeapMgr()->PopHeap( GMA_PERSISTENT );
#endif

MEMTRACK_POP_GROUP( "GameDataManager" );
}

void
GameDataManager::LoadGame( unsigned int slot, GameDataLoadCallback* callback, const char *load_filename )
{
    rAssertMsg( slot < NUM_GAME_SLOTS, "ERROR: *** Invalid game slot!" );

    rReleasePrintf( ">> Loading game from slot %d ... ...\n", slot + 1 );

    m_gameDataLoadCallback = callback;

    // open save game file for reading
    //
    char filename[ radFileFilenameMax + 1 ];
	if (load_filename==NULL) // set up predefined filename
		this->FormatSavedGameFilename( filename,
									sizeof( filename ),
									slot );
	else
		strcpy( filename, load_filename ); // filename is passed in for xbox
    IRadDrive* currentDrive = GetMemoryCardManager()->GetCurrentDrive();
    rAssert( currentDrive );
#ifndef RAD_WIN32
    currentDrive->SaveGameOpenAsync( &m_radFile,
                                     filename,
                                     false,
                                     OpenExisting,
                                     NULL,
                                     m_gameDataSize,
									 true);
#else
    currentDrive->FileOpenAsync( &m_radFile,
                                 filename,
                                 false,
                                 OpenExisting );
#endif // ~RAD_WIN32
    rAssert( m_radFile );
    m_radFile->AddCompletionCallback( this, NULL );

    // allocate temp memory for game data buffer
    //
    rAssert( m_gameDataBuffer == NULL );

#ifndef WORLD_BUILDER
    HeapMgr()->PushHeap( GMA_TEMP );
#endif

    m_gameDataBuffer = new GameDataByte[ m_gameDataSize ];

#ifndef WORLD_BUILDER
    HeapMgr()->PopHeap( GMA_TEMP );
#endif

    rAssert( m_gameDataBuffer != NULL );

    m_currentFileOperation = FILE_OP_OPEN_FOR_READING;
    m_elapsedOperationTime = 0;
}

radFileError GameDataManager::DeleteGame( const char *fileName,
                                          bool async,
                                          GameDataDeleteCallback* callback )
{
	rAssert(m_currentFileOperation == FILE_OP_NONE);
	m_currentFileOperation = FILE_OP_DELETE;
	
	IRadDrive* currentDrive = GetMemoryCardManager()->GetCurrentDrive();

	rAssert( currentDrive );

    m_lastError = Success;

    if( async )
    {
    	currentDrive->DestroyFileAsync( fileName, true );
        currentDrive->AddCompletionCallback( this, NULL );

        rAssert( callback != NULL );
        m_gameDataDeleteCallback = callback;

        m_elapsedOperationTime = 0;
    }
    else
    {
    	currentDrive->DestroyFileSync( fileName, true );
	    m_currentFileOperation = FILE_OP_NONE;
    }

	return m_lastError;
}

void
GameDataManager::SaveGame( unsigned int slot, GameDataSaveCallback* callback )
{
    rAssertMsg( slot < NUM_GAME_SLOTS, "ERROR: *** Invalid game slot!" );

    rReleasePrintf( ">> Saving game to slot %d ... ...\n", slot + 1 );

    m_gameDataSaveCallback = callback;

    // allocate temp memory for game data buffer
    //
    rAssert( m_gameDataBuffer == NULL );
#ifndef WORLD_BUILDER
    HeapMgr()->PushHeap( GMA_TEMP );
#endif

    m_gameDataBuffer = new GameDataByte[ m_gameDataSize ];
#ifndef WORLD_BUILDER
    HeapMgr()->PopHeap( GMA_TEMP );
#endif
    rAssert( m_gameDataBuffer != NULL );

    this->SaveAllData();

    // update saved game title in memcard info before saving
    //
#ifdef RAD_GAMECUBE
    char levelMissionInfo[ 32 ];
    m_saveGameInfoHandler->FormatLevelMissionInfo( levelMissionInfo );

    char savedGameTitle[ 32 ];
    sprintf( savedGameTitle, "Slot %d %s", slot + 1, levelMissionInfo );

    GetMemoryCardManager()->UpdateMemcardInfo( savedGameTitle );
#endif
#ifdef RAD_PS2
    char levelMissionInfo[ 32 ];
    m_saveGameInfoHandler->FormatLevelMissionInfo( levelMissionInfo );

    char savedGameTitle[ 32 ];
    sprintf( savedGameTitle, "%s (%d)", SAVED_GAME_TITLE, slot + 1 );

    GetMemoryCardManager()->UpdateMemcardInfo( savedGameTitle, 13 );
#endif
#ifdef RAD_XBOX
    GetMemoryCardManager()->UpdateMemcardInfo( NULL );
#endif
#ifdef RAD_WIN32
    GetMemoryCardManager()->UpdateMemcardInfo( NULL );
#endif

    // open save game file for writing
    //
    char filename[ radFileFilenameMax + 1 ];
    this->FormatSavedGameFilename( filename,
                                   sizeof( filename ),
                                   slot );

	IRadDrive* currentDrive = GetMemoryCardManager()->GetCurrentDrive();
	rAssert( currentDrive );

#ifdef RAD_XBOX
	m_saveGameInfoHandler->FormatDisplay(filename, sizeof(filename)); // define filename for xbox
#endif

#ifndef RAD_WIN32
    const radMemcardInfo* memcardInfo = GetMemoryCardManager()->GetMemcardInfo();
	bool simpleName = false;
#ifdef RAD_XBOX
	simpleName = true; // set the flag so radcore doesn't process ':' and '/'
#endif

#ifdef RAD_PS2
    radFileOpenFlags fileOpenFlags = OpenAlways;
#else
    radFileOpenFlags fileOpenFlags = CreateAlways;
#endif
    currentDrive->SaveGameOpenAsync( &m_radFile,
                                     filename,
                                     true,
                                     fileOpenFlags,
                                     const_cast<radMemcardInfo*>( memcardInfo ),
                                     m_gameDataSize, simpleName );
#else
    currentDrive->FileOpenAsync( &m_radFile,
                                 filename,
                                 true,
                                 CreateAlways );
#endif // ~RAD_WIN32


    rAssert( m_radFile );
    m_radFile->AddCompletionCallback( this, NULL );

    m_currentFileOperation = FILE_OP_OPEN_FOR_WRITING;
    m_elapsedOperationTime = 0;
}

void
GameDataManager::ResetGame()
{
    // tell all game data handlers to reset their data to defaults
    //
    for( unsigned int i = 0; i < m_numRegisteredGameData; i++ )
    {
        rAssert( m_registeredGameData[ i ] != NULL &&
                 m_registeredGameData[ i ]->m_gdHandler != NULL );

        m_registeredGameData[ i ]->m_gdHandler->ResetData();
    }

    // game is no longer loaded
    //
    m_isGameLoaded = false; 
}

void
GameDataManager::SetMinimumLoadSaveTime( unsigned int minimumTime )
{
    m_minimumLoadSaveTime = minimumTime;
}

void
GameDataManager::RestoreDefaultMinimumLoadSaveTime()
{
#ifdef ENABLE_MINIMUM_LOAD_SAVE_TIME
    m_minimumLoadSaveTime = MINIMUM_LOAD_SAVE_TIME;
#else
    m_minimumLoadSaveTime = 0;
#endif
}

bool
GameDataManager::GetSaveGameInfo( IRadDrive* pDrive, unsigned int slot, 
                                 SaveGameInfo* saveGameInfo,
                                 bool  *file_corrupt_flag)
{
    rAssert( pDrive != NULL );
    rAssert( saveGameInfo != NULL );
	// open save game file for checking if it exists
	//
	char filename[ radFileFilenameMax + 1 ];

#ifdef RAD_XBOX
	// xbox, we get the filename from the drive instead of predefined slot based filename
	IRadDrive::DirectoryInfo dir_info;
    dir_info.m_Type = IRadDrive::DirectoryInfo::IsDone; // initialize first, in case it errs out

 
	pDrive->FindFirstSync("*",&dir_info);

	if (dir_info.m_Type==IRadDrive::DirectoryInfo::IsDone)
		return false;

	for (unsigned int i = 0; i < slot; i++)
	{
        dir_info.m_Type = IRadDrive::DirectoryInfo::IsDone; // initialize first, in case it errs out
		pDrive->FindNextSync(&dir_info);
		if (dir_info.m_Type==IRadDrive::DirectoryInfo::IsDone)
			break;
	}

	if (dir_info.m_Type==IRadDrive::DirectoryInfo::IsDone)
		return false;
	strcpy(filename,dir_info.m_Name);

#else
    this->FormatSavedGameFilename( filename,
                                   sizeof( filename ),
                                   slot );
#endif

    m_lastError = Success; // want to know what is the error from opensync
    if (file_corrupt_flag)
        *file_corrupt_flag = false;


#ifndef RAD_WIN32
	bool simpleName = false;
#ifdef RAD_XBOX
	simpleName = true; // set up flag for xbox so radcore doesn't process ':' '/' character
#endif
    pDrive->SaveGameOpenSync( &m_radFile,
                              filename,
                              false,
                              OpenExisting,
							  0,
							  0,
							  simpleName);
#else

    eFileOperation temp = m_currentFileOperation;
    m_currentFileOperation = FILE_OP_FILE_CHECK;
    pDrive->FileOpenSync( &m_radFile,
                           filename,
                           false,
                           OpenExisting );

    m_currentFileOperation = temp;

#endif // ~RAD_WIN32

    rAssert( m_radFile );
    bool saveGameExists = false;
// since for xbox we know the file is definitely there
// we could get FileNotFound because of old files, just to cut down
// on bug report, let's treat that as corrupt file
#ifdef RAD_XBOX
    if (m_lastError==FileNotFound)
        m_lastError = DataCorrupt;
#endif

    if (m_lastError==DataCorrupt && file_corrupt_flag)
    {
        *file_corrupt_flag = true;
        saveGameExists = true;
    }
    else
    {
        saveGameExists = m_radFile->IsOpen();
        if( saveGameExists )
        {
            // read save game info from file (synchronously)
            //
            unsigned int numBytes = SaveGameInfo::GetSize();

            rAssert( m_gameDataBuffer == NULL );
    #ifndef WORLD_BUILDER
        HeapMgr()->PushHeap( GMA_TEMP );
    #endif
            m_gameDataBuffer = new GameDataByte[ numBytes ];
    #ifndef WORLD_BUILDER
        HeapMgr()->PopHeap( GMA_TEMP );
    #endif
            rAssert( m_gameDataBuffer != NULL );

            m_radFile->ReadSync( m_gameDataBuffer, numBytes );
            saveGameInfo->LoadData( m_gameDataBuffer, numBytes );

            if( m_gameDataBuffer != NULL )
            {
                delete [] m_gameDataBuffer;
                m_gameDataBuffer = NULL;
            }
        }
    }

#ifdef RAD_XBOX
    strcpy(saveGameInfo->m_displayFilename, filename); // use the filename as the display name
#else
    saveGameInfo->FormatDisplay( saveGameInfo->m_displayFilename, sizeof(saveGameInfo->m_displayFilename) );
#endif
 
    m_radFile->Release();
    m_radFile = NULL;

    return saveGameExists;
}

bool
GameDataManager::DoesSaveGameExist( IRadDrive* pDrive, bool check_valid/* = true*/, bool forAllSlots )
{
    bool saveGameExists = false;
    unsigned int numSavedGameExists = 0;

    unsigned int to_check_file = NUM_GAME_SLOTS;
#ifdef RAD_XBOX
    to_check_file = 1; // on xbox since we query the drive for the file,
                       // just check first one
#endif

    // check if at least one saved game file exists on the drive
    //
    for( unsigned int i = 0; i < to_check_file; i++ )
    {
        SaveGameInfo saveGameInfo;
        bool corrupt = false;
        if( this->GetSaveGameInfo( pDrive, i, &saveGameInfo, &corrupt ) )
        {
            if( !check_valid ) // no need to check validity
            {
                saveGameExists = true;

                if( forAllSlots )
                {
                    numSavedGameExists++;
                    continue;
                }

                break;
            }
            // ok, we found a saved game, but let's make sure the saved game
            // info data are valid so we at least know the file size is correct
            //
            else if( !corrupt && saveGameInfo.CheckData() )
            {
                // everything's cool, we have a valid saved game
                //
                saveGameExists = true;

                if( forAllSlots )
                {
                    numSavedGameExists++;
                    continue;
                }

                break;
            }
        }
        else
        {
            // no save game file for current slot
            //
            if( forAllSlots )
            {
                // if checking for save game file exists in all slots, then
                // we've found a slot w/out a save game file, so stop checking
                //
                break;
            }
        }
    }

    if( forAllSlots )
    {
        saveGameExists = (numSavedGameExists == NUM_GAME_SLOTS);
    }

    return saveGameExists;
}

bool
GameDataManager::FindMostRecentSaveGame( IRadDrive* pDrive,
                                         unsigned int& slot,
                                         radDate& timeStamp )
{
    bool saveGameExists = false;

    timeStamp.m_Year = 0;

    // search for most recent save game file on the drive
    //
    for( unsigned int i = 0; i < NUM_GAME_SLOTS; i++ )
    {
        SaveGameInfo saveGameInfo;
        if( this->GetSaveGameInfo( pDrive, i, &saveGameInfo ) )
        {
            if( saveGameInfo.CheckData() )
            {
                // everything's cool, we have a valid saved game
                //
                saveGameExists = true;

                // now let's check if this is the most recent one thus far
                //
                const SaveGameInfoData* pData = saveGameInfo.GetData();
                rAssert( pData != NULL );
                if( SaveGameInfo::CompareTimeStamps( pData->m_timeStamp, timeStamp ) > 0 )
                {
                    memcpy( &timeStamp, &pData->m_timeStamp, sizeof( radDate ) );

                    slot = i; // update most recent saved game slot
                }
            }
        }
    }

    return saveGameExists;
}

void
GameDataManager::FormatSavedGameFilename( char* filename,
                                          unsigned int filenameLength,
                                          unsigned int slot )
{
    rAssert( filename != NULL );
    rAssert( filenameLength >= 32 );

#ifdef RAD_XBOX
    sprintf( filename, "Saved Game (Slot %d)", slot + 1 );
#else
    sprintf( filename, "%sSave%d", PS2_FILENAME_PREFIX, slot + 1 );
#endif
}

void
GameDataManager::OnFileOperationsComplete( void* pUserData )
{
    switch( m_currentFileOperation )
    {
        // cases during loading
        //

        case FILE_OP_OPEN_FOR_READING: // done opening file for reading
        {
            rAssert( m_radFile );
            rAssert( m_radFile->IsOpen() );

            m_radFile->ReadAsync( m_gameDataBuffer,
                                  m_gameDataSize );

            m_radFile->AddCompletionCallback( this, NULL );
            m_currentFileOperation = FILE_OP_READ;

            break;
        }

        case FILE_OP_READ: // done reading data from file
        {
            rAssert( m_radFile );

            m_radFile->Release();
            m_radFile = NULL;

            bool loadOK = this->LoadAllData();
            if( loadOK )
            {
#ifdef ENABLE_MINIMUM_LOAD_SAVE_TIME
                m_currentFileOperation = FILE_OP_LOAD_COMPLETED;
#else
                if( m_gameDataLoadCallback != NULL )
                {
                    m_gameDataLoadCallback->OnLoadGameComplete( Success );
                }

                m_currentFileOperation = FILE_OP_NONE;
#endif
                rReleasePrintf( ">> Load game completed successfully. (%d ms)\n\n",
                                m_elapsedOperationTime );
            }
            else
            {
                if( m_gameDataLoadCallback != NULL )
                {
                    m_gameDataLoadCallback->OnLoadGameComplete( DataCorrupt );
                }

                m_currentFileOperation = FILE_OP_NONE;
            }

            // free up temp memory allocated for game data buffer
            //
            if( m_gameDataBuffer != NULL )
            {
                delete [] m_gameDataBuffer;
                m_gameDataBuffer = NULL;
            }

            break;
        }

        // cases during saving
        //

        case FILE_OP_OPEN_FOR_WRITING: // done opening file for writing
        {
            rAssert( m_radFile );
            rAssert( m_radFile->IsOpen() );

            m_radFile->WriteAsync( m_gameDataBuffer,
                                   m_gameDataSize );

            m_radFile->AddCompletionCallback( this, NULL );
            m_currentFileOperation = FILE_OP_WRITE;

            break;
        }

        case FILE_OP_WRITE: // done writing data to file
        {
            rAssert( m_radFile );

            m_radFile->CommitAsync();

            m_radFile->AddCompletionCallback( this, NULL );
            m_currentFileOperation = FILE_OP_COMMIT;

            break;
        }

        case FILE_OP_COMMIT: // done committing all data writes to file
        {
            rAssert( m_radFile );

            m_radFile->Release();
            m_radFile = NULL;

#ifdef ENABLE_MINIMUM_LOAD_SAVE_TIME
            m_currentFileOperation = FILE_OP_SAVE_COMPLETED;
#else
            if( m_gameDataSaveCallback != NULL )
            {
                m_gameDataSaveCallback->OnSaveGameComplete( Success );
            }

            m_currentFileOperation = FILE_OP_NONE;
#endif
            rReleasePrintf( ">> Save game completed successfully. (%d ms)\n\n",
                            m_elapsedOperationTime );

            // free up temp memory allocated for game data buffer
            //
            if( m_gameDataBuffer != NULL )
            {
                delete [] m_gameDataBuffer;
                m_gameDataBuffer = NULL;
            }

            break;
        }

        default:
        {
            rAssertMsg( m_currentFileOperation == FILE_OP_NONE,
                        "ERROR: *** Invalid file operation!" );

            break;
        }
    }
}

void
GameDataManager::OnDriveOperationsComplete( void* pUserData )
{
    switch( m_currentFileOperation )
    {
        case FILE_OP_DELETE:
        {
            m_currentFileOperation = FILE_OP_DELETE_COMPLETED;

            break;
        }
        default:
        {
            break;
        }
    }
}

bool
GameDataManager::OnDriveError( radFileError error,
                               const char* pDriveName,
                               void* pUserData )
{
    m_lastError = error; // cache error for synchronous call 
    switch( m_currentFileOperation )
    {
        case FILE_OP_OPEN_FOR_READING:
        case FILE_OP_READ:
        {
            rTunePrintf( "*** Error [%d] occurred on drive [%s] during loading!\n",
                         error, pDriveName );

#ifdef RAD_XBOX
            // on xbox we know the filename already
            //  this could happen because of old version file format

            if (m_lastError==FileNotFound)
                m_lastError = DataCorrupt;
#endif

            if( m_gameDataLoadCallback != NULL )
            {
                m_gameDataLoadCallback->OnLoadGameComplete( error );
            }

            if( m_radFile != NULL )
            {
                m_radFile->Release();
                m_radFile = NULL;
            }

            // free up temp memory allocated for game data buffer
            //
            if( m_gameDataBuffer != NULL )
            {
                delete [] m_gameDataBuffer;
                m_gameDataBuffer = NULL;
            }

            m_currentFileOperation = FILE_OP_NONE;

            break;
        }
        case FILE_OP_OPEN_FOR_WRITING:
        case FILE_OP_WRITE:
        case FILE_OP_COMMIT:
        {
            rTunePrintf( "*** Error [%d] occurred on drive [%s] during saving!\n",
                         error, pDriveName );

            if( m_gameDataSaveCallback != NULL )
            {
                m_gameDataSaveCallback->OnSaveGameComplete( error );
            }

            if( m_radFile != NULL )
            {
                m_radFile->Release();
                m_radFile = NULL;
            }

            // free up temp memory allocated for game data buffer
            //
            if( m_gameDataBuffer != NULL )
            {
                delete [] m_gameDataBuffer;
                m_gameDataBuffer = NULL;
            }

            m_currentFileOperation = FILE_OP_NONE;

            break;
        }
        case FILE_OP_DELETE:
        {
            rTunePrintf( "*** Error [%d] occurred on drive [%s] during deleting!\n",
                         error, pDriveName );

            if( m_gameDataDeleteCallback != NULL )
            {
                m_gameDataDeleteCallback->OnDeleteGameComplete( error );
                m_gameDataDeleteCallback = NULL;
            }

            m_currentFileOperation = FILE_OP_NONE;

            break;
        }
        default:
        {
//            rDebugPrintf( "*** WARNING: Unhandled drive error [%d] occurred on drive: %s\n",
//                          error, pDriveName );

            break;
        }
    }

    // we should always return false, since we're always going to prompt
    // the user first before attempting to retry any operation
    //
    return false;
}

bool GameDataManager::IsUsingDrive() const
{
    return m_currentFileOperation != FILE_OP_NONE;
}

//===========================================================================
// Private Member Functions
//===========================================================================

bool
GameDataManager::LoadAllData()
{
    GameDataByte* currentGameDataBuffer = m_gameDataBuffer;

    for( unsigned int i = 0; i < m_numRegisteredGameData; i++ )
    {
        rAssert( m_registeredGameData[ i ] );

        // get number of bytes for current game data
        //
        unsigned int numDataBytes = m_registeredGameData[ i ]->m_numBytes;
        rAssert( numDataBytes >= 0 );

#ifdef PRINT_RAW_DATA
        rDebugPrintf( "Game Data Load (%s): ",
                      m_registeredGameData[ i ]->m_name );

        this->PrintRawData( currentGameDataBuffer, numDataBytes );

        rDebugPrintf( "\n" );
#endif

        // call current game data handler to load data
        //
        rAssert( m_registeredGameData[ i ]->m_gdHandler );
        m_registeredGameData[ i ]->m_gdHandler->LoadData( currentGameDataBuffer,
                                                          numDataBytes );

        if( i == 0 ) // 0 = saved game info data handler
        {
            bool isDataValid = m_saveGameInfoHandler->CheckData();
            if( !isDataValid )
            {
                // saved game info data is not valid, assume file corrupted
                //
                return false;
            }
        }

        // advance reference to current game data buffer
        //
        currentGameDataBuffer += numDataBytes;
    }

    // set flag indicating that a saved game has been loaded
    //
    m_isGameLoaded = true;

    // sanity check
    //
    rAssert( currentGameDataBuffer - m_gameDataBuffer == static_cast<int>( m_gameDataSize ) );

    return true;
}

bool
GameDataManager::SaveAllData()
{
MEMTRACK_PUSH_GROUP( "GameDataManager" );
    GameDataByte* currentGameDataBuffer = m_gameDataBuffer;

    for( unsigned int i = 0; i < m_numRegisteredGameData; i++ )
    {
        rAssert( m_registeredGameData[ i ] );

        // get number of bytes for current game data
        //
        unsigned int numDataBytes = m_registeredGameData[ i ]->m_numBytes;
        rAssert( numDataBytes >= 0 );
/*
        // create temporary buffer for client to write in
        //
        GameDataByte* tempDataBuffer = new( GMA_TEMP ) GameDataByte[ numDataBytes ];
        rAssert( tempDataBuffer );
*/
        // call current game data handler to save data
        //
        rAssert( m_registeredGameData[ i ]->m_gdHandler );
        m_registeredGameData[ i ]->m_gdHandler->SaveData( currentGameDataBuffer,
                                                          numDataBytes );
/*
        // copy data from temporary buffer to current buffer
        //
        memcpy( currentGameDataBuffer, tempDataBuffer, numDataBytes );

        // and destroy temporary data buffer
        //
        if( tempDataBuffer != NULL )
        {
            delete tempDataBuffer;
            tempDataBuffer = NULL;
        }
*/
#ifdef PRINT_RAW_DATA
        rDebugPrintf( "Game Data Save (%s): ",
                      m_registeredGameData[ i ]->m_name );

        this->PrintRawData( currentGameDataBuffer, numDataBytes );

        rDebugPrintf( "\n" );
#endif

        // advance reference to current game data buffer
        //
        currentGameDataBuffer += numDataBytes;
    }

    // sanity check
    //
    rAssert( currentGameDataBuffer - m_gameDataBuffer == static_cast<int>( m_gameDataSize ) );
    MEMTRACK_POP_GROUP("GameDataManager");
    return true;
}

void
GameDataManager::PrintRawData( GameDataByte* dataBuffer,
                               unsigned int numBytes )
{
    rAssert( dataBuffer != NULL );

    for( unsigned int i = 0; i < numBytes; i++ )
    {
        rDebugPrintf( "[ %02X ]", dataBuffer[ i ] );
    }
}