forked from Kromster80/kam_remake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KM_Saves.pas
579 lines (482 loc) · 14.9 KB
/
KM_Saves.pas
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
unit KM_Saves;
{$I KaM_Remake.inc}
interface
uses
Classes, KromUtils, Math, Windows, SysUtils, SyncObjs,
KM_CommonClasses, KM_Defaults, KM_GameInfo, KM_GameOptions, KM_Minimap, KM_ResTexts, KM_Resource;
type
TSavesSortMethod = (
smByFileNameAsc, smByFileNameDesc,
smByDescriptionAsc, smByDescriptionDesc,
smByTimeAsc, smByTimeDesc,
smByDateAsc, smByDateDesc,
smByPlayerCountAsc, smByPlayerCountDesc,
smByModeAsc, smByModeDesc);
TKMSaveInfo = class;
TSaveEvent = procedure (aSave: TKMSaveInfo) of object;
//Savegame info, most of which is stored in TKMGameInfo structure
TKMSaveInfo = class
private
fPath: string; //TKMGameInfo does not stores paths, because they mean different things for Maps and Saves
fFileName: string; //without extension
fCRC: Cardinal;
fSaveError: string;
fInfo: TKMGameInfo;
fGameOptions: TKMGameOptions;
procedure ScanSave;
public
constructor Create(const aPath, aFileName: String);
destructor Destroy; override;
property Info: TKMGameInfo read fInfo;
property GameOptions: TKMGameOptions read fGameOptions;
property Path: string read fPath;
property FileName: string read fFileName;
property CRC: Cardinal read fCRC;
function IsValid: Boolean;
function IsMultiplayer: Boolean;
function IsReplayValid: Boolean;
function LoadMinimap(aMinimap: TKMMinimap): Boolean;
end;
TTSavesScanner = class(TThread)
private
fMultiplayerPath: Boolean;
fOnSaveAdd: TSaveEvent;
fOnSaveAddDone: TNotifyEvent;
public
constructor Create(aMultiplayerPath: Boolean; aOnSaveAdd: TSaveEvent; aOnSaveAddDone, aOnComplete: TNotifyEvent);
procedure Execute; override;
end;
TKMSavesCollection = class
private
fCount: Word;
fSaves: array of TKMSaveInfo;
fSortMethod: TSavesSortMethod;
CS: TCriticalSection;
fScanner: TTSavesScanner;
fScanning: Boolean;
fScanFinished: Boolean;
fUpdateNeeded: Boolean;
fOnRefresh: TNotifyEvent;
fOnComplete: TNotifyEvent;
procedure Clear;
procedure SaveAdd(aSave: TKMSaveInfo);
procedure SaveAddDone(Sender: TObject);
procedure ScanComplete(Sender: TObject);
procedure DoSort;
function GetSave(aIndex: Integer): TKMSaveInfo;
public
constructor Create(aSortMethod: TSavesSortMethod = smByFileNameDesc);
destructor Destroy; override;
property Count: Word read fCount;
property SavegameInfo[aIndex: Integer]: TKMSaveInfo read GetSave; default;
procedure Lock;
procedure Unlock;
procedure Refresh(aOnRefresh: TNotifyEvent; aMultiplayerPath: Boolean; aOnComplete: TNotifyEvent = nil);
procedure TerminateScan;
procedure Sort(aSortMethod: TSavesSortMethod; aOnSortComplete: TNotifyEvent);
property SortMethod: TSavesSortMethod read fSortMethod; //Read-only because we should not change it while Refreshing
property ScanFinished: Boolean read fScanFinished;
function Contains(aNewName: UnicodeString): Boolean;
procedure DeleteSave(aIndex: Integer);
procedure RenameSave(aIndex: Integer; aName: UnicodeString);
function SavesList: UnicodeString;
procedure UpdateState;
end;
implementation
uses
KM_Utils;
{ TKMSaveInfo }
constructor TKMSaveInfo.Create(const aPath, aFileName: String);
begin
inherited Create;
fPath := aPath;
fFileName := aFileName;
fInfo := TKMGameInfo.Create;
fGameOptions := TKMGameOptions.Create;
//We could postpone this step till info is actually required
//but we do need title and TickCount right away, so it's better just to scan it ASAP
ScanSave;
end;
destructor TKMSaveInfo.Destroy;
begin
fInfo.Free;
fGameOptions.Free;
inherited;
end;
procedure TKMSaveInfo.ScanSave;
var
LoadStream: TKMemoryStream;
begin
if not FileExists(fPath + fFileName + '.sav') then
begin
fSaveError := 'File not exists';
Exit;
end;
fCRC := Adler32CRC(fPath + fFileName + '.sav');
LoadStream := TKMemoryStream.Create; //Read data from file into stream
LoadStream.LoadFromFile(fPath + fFileName + '.sav');
fInfo.Load(LoadStream);
fGameOptions.Load(LoadStream);
fSaveError := fInfo.ParseError;
if (fSaveError = '') and (fInfo.DATCRC <> gRes.GetDATCRC) then
fSaveError := gResTexts[TX_SAVE_UNSUPPORTED_MODS];
if fSaveError <> '' then
fInfo.Title := fSaveError;
LoadStream.Free;
end;
function TKMSaveInfo.LoadMinimap(aMinimap: TKMMinimap): Boolean;
var
LoadStream, LoadMnmStream: TKMemoryStream;
DummyInfo: TKMGameInfo;
DummyOptions: TKMGameOptions;
IsMultiplayer: Boolean;
MinimapFilePath: String;
begin
Result := False;
if not FileExists(fPath + fFileName + '.sav') then Exit;
DummyInfo := TKMGameInfo.Create;
DummyOptions := TKMGameOptions.Create;
LoadStream := TKMemoryStream.Create; //Read data from file into stream
try
LoadStream.LoadFromFile(fPath + fFileName + '.sav');
DummyInfo.Load(LoadStream); //We don't care, we just need to skip past it correctly
DummyOptions.Load(LoadStream); //We don't care, we just need to skip past it correctly
LoadStream.Read(IsMultiplayer);
if not IsMultiplayer then
begin
aMinimap.LoadFromStream(LoadStream);
Result := True;
end else begin
// Lets try to load Minimap for MP save
LoadMnmStream := TKMemoryStream.Create;
try
try
MinimapFilePath := fPath + fFileName + '.' + MP_MINIMAP_SAVE_EXT;
if FileExists(MinimapFilePath) then
begin
LoadMnmStream.LoadFromFile(MinimapFilePath); // try to load minimap from file
aMinimap.LoadFromStream(LoadMnmStream);
Result := True;
end;
except
// Ignore any errors, because MP minimap is optional
end;
finally
LoadMnmStream.Free;
end;
end;
finally
DummyInfo.Free;
DummyOptions.Free;
LoadStream.Free;
end;
end;
function TKMSaveInfo.IsValid: Boolean;
begin
Result := FileExists(fPath + fFileName + '.sav') and (fSaveError = '') and fInfo.IsValid(True);
end;
function TKMSaveInfo.IsMultiplayer: Boolean;
begin
Result := GetFileDirName(fPath + fFileName) = SAVES_MP_FOLDER_NAME;
end;
//Check if replay files exist at location
function TKMSaveInfo.IsReplayValid: Boolean;
begin
Result := FileExists(fPath + fFileName + '.bas') and
FileExists(fPath + fFileName + '.rpl');
end;
{ TKMSavesCollection }
constructor TKMSavesCollection.Create(aSortMethod: TSavesSortMethod = smByFileNameDesc);
begin
inherited Create;
fSortMethod := aSortMethod;
fScanFInished := True;
//CS is used to guard sections of code to allow only one thread at once to access them
//We mostly don't need it, as UI should access Maps only when map events are signaled
//it acts as a safenet mostly
CS := TCriticalSection.Create;
end;
destructor TKMSavesCollection.Destroy;
begin
//Terminate and release the Scanner if we have one working or finished
TerminateScan;
//Release TKMapInfo objects
Clear;
CS.Free;
inherited;
end;
procedure TKMSavesCollection.Lock;
begin
CS.Enter;
end;
procedure TKMSavesCollection.Unlock;
begin
CS.Leave;
end;
procedure TKMSavesCollection.Clear;
var
I: Integer;
begin
Assert(not fScanning, 'Guarding from access to inconsistent data');
for I := 0 to fCount - 1 do
fSaves[i].Free;
fCount := 0;
end;
function TKMSavesCollection.GetSave(aIndex: Integer): TKMSaveInfo;
begin
//No point locking/unlocking here since we return a TObject that could be modified/freed
//by another thread before the caller uses it.
Assert(InRange(aIndex, 0, fCount-1));
Result := fSaves[aIndex];
end;
function TKMSavesCollection.Contains(aNewName: UnicodeString): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to fCount - 1 do
if LowerCase(fSaves[I].FileName) = LowerCase(aNewName) then
begin
Result := True;
Exit;
end;
end;
procedure TKMSavesCollection.DeleteSave(aIndex: Integer);
var
I: Integer;
begin
Lock;
try
Assert(InRange(aIndex, 0, fCount-1));
DeleteFile(fSaves[aIndex].Path + fSaves[aIndex].fFileName + '.sav');
DeleteFile(fSaves[aIndex].Path + fSaves[aIndex].fFileName + '.rpl');
DeleteFile(fSaves[aIndex].Path + fSaves[aIndex].fFileName + '.bas');
fSaves[aIndex].Free;
for I := aIndex to fCount - 2 do
fSaves[I] := fSaves[I+1]; //Move them down
dec(fCount);
SetLength(fSaves, fCount);
finally
Unlock;
end;
end;
procedure TKMSavesCollection.RenameSave(aIndex: Integer; aName: UnicodeString);
var
fileOld, fileNew: UnicodeString;
begin
Lock;
try
fileOld := fSaves[aIndex].Path + fSaves[aIndex].fFileName;
fileNew := fSaves[aIndex].Path + aName;
RenameFile(fileOld + '.sav', fileNew + '.sav');
RenameFile(fileOld + '.rpl', fileNew + '.rpl');
RenameFile(fileOld + '.bas', fileNew + '.bas');
finally
Unlock;
end;
end;
//For private acces, where CS is managed by the caller
procedure TKMSavesCollection.DoSort;
var TempSaves: array of TKMSaveInfo;
//Return True if items should be exchanged
function Compare(A, B: TKMSaveInfo): Boolean;
begin
Result := False; //By default everything remains in place
case fSortMethod of
smByFileNameAsc: Result := CompareText(A.FileName, B.FileName) < 0;
smByFileNameDesc: Result := CompareText(A.FileName, B.FileName) > 0;
smByDescriptionAsc: Result := CompareText(A.Info.GetTitleWithTime, B.Info.GetTitleWithTime) < 0;
smByDescriptionDesc: Result := CompareText(A.Info.GetTitleWithTime, B.Info.GetTitleWithTime) > 0;
smByTimeAsc: Result := A.Info.TickCount < B.Info.TickCount;
smByTimeDesc: Result := A.Info.TickCount > B.Info.TickCount;
smByDateAsc: Result := A.Info.SaveTimestamp > B.Info.SaveTimestamp;
smByDateDesc: Result := A.Info.SaveTimestamp < B.Info.SaveTimestamp;
smByPlayerCountAsc: Result := A.Info.PlayerCount < B.Info.PlayerCount;
smByPlayerCountDesc: Result := A.Info.PlayerCount > B.Info.PlayerCount;
smByModeAsc: Result := A.Info.MissionMode < B.Info.MissionMode;
smByModeDesc: Result := A.Info.MissionMode > B.Info.MissionMode;
end;
end;
procedure MergeSort(left, right: integer);
var middle, i, j, ind1, ind2: integer;
begin
if right <= left then
exit;
middle := (left+right) div 2;
MergeSort(left, middle);
Inc(middle);
MergeSort(middle, right);
ind1 := left;
ind2 := middle;
for i := left to right do
begin
if (ind1 < middle) and ((ind2 > right) or not Compare(fSaves[ind1], fSaves[ind2])) then
begin
TempSaves[i] := fSaves[ind1];
Inc(ind1);
end
else
begin
TempSaves[i] := fSaves[ind2];
Inc(ind2);
end;
end;
for j := left to right do
fSaves[j] := TempSaves[j];
end;
begin
SetLength(TempSaves, Length(fSaves));
MergeSort(Low(fSaves), High(fSaves));
end;
function TKMSavesCollection.SavesList: UnicodeString;
var
I: Integer;
begin
Lock;
try
Result := '';
for I := 0 to fCount - 1 do
Result := Result + fSaves[I].FileName + EolW;
finally
Unlock;
end;
end;
procedure TKMSavesCollection.UpdateState;
begin
if fUpdateNeeded then
begin
if Assigned(fOnRefresh) then
fOnRefresh(Self);
fUpdateNeeded := False;
end;
end;
//For public access
//Apply new Sort within Critical Section, as we could be in the Refresh phase
//note that we need to preserve fScanning flag
procedure TKMSavesCollection.Sort(aSortMethod: TSavesSortMethod; aOnSortComplete: TNotifyEvent);
begin
Lock;
try
if fScanning then
begin
fScanning := False;
fSortMethod := aSortMethod;
DoSort;
if Assigned(aOnSortComplete) then
aOnSortComplete(Self);
fScanning := True;
end
else
begin
fSortMethod := aSortMethod;
DoSort;
if Assigned(aOnSortComplete) then
aOnSortComplete(Self);
end;
finally
Unlock;
end;
end;
procedure TKMSavesCollection.TerminateScan;
begin
if (fScanner <> nil) then
begin
fScanner.Terminate;
fScanner.WaitFor;
fScanner.Free;
fScanner := nil;
fScanning := False;
end;
fUpdateNeeded := False; //If the scan was terminated we should not run fOnRefresh next UpdateState
end;
//Start the refresh of maplist
procedure TKMSavesCollection.Refresh(aOnRefresh: TNotifyEvent; aMultiplayerPath: Boolean; aOnComplete: TNotifyEvent = nil);
begin
//Terminate previous Scanner if two scans were launched consequentialy
TerminateScan;
Clear;
fScanFinished := False;
fOnRefresh := aOnRefresh;
fOnComplete := aOnComplete;
//Scan will launch upon create automatcally
fScanning := True;
fScanner := TTSavesScanner.Create(aMultiplayerPath, SaveAdd, SaveAddDone, ScanComplete);
end;
procedure TKMSavesCollection.SaveAdd(aSave: TKMSaveInfo);
begin
Lock;
try
SetLength(fSaves, fCount + 1);
fSaves[fCount] := aSave;
Inc(fCount);
//Set the scanning to false so we could Sort
fScanning := False;
//Keep the saves sorted
//We signal from Locked section, so everything caused by event can safely access our Saves
DoSort;
fScanning := True;
finally
Unlock;
end;
end;
procedure TKMSavesCollection.SaveAddDone(Sender: TObject);
begin
fUpdateNeeded := True; //Next time the GUI thread calls UpdateState we will run fOnRefresh
end;
//All saves have been scanned
//No need to resort since that was done in last SaveAdd event
procedure TKMSavesCollection.ScanComplete(Sender: TObject);
begin
Lock;
try
fScanning := False;
fScanFinished := True;
if Assigned(fOnComplete) then
fOnComplete(Self);
finally
Unlock;
end;
end;
{ TTSavesScanner }
//aOnSaveAdd - signal that there's new save that should be added
//aOnSaveAddDone - signal that save has been added
//aOnComplete - scan is complete
constructor TTSavesScanner.Create(aMultiplayerPath: Boolean; aOnSaveAdd: TSaveEvent; aOnSaveAddDone, aOnComplete: TNotifyEvent);
begin
//Thread isn't started until all constructors have run to completion
//so Create(False) may be put in front as well
inherited Create(False);
Assert(Assigned(aOnSaveAdd));
fMultiplayerPath := aMultiplayerPath;
fOnSaveAdd := aOnSaveAdd;
fOnSaveAddDone := aOnSaveAddDone;
OnTerminate := aOnComplete;
FreeOnTerminate := False;
end;
procedure TTSavesScanner.Execute;
var
pathToSaves: string;
SearchRec: TSearchRec;
Save: TKMSaveInfo;
begin
if fMultiplayerPath then
pathToSaves := ExeDir + SAVES_MP_FOLDER_NAME + PathDelim
else
pathToSaves := ExeDir + SAVES_FOLDER_NAME + PathDelim;
if not DirectoryExists(pathToSaves) then Exit;
if FindFirst(pathToSaves + '*.sav', faAnyFile, SearchRec) = 0 then
repeat
if (SearchRec.Attr and faDirectory <> faDirectory) //Only files
and (SearchRec.Name <> '.') and (SearchRec.Name <> '..')
then
begin
Save := TKMSaveInfo.Create(pathToSaves, TruncateExt(SearchRec.Name));
if SLOW_SAVE_SCAN then
Sleep(50);
fOnSaveAdd(Save);
fOnSaveAddDone(Self);
end;
until (FindNext(SearchRec) <> 0) or Terminated;
FindClose(SearchRec);
end;
end.