forked from Kromster80/kam_remake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KM_Maps.pas
1122 lines (928 loc) · 31.1 KB
/
KM_Maps.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
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
unit KM_Maps;
{$I KaM_Remake.inc}
interface
uses
Classes, KromUtils, Math, SyncObjs, SysUtils, StrUtils
{$IFDEF FPC} , FileUtil {$ENDIF}
{$IFDEF WDC} , IOUtils {$ENDIF}
, KM_Defaults;
type
TMapsSortMethod = (
smByFavouriteAsc, smByFavouriteDesc,
smByNameAsc, smByNameDesc,
smBySizeAsc, smBySizeDesc,
smByPlayersAsc, smByPlayersDesc,
smByHumanPlayersAsc, smByHumanPlayersDesc,
smByHumanPlayersMPAsc, smByHumanPlayersMPDesc,
smByModeAsc, smByModeDesc);
TKMapInfo = class;
TMapEvent = procedure (aMap: TKMapInfo) of object;
TKMMapInfoAmount = (iaBase, iaExtra);
TKMMapGoalInfo = packed record
Cond: TKMGoalCondition;
Play: TKMHandIndex;
Stat: TKMGoalStatus;
end;
TKMapInfo = class
private
fPath: string;
fFileName: UnicodeString; //without extension
fCRC: Cardinal;
fDatCRC: Cardinal; //Used to speed up scanning
fVersion: AnsiString; //Savegame version, yet unused in maps, they always have actual version
fInfoAmount: TKMMapInfoAmount;
fMapFolder: TMapFolder;
fSizeText: string;
procedure ResetInfo;
procedure LoadTXTInfo;
procedure LoadFromFile(const aPath: string);
procedure SaveToFile(const aPath: string);
function GetSizeText: string;
function DetermineReadmeFilePath: String;
public
MapSizeX, MapSizeY: Integer;
MissionMode: TKMissionMode;
LocCount: Byte;
CanBeHuman: array [0..MAX_HANDS-1] of Boolean;
CanBeAI: array [0..MAX_HANDS-1] of Boolean;
DefaultHuman: TKMHandIndex;
GoalsVictoryCount, GoalsSurviveCount: array [0..MAX_HANDS-1] of Byte;
GoalsVictory: array [0..MAX_HANDS-1] of array of TKMMapGoalInfo;
GoalsSurvive: array [0..MAX_HANDS-1] of array of TKMMapGoalInfo;
Alliances: array [0..MAX_HANDS-1, 0..MAX_HANDS-1] of TKMAllianceType;
FlagColors: array [0..MAX_HANDS-1] of Cardinal;
Author, SmallDesc, BigDesc: UnicodeString;
IsCoop: Boolean; //Some multiplayer missions are defined as coop
IsSpecial: Boolean; //Some missions are defined as special (e.g. tower defence, quest, etc.)
IsFavourite: Boolean;
BlockTeamSelection: Boolean;
BlockPeacetime: Boolean;
BlockFullMapPreview: Boolean;
constructor Create(const aFolder: string; aStrictParsing: Boolean; aMapFolder: TMapFolder); overload;
destructor Destroy; override;
procedure AddGoal(aType: TKMGoalType; aPlayer: TKMHandIndex; aCondition: TKMGoalCondition; aStatus: TKMGoalStatus; aPlayerIndex: TKMHandIndex);
procedure LoadExtra;
property InfoAmount: TKMMapInfoAmount read fInfoAmount;
property Path: string read fPath;
property MapFolder: TMapFolder read fMapFolder;
property FileName: UnicodeString read fFileName;
function FullPath(const aExt: string): string;
function HumanUsableLocations: TKMHandIndexArray;
function AIUsableLocations: TKMHandIndexArray;
property CRC: Cardinal read fCRC;
function LocationName(aIndex: TKMHandIndex): string;
property SizeText: string read GetSizeText;
function IsValid: Boolean;
function HumanPlayerCount: Byte;
function HumanPlayerCountMP: Byte;
function AIOnlyLocCount: Byte;
function FileNameWithoutHash: UnicodeString;
function HasReadme: Boolean;
function ViewReadme: Boolean;
function GetLobbyColor: Cardinal;
function IsFilenameEndMatchHash: Boolean;
end;
TTCustomMapsScanner = class(TThread)
private
fMapFolders: TMapFolderSet;
procedure ProcessMap(aPath: UnicodeString; aFolder: TMapFolder); virtual; abstract;
public
constructor Create(aMapFolders: TMapFolderSet);
procedure Execute; override;
end;
TTMapsScanner = class(TTCustomMapsScanner)
private
fOnMapAdd: TMapEvent;
fOnMapAddDone: TNotifyEvent;
procedure ProcessMap(aPath: UnicodeString; aFolder: TMapFolder); override;
public
constructor Create(aMapFolders: TMapFolderSet; aOnMapAdd: TMapEvent; aOnMapAddDone, aOnComplete: TNotifyEvent);
end;
TTMapsCacheUpdater = class(TTCustomMapsScanner)
private
procedure ProcessMap(aPath: UnicodeString; aFolder: TMapFolder); override;
public
constructor Create(aMapFolders: TMapFolderSet);
end;
TKMapsCollection = class
private
fCount: Integer;
fMaps: array of TKMapInfo;
fMapFolders: TMapFolderSet;
fSortMethod: TMapsSortMethod;
fDoSortWithFavourites: Boolean;
CS: TCriticalSection;
fScanner: TTMapsScanner;
fScanning: Boolean; //Flag if scan is in progress
fUpdateNeeded: Boolean;
fOnRefresh: TNotifyEvent;
fOnComplete: TNotifyEvent;
procedure Clear;
procedure MapAdd(aMap: TKMapInfo);
procedure MapAddDone(Sender: TObject);
procedure ScanComplete(Sender: TObject);
procedure DoSort;
function GetMap(aIndex: Integer): TKMapInfo;
public
constructor Create(aMapFolders: TMapFolderSet; aSortMethod: TMapsSortMethod = smByNameDesc; aDoSortWithFavourites: Boolean = False); overload;
constructor Create(aMapFolder: TMapFolder; aSortMethod: TMapsSortMethod = smByNameDesc; aDoSortWithFavourites: Boolean = False); overload;
destructor Destroy; override;
property Count: Integer read fCount;
property Maps[aIndex: Integer]: TKMapInfo read GetMap; default;
procedure Lock;
procedure Unlock;
class function FullPath(const aName, aExt: string; aMultiplayer: Boolean): string; overload;
class function FullPath(const aName, aExt: string; aMapFolder: TMapFolder): string; overload;
class function FullPath(const aName, aExt: string; aMapFolder: TMapFolder; aCRC: Cardinal): string; overload;
class function GuessMPPath(const aName, aExt: string; aCRC: Cardinal): string;
class procedure GetAllMapPaths(aExeDir: string; aList: TStringList);
procedure Refresh(aOnRefresh: TNotifyEvent; aOnComplete: TNotifyEvent = nil);
procedure TerminateScan;
procedure Sort(aSortMethod: TMapsSortMethod; aOnSortComplete: TNotifyEvent);
property SortMethod: TMapsSortMethod read fSortMethod; //Read-only because we should not change it while Refreshing
procedure DeleteMap(aIndex: Integer);
procedure MoveMap(aIndex: Integer; aName: UnicodeString; aMapFolder: TMapFolder);
procedure UpdateState;
end;
function DetermineMapFolder(aFolderName: UnicodeString; out oMapFolder: TMapFolder): Boolean;
implementation
uses
KM_CommonClasses, KM_MissionScript_Info, KM_ResTexts, KM_Utils, KM_GameApp;
const
//Folder name containing single maps for SP/MP/DL mode
MAP_FOLDER: array [TMapFolder] of string = (MAPS_FOLDER_NAME, MAPS_MP_FOLDER_NAME, MAPS_DL_FOLDER_NAME);
MAP_FOLDER_TYPE_MP: array [Boolean] of TMapFolder = (mfSP, mfMP);
{ TKMapInfo }
constructor TKMapInfo.Create(const aFolder: string; aStrictParsing: Boolean; aMapFolder: TMapFolder);
function GetLIBXCRC(aSearchFile: UnicodeString): Cardinal;
var SearchRec: TSearchRec;
begin
Result := 0;
FindFirst(aSearchFile, faAnyFile - faDirectory, SearchRec);
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
Result := Result xor Adler32CRC(ExtractFilePath(aSearchFile) + SearchRec.Name);
until (FindNext(SearchRec) <> 0);
FindClose(SearchRec);
end;
var
DatFile, MapFile, ScriptFile, TxtFile, LIBXFiles: string;
DatCRC, OthersCRC: Cardinal;
fMissionParser: TMissionParserInfo;
begin
inherited Create;
fPath := ExeDir + MAP_FOLDER[aMapFolder] + PathDelim + aFolder + PathDelim;
fFileName := aFolder;
fMapFolder := aMapFolder;
DatFile := fPath + fFileName + '.dat';
MapFile := fPath + fFileName + '.map';
ScriptFile := fPath + fFileName + '.script'; //Needed for CRC
TxtFile := fPath + fFileName + '.txt'; //Needed for CRC
LIBXFiles := fPath + fFileName + '.*.libx'; //Needed for CRC
fSizeText := ''; //Lazy initialization
if not FileExists(DatFile) then Exit;
//Try loading info from cache, since map scanning is rather slow
LoadFromFile(fPath + fFileName + '.mi'); //Data will be empty if failed
//We will scan map once again if anything has changed
//In SP mode (non-strict) we check DAT CRC and version, that is enough
//In MP mode (strict) we also need exact CRCs to match maps between players
DatCRC := Adler32CRC(DatFile);
//.map file CRC is the slowest, so only calculate it if necessary
OthersCRC := 0; //Supresses incorrect warning by Delphi
if aStrictParsing then
OthersCRC := Adler32CRC(MapFile) xor Adler32CRC(ScriptFile) xor Adler32CRC(TxtFile) xor GetLIBXCRC(LIBXFiles);
//Does the map need to be fully rescanned? (.mi cache is outdated?)
if (fVersion <> GAME_REVISION) or
(fDatCRC <> DatCRC) or //In non-strict mode only DAT CRC matters (SP)
(aStrictParsing and (fCRC <> DatCRC xor OthersCRC)) //In strict mode we check all CRCs (MP)
then
begin
//Calculate OthersCRC if it wasn't calculated before
if not aStrictParsing then
OthersCRC := Adler32CRC(MapFile) xor Adler32CRC(ScriptFile) xor Adler32CRC(TxtFile);
fCRC := DatCRC xor OthersCRC;
fDatCRC := DatCRC;
fVersion := GAME_REVISION;
//First reset everything because e.g. CanBeHuman is assumed false by default and set true when we encounter SET_USER_PLAYER
ResetInfo;
fMissionParser := TMissionParserInfo.Create;
try
//Fill Self properties with MissionParser
fMissionParser.LoadMission(DatFile, Self, pmBase);
finally
fMissionParser.Free;
end;
//Load additional text info
LoadTXTInfo;
IsFavourite := gGameApp.GameSettings.FavouriteMaps.Contains(fCRC);
SaveToFile(fPath + fFileName + '.mi'); //Save new cache file
end;
fInfoAmount := iaBase;
end;
destructor TKMapInfo.Destroy;
begin
inherited;
end;
procedure TKMapInfo.AddGoal(aType: TKMGoalType; aPlayer: TKMHandIndex; aCondition: TKMGoalCondition; aStatus: TKMGoalStatus; aPlayerIndex: TKMHandIndex);
var G: TKMMapGoalInfo;
begin
G.Cond := aCondition;
G.Play := aPlayerIndex;
G.Stat := aStatus;
case aType of
glt_Victory: begin
SetLength(GoalsVictory[aPlayer], GoalsVictoryCount[aPlayer] + 1);
GoalsVictory[aPlayer, GoalsVictoryCount[aPlayer]] := G;
Inc(GoalsVictoryCount[aPlayer]);
end;
glt_Survive: begin
SetLength(GoalsSurvive[aPlayer], GoalsSurviveCount[aPlayer] + 1);
GoalsSurvive[aPlayer, GoalsSurviveCount[aPlayer]] := G;
Inc(GoalsSurviveCount[aPlayer]);
end;
else ;
end;
end;
function TKMapInfo.FullPath(const aExt: string): string;
begin
Result := fPath + fFileName + aExt;
end;
function TKMapInfo.HumanUsableLocations: TKMHandIndexArray;
var
I: Integer;
begin
SetLength(Result, 0);
for I := 0 to MAX_HANDS - 1 do
if CanBeHuman[I] then
begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1] := I;
end;
end;
function TKMapInfo.AIUsableLocations: TKMHandIndexArray;
var
I: Integer;
begin
SetLength(Result, 0);
for I := 0 to MAX_HANDS - 1 do
if CanBeAI[I] then
begin
SetLength(Result, Length(Result)+1);
Result[Length(Result)-1] := I;
end;
end;
function TKMapInfo.LocationName(aIndex: TKMHandIndex): string;
begin
Result := Format(gResTexts[TX_LOBBY_LOCATION_X], [aIndex + 1]);
end;
function TKMapInfo.GetSizeText: string;
begin
if fSizeText = '' then
fSizeText := MapSizeText(MapSizeX, MapSizeY);
Result := fSizeText;
end;
procedure TKMapInfo.LoadTXTInfo;
function LoadDescriptionFromLIBX(aIndex: Integer): UnicodeString;
var MissionTexts: TKMTextLibrarySingle;
begin
if aIndex = -1 then Exit;
MissionTexts := TKMTextLibrarySingle.Create;
MissionTexts.LoadLocale(fPath + fFileName + '.%s.libx');
Result := MissionTexts.Texts[aIndex];
MissionTexts.Free;
end;
var
st, S: string;
ft: TextFile;
begin
//Load additional text info
if FileExists(fPath + fFileName + '.txt') then
begin
AssignFile(ft, fPath + fFileName + '.txt');
FileMode := fmOpenRead;
Reset(ft);
repeat
ReadLn(ft, st);
if SameText(st, 'Author') then Readln(ft, Author);
if SameText(st, 'BigDesc') then Readln(ft, BigDesc);
if SameText(st, 'BigDescLIBX') then
begin
Readln(ft, S);
BigDesc := LoadDescriptionFromLIBX(StrToIntDef(S, -1));
end;
if SameText(st, 'SmallDesc') then ReadLn(ft, SmallDesc);
if SameText(st, 'SmallDescLIBX') then
begin
Readln(ft, S);
SmallDesc := LoadDescriptionFromLIBX(StrToIntDef(S, -1));
end;
if SameText(st, 'SetCoop') then
begin
IsCoop := True;
BlockPeacetime := True;
BlockTeamSelection := True;
BlockFullMapPreview := True;
end;
if SameText(st, 'SetSpecial')then IsSpecial := True;
if SameText(st, 'BlockPeacetime') then BlockPeacetime := True;
if SameText(st, 'BlockTeamSelection') then BlockTeamSelection := True;
if SameText(st, 'BlockFullMapPreview') then BlockFullMapPreview := True;
until(eof(ft));
CloseFile(ft);
end;
end;
//Load additional information for map that is not in main SP list
procedure TKMapInfo.LoadExtra;
var
DatFile: string;
fMissionParser: TMissionParserInfo;
begin
//Do not append Extra info twice
if fInfoAmount = iaExtra then Exit;
//First reset everything because e.g. CanBeHuman is assumed false by default and set true when we encounter SET_USER_PLAYER
ResetInfo;
DatFile := fPath + fFileName + '.dat';
fMissionParser := TMissionParserInfo.Create;
try
//Fill Self properties with MissionParser
fMissionParser.LoadMission(DatFile, Self, pmExtra);
finally
fMissionParser.Free;
end;
if MissionMode = mm_Tactic then
BlockPeacetime := True;
LoadTXTInfo;
fInfoAmount := iaExtra;
end;
procedure TKMapInfo.ResetInfo;
var I, K: Integer;
begin
IsCoop := False;
IsSpecial := False;
MissionMode := mm_Normal;
DefaultHuman := 0;
Author := '';
SmallDesc := '';
BigDesc := '';
for I:=0 to MAX_HANDS-1 do
begin
FlagColors[I] := DefaultTeamColors[I];
CanBeHuman[I] := False;
CanBeAI[I] := False;
GoalsVictoryCount[I] := 0;
SetLength(GoalsVictory[I], 0);
GoalsSurviveCount[I] := 0;
SetLength(GoalsSurvive[I], 0);
for K:=0 to MAX_HANDS-1 do
if I = K then
Alliances[I,K] := at_Ally
else
Alliances[I,K] := at_Enemy;
end;
end;
procedure TKMapInfo.LoadFromFile(const aPath: string);
var
S: TKMemoryStream;
begin
if not FileExists(aPath) then Exit;
S := TKMemoryStream.Create;
S.LoadFromFile(aPath);
//Internal properties
S.Read(fCRC);
S.Read(fDatCRC);
S.ReadA(fVersion);
//Exposed properties
S.Read(MapSizeX);
S.Read(MapSizeY);
S.Read(MissionMode, SizeOf(TKMissionMode));
S.Read(LocCount);
S.ReadW(SmallDesc);
S.Read(IsCoop);
S.Read(IsSpecial);
S.Read(CanBeHuman, SizeOf(CanBeHuman));
S.Read(BlockTeamSelection);
S.Read(BlockPeacetime);
S.Read(BlockFullMapPreview);
IsFavourite := gGameApp.GameSettings.FavouriteMaps.Contains(fCRC);
//Other properties are not saved, they are fast to reload
S.Free;
end;
procedure TKMapInfo.SaveToFile(const aPath: string);
var
S: TKMemoryStream;
begin
S := TKMemoryStream.Create;
try
//Internal properties
S.Write(fCRC);
S.Write(fDatCRC);
S.WriteA(fVersion);
//Exposed properties
S.Write(MapSizeX);
S.Write(MapSizeY);
S.Write(MissionMode, SizeOf(TKMissionMode));
S.Write(LocCount);
S.WriteW(SmallDesc);
S.Write(IsCoop);
S.Write(IsSpecial);
S.Write(CanBeHuman, SizeOf(CanBeHuman));
S.Write(BlockTeamSelection);
S.Write(BlockPeacetime);
S.Write(BlockFullMapPreview);
//Other properties from text file are not saved, they are fast to reload
S.SaveToFile(aPath);
finally
S.Free;
end;
end;
function TKMapInfo.IsValid: Boolean;
begin
Result := (LocCount > 0) and
FileExists(fPath + fFileName + '.dat') and
FileExists(fPath + fFileName + '.map');
end;
function TKMapInfo.HumanPlayerCount: Byte;
var I: Integer;
begin
Result := 0;
for I := 0 to MAX_HANDS - 1 do
if CanBeHuman[I] then
Inc(Result);
end;
function TKMapInfo.HumanPlayerCountMP: Byte;
begin
Result := HumanPlayerCount;
//Enforce MP limit
if Result > MAX_LOBBY_PLAYERS then
Result := MAX_LOBBY_PLAYERS;
end;
function TKMapInfo.AIOnlyLocCount: Byte;
var I: Integer;
begin
Result := 0;
for I := 0 to MAX_HANDS - 1 do
if CanBeAI[I] and not CanBeHuman[I] then
Inc(Result);
end;
//Returns True if map filename ends with this map actual CRC hash.
//Used to check if downloaded map was changed
function TKMapInfo.IsFilenameEndMatchHash: Boolean;
begin
Result := (Length(fFileName) > 9)
and (fFileName[Length(FileName)-8] = '_')
and (IntToHex(fCRC, 8) = RightStr(fFileName, 8));
end;
function TKMapInfo.FileNameWithoutHash: UnicodeString;
begin
if (MapFolder = mfDL) and IsFilenameEndMatchHash then
Result := LeftStr(FileName, Length(FileName)-9)
else
Result := FileName;
end;
function TKMapInfo.DetermineReadmeFilePath: String;
var Path: String;
Locale: AnsiString;
begin
Result := '';
Locale := gGameApp.GameSettings.Locale;
Path := fPath + fFileName + '.' + String(Locale) + '.pdf'; // Try to file with our locale first
if FileExists(Path) then
Result := Path
else
begin
Path := fPath + fFileName + '.' + String(DEFAULT_LOCALE) + '.pdf'; // then with default locale
if FileExists(Path) then
Result := Path
else
begin
Path := fPath + fFileName + '.pdf'; // and finally without any locale
if FileExists(Path) then
Result := Path;
end;
end;
end;
function TKMapInfo.HasReadme: Boolean;
begin
Result := DetermineReadmeFilePath <> '';
end;
function TKMapInfo.ViewReadme: Boolean;
begin
Result := OpenPDF(DetermineReadmeFilePath);
end;
function TKMapInfo.GetLobbyColor: Cardinal;
begin
if fMapFolder = mfDL then
Result := $FFC9BBBB
else
Result := $FF9CF6FF;
end;
{ TKMapsCollection }
constructor TKMapsCollection.Create(aMapFolders: TMapFolderSet; aSortMethod: TMapsSortMethod = smByNameDesc; aDoSortWithFavourites: Boolean = False);
begin
inherited Create;
fMapFolders := aMapFolders;
fSortMethod := aSortMethod;
fDoSortWithFavourites := aDoSortWithFavourites;
//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 mostly acts as a safenet
CS := TCriticalSection.Create;
end;
constructor TKMapsCollection.Create(aMapFolder: TMapFolder; aSortMethod: TMapsSortMethod = smByNameDesc; aDoSortWithFavourites: Boolean = False);
begin
Create([aMapFolder], aSortMethod, aDoSortWithFavourites);
end;
destructor TKMapsCollection.Destroy;
begin
//Terminate and release the Scanner if we have one working or finished
TerminateScan;
//Release TKMapInfo objects
Clear;
CS.Free;
inherited;
end;
function TKMapsCollection.GetMap(aIndex: Integer): TKMapInfo;
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 := fMaps[aIndex];
end;
class function TKMapsCollection.GuessMPPath(const aName, aExt: string; aCRC: Cardinal): string;
var S: UnicodeString;
begin
S := aName + '_' + IntToHex(aCRC, 8);
Result := MAP_FOLDER[mfDL] + PathDelim + S + PathDelim + S + aExt;
if not FileExists(ExeDir + Result) then
Result := MAP_FOLDER[mfMP] + PathDelim + aName + PathDelim + aName + aExt;
end;
procedure TKMapsCollection.Lock;
begin
CS.Enter;
end;
procedure TKMapsCollection.Unlock;
begin
CS.Leave;
end;
procedure TKMapsCollection.Clear;
var
I: Integer;
begin
Assert(not fScanning, 'Guarding from access to inconsistent data');
for I := 0 to fCount - 1 do
FreeAndNil(fMaps[I]);
fCount := 0;
end;
procedure TKMapsCollection.UpdateState;
begin
if fUpdateNeeded then
begin
if Assigned(fOnRefresh) then
fOnRefresh(Self);
fUpdateNeeded := False;
end;
end;
procedure TKMapsCollection.DeleteMap(aIndex: Integer);
var
I: Integer;
begin
Lock;
try
Assert(InRange(aIndex, 0, fCount - 1));
{$IFDEF FPC} DeleteDirectory(fMaps[aIndex].Path, False); {$ENDIF}
{$IFDEF WDC} TDirectory.Delete(fMaps[aIndex].Path, True); {$ENDIF}
fMaps[aIndex].Free;
for I := aIndex to fCount - 2 do
fMaps[I] := fMaps[I + 1];
Dec(fCount);
SetLength(fMaps, fCount);
finally
Unlock;
end;
end;
procedure TKMapsCollection.MoveMap(aIndex: Integer; aName: UnicodeString; aMapFolder: TMapFolder);
var
I: Integer;
Dest, RenamedFile: UnicodeString;
SearchRec: TSearchRec;
begin
if Trim(aName) = '' then Exit;
Lock;
try
Dest := ExeDir + MAP_FOLDER[aMapFolder] + PathDelim + aName + PathDelim;
Assert(fMaps[aIndex].Path <> Dest);
Assert(InRange(aIndex, 0, fCount - 1));
//Remove existing dest directory
if DirectoryExists(Dest) then
begin
{$IFDEF FPC} DeleteDirectory(Dest, False); {$ENDIF}
{$IFDEF WDC} TDirectory.Delete(Dest, True); {$ENDIF}
end;
//Move directory to dest
{$IFDEF FPC} RenameFile(fMaps[aIndex].Path, Dest); {$ENDIF}
{$IFDEF WDC} TDirectory.Move(fMaps[aIndex].Path, Dest); {$ENDIF}
//Rename all the files in dest
FindFirst(Dest + fMaps[aIndex].FileName + '*', faAnyFile - faDirectory, SearchRec);
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..')
and (Length(SearchRec.Name) > Length(fMaps[aIndex].FileName)) then
begin
RenamedFile := Dest + aName + RightStr(SearchRec.Name, Length(SearchRec.Name) - Length(fMaps[aIndex].FileName));
if not FileExists(RenamedFile) and (Dest + SearchRec.Name <> RenamedFile) then
{$IFDEF FPC} RenameFile(Dest + SearchRec.Name, RenamedFile); {$ENDIF}
{$IFDEF WDC} TFile.Move(Dest + SearchRec.Name, RenamedFile); {$ENDIF}
end;
until (FindNext(SearchRec) <> 0);
FindClose(SearchRec);
//Remove the map from our list
fMaps[aIndex].Free;
for I := aIndex to fCount - 2 do
fMaps[I] := fMaps[I + 1];
Dec(fCount);
SetLength(fMaps, fCount);
finally
Unlock;
end;
end;
//For private access, where CS is managed by the caller
procedure TKMapsCollection.DoSort;
var TempMaps: array of TKMapInfo;
//Return True if items should be exchanged
function Compare(A, B: TKMapInfo): Boolean;
begin
Result := False; //By default everything remains in place
case fSortMethod of
smByFavouriteAsc: Result := A.IsFavourite and not B.IsFavourite;
smByFavouriteDesc: Result := not A.IsFavourite and B.IsFavourite;
smByNameAsc: Result := CompareText(A.FileName, B.FileName) < 0;
smByNameDesc: Result := CompareText(A.FileName, B.FileName) > 0;
smBySizeAsc: Result := MapSizeIndex(A.MapSizeX, A.MapSizeY) < MapSizeIndex(B.MapSizeX, B.MapSizeY);
smBySizeDesc: Result := MapSizeIndex(A.MapSizeX, A.MapSizeY) > MapSizeIndex(B.MapSizeX, B.MapSizeY);
smByPlayersAsc: Result := A.LocCount < B.LocCount;
smByPlayersDesc: Result := A.LocCount > B.LocCount;
smByHumanPlayersAsc: Result := A.HumanPlayerCount < B.HumanPlayerCount;
smByHumanPlayersDesc: Result := A.HumanPlayerCount > B.HumanPlayerCount;
smByHumanPlayersMPAsc: Result := A.HumanPlayerCountMP < B.HumanPlayerCountMP;
smByHumanPlayersMPDesc: Result := A.HumanPlayerCountMP > B.HumanPlayerCountMP;
smByModeAsc: Result := A.MissionMode < B.MissionMode;
smByModeDesc: Result := A.MissionMode > B.MissionMode;
end;
if fDoSortWithFavourites and not (fSortMethod in [smByFavouriteAsc, smByFavouriteDesc]) then
begin
if A.IsFavourite and not B.IsFavourite then
Result := False
else if not A.IsFavourite and B.IsFavourite then
Result := True
end;
end;
procedure MergeSort(aLeft, aRight: Integer);
var Middle, I, J, Ind1, Ind2: integer;
begin
if aRight <= aLeft then
exit;
Middle := (aLeft+aRight) div 2;
MergeSort(aLeft, Middle);
Inc(Middle);
MergeSort(Middle, aRight);
Ind1 := aLeft;
Ind2 := Middle;
for I := aLeft to aRight do
begin
if (Ind1 < Middle) and ((Ind2 > aRight) or not Compare(fMaps[Ind1], fMaps[Ind2])) then
begin
TempMaps[I] := fMaps[Ind1];
Inc(Ind1);
end
else
begin
TempMaps[I] := fMaps[Ind2];
Inc(Ind2);
end;
end;
for J := aLeft to aRight do
fMaps[J] := TempMaps[J];
end;
begin
SetLength(TempMaps, Length(fMaps));
MergeSort(Low(fMaps), High(fMaps));
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 TKMapsCollection.Sort(aSortMethod: TMapsSortMethod; 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 TKMapsCollection.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 TKMapsCollection.Refresh(aOnRefresh: TNotifyEvent; aOnComplete: TNotifyEvent = nil);
begin
//Terminate previous Scanner if two scans were launched consequentialy
TerminateScan;
Clear;
fOnRefresh := aOnRefresh;
fOnComplete := aOnComplete;
//Scan will launch upon create automatcally
fScanning := True;
fScanner := TTMapsScanner.Create(fMapFolders, MapAdd, MapAddDone, ScanComplete);
end;
procedure TKMapsCollection.MapAdd(aMap: TKMapInfo);
begin
Lock;
try
SetLength(fMaps, fCount + 1);
fMaps[fCount] := aMap;
Inc(fCount);
//Set the scanning to false so we could Sort
fScanning := False;
//Keep the maps sorted
//We signal from Locked section, so everything caused by event can safely access our Maps
DoSort;
fScanning := True;
finally
Unlock;
end;
end;
procedure TKMapsCollection.MapAddDone(Sender: TObject);
begin
fUpdateNeeded := True; //Next time the GUI thread calls UpdateState we will run fOnRefresh
end;
//All maps have been scanned
//No need to resort since that was done in last MapAdd event
procedure TKMapsCollection.ScanComplete(Sender: TObject);
begin
Lock;
try
fScanning := False;
if Assigned(fOnComplete) then
fOnComplete(Self);
finally
Unlock;
end;
end;
class function TKMapsCollection.FullPath(const aName, aExt: string; aMultiplayer: Boolean): string;
begin
Result := FullPath(aName, aExt, MAP_FOLDER_TYPE_MP[aMultiplayer]);
end;
class function TKMapsCollection.FullPath(const aName, aExt: string; aMapFolder: TMapFolder): string;
begin
Result := ExeDir + MAP_FOLDER[aMapFolder] + PathDelim + aName + PathDelim + aName + aExt;
end;
class function TKMapsCollection.FullPath(const aName, aExt: string; aMapFolder: TMapFolder; aCRC: Cardinal): string;
var S: UnicodeString;
begin
S := aName;
if aMapFolder = mfDL then
S := S + '_' + IntToHex(Integer(aCRC), 8);
Result := FullPath(S, aExt, aMapFolder);
end;
class procedure TKMapsCollection.GetAllMapPaths(aExeDir: string; aList: TStringList);
var
I: Integer;
SearchRec: TSearchRec;
PathToMaps: TStringList;
begin
aList.Clear;
PathToMaps := TStringList.Create;
try
PathToMaps.Add(aExeDir + MAPS_FOLDER_NAME + PathDelim);
PathToMaps.Add(aExeDir + MAPS_MP_FOLDER_NAME + PathDelim);
PathToMaps.Add(aExeDir + TUTORIALS_FOLDER_NAME + PathDelim);
//Include all campaigns maps
FindFirst(aExeDir + CAMPAIGNS_FOLDER_NAME + PathDelim + '*', faDirectory, SearchRec);
repeat
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
PathToMaps.Add(aExeDir + CAMPAIGNS_FOLDER_NAME + PathDelim + SearchRec.Name + PathDelim);
until (FindNext(SearchRec) <> 0);
FindClose(SearchRec);
for I := 0 to PathToMaps.Count - 1 do
if DirectoryExists(PathToMaps[I]) then