-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGameExt.pas
557 lines (453 loc) · 16.5 KB
/
GameExt.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
unit GameExt;
(*
Description: Game extension support. Era entry point.
Author: Alexander Shostak aka Berserker.
*)
(***) interface (***)
uses
Math,
SysUtils,
Windows,
ApiJack,
BinPatching,
CmdApp,
Crypto,
DataLib,
Debug,
DlgMes,
Files,
FilesEx,
Lists,
Log,
StrLib,
Utils,
WinUtils,
EraLog,
EraSettings,
EventMan,
PatchApi,
VfsImport;
type
(* Import *)
TList = DataLib.TList;
TStringList = DataLib.TStrList;
TEvent = EventMan.TEvent;
PEvent = EventMan.PEvent;
const
(* Command line arguments *)
CMDLINE_ARG_MODLIST = 'modlist';
(* Paths *)
MODS_DIR = 'Mods';
DEFAULT_MOD_LIST_FILE = MODS_DIR + '\list.txt';
PLUGINS_PATH = 'EraPlugins';
PATCHES_PATH = 'EraPlugins';
DEBUG_MAPS_DIR = 'DebugMaps';
RUNTIME_DIR = 'Runtime';
RANDOM_MAPS_DIR = 'Random_Maps';
SAVED_GAMES_DIR = 'Games';
DEBUG_EVENT_LIST_PATH = EraSettings.DEBUG_DIR + '\event list.txt';
DEBUG_PATCH_LIST_PATH = EraSettings.DEBUG_DIR + '\patch list.txt';
DEBUG_MOD_LIST_PATH = EraSettings.DEBUG_DIR + '\mod list.txt';
DEBUG_X86_PATCH_LIST_PATH = EraSettings.DEBUG_DIR + '\x86 patches.txt';
CONST_STR = -1;
NO_EVENT_DATA = nil;
ERA_VERSION_STR = '3.9.22';
ERA_VERSION_INT = 3922;
FALLBACK_TO_ORIGINAL = true;
DONT_FALLBACK_TO_ORIGINAL = false;
type
EAssertFailure = class (Exception) end;
PEraEventParams = ^TEraEventParams;
TEraEventParams = array [0..15] of integer;
PMemRedirection = ^TMemRedirection;
TMemRedirection = record
OldAddr: pointer;
BlockSize: integer;
NewAddr: pointer;
end;
var
{O} PluginsList: DataLib.TStrList {OF TDllHandle};
hEra: Windows.THandle;
ProcessStartTime: Windows.TSystemTime;
(* Means for exe structures relocation (enlarging). It's possible to find relocated address by old
structure address in a speed of binary search (log2(N)) *)
{O} MemRedirections: {O} DataLib.TList {OF PMemRedirection};
GameDir: string;
ModsDir: string;
MapDir: string;
function PatchExists (const PatchName: string): boolean; stdcall;
function PluginExists (const PluginName: string): boolean; stdcall;
procedure RedirectMemoryBlock (OldAddr: pointer; BlockSize: integer; NewAddr: pointer); stdcall;
function GetRealAddr (Addr: pointer): pointer; stdcall;
function GetMapDir: string; stdcall;
function GetMapDirName: string;
procedure SetMapDir (const NewMapDir: string);
function GetMapResourcePath (const RelResourcePath: string): string;
function LoadMapRscFile (const RelResourcePath: string; out FileContents: string): boolean;
procedure ClearDebugDir;
procedure GenerateDebugInfo;
procedure GenerateDebugInfoWithoutCleanup;
procedure ReportPluginVersion (const VersionLine: string);
procedure Init (hDll: integer);
(***) implementation (***)
uses Heroes;
const
WoGVersionStrEng: ppchar = pointer($7066E2);
WoGVersionStrRus: ppchar = pointer($7066CF);
var
{On} ReportedPluginVersions: TStrList;
VersionsInfo: string;
procedure InitWoG; ASSEMBLER;
asm
MOV EAX, $70105A
CALL EAX
MOV EAX, $774483
CALL EAX
MOV ECX, $28AAFD0
MOV EAX, $706CC0
CALL EAX
MOV EAX, $701215
CALL EAX
end;
procedure LoadPlugins (const Ext: string);
const
ERM_V_1 = $887668;
var
DllName: string;
DllHandle: integer;
FileExt: string;
ForbiddenPluginPath: string;
begin
with Files.Locate(GameDir + '\' + PLUGINS_PATH + '\*.' + Ext, Files.ONLY_FILES) do begin
while FindNext do begin
if (FoundRec.Rec.Size > 0) then begin
DllName := SysUtils.AnsiLowerCase(FoundName);
FileExt := StrLib.ExtractExt(FoundName);
if (FileExt = 'dll') or (FileExt = 'era') then begin
ForbiddenPluginPath := SysUtils.ChangeFileExt(FoundPath, Utils.IfThen(FileExt = 'dll', '.era', '.dll'));
{!} Assert(
not SysUtils.FileExists(ForbiddenPluginPath),
Format('Failed to load plugin "%s", because "%s" is also present. Duplicate plugin files with different extensions detected.', [FoundPath, ForbiddenPluginPath])
);
// Providing Era handle in v1 for compatibility reasons
PINTEGER(ERM_V_1)^ := hEra;
DllHandle := Windows.LoadLibrary(pchar(FoundPath));
{!} Assert(DllHandle <> 0, 'Failed to load DLL at "' + FoundPath + '"');
PluginsList.AddObj(DllName, Ptr(DllHandle));
end;
end; // .if
end; // .while
end; // .with
end; // .procedure LoadPlugins
procedure ReportPluginVersion (const VersionLine: string);
begin
if ReportedPluginVersions <> nil then begin
ReportedPluginVersions.Add(VersionLine);
end;
end;
function PatchExists (const PatchName: string): boolean;
var
PatchInd: integer;
begin
result := BinPatching.PatchList.Find(PatchName, PatchInd);
end;
function PluginExists (const PluginName: string): boolean;
var
FileSize: integer;
begin
result :=
(Files.GetFileSize(PLUGINS_PATH + '\' + PluginName + '.era', FileSize) and (FileSize > 0)) or
(Files.GetFileSize(PLUGINS_PATH + '\' + PluginName + '.dll', FileSize) and (FileSize > 0));
end;
function CompareMemoryBlocks (Addr1: pointer; Size1: integer; Addr2: pointer; Size2: integer): integer;
begin
{!} Assert(Size1 > 0);
{!} Assert(Size2 > 0);
if (Math.Max(cardinal(Addr1) + cardinal(Size1), cardinal(Addr2) + cardinal(Size2)) - Math.Min(cardinal(Addr1), cardinal(Addr2))) < (cardinal(Size1) + cardinal(Size2)) then begin
result := 0;
end else if cardinal(Addr1) < cardinal(Addr2) then begin
result := -1;
end else begin
result := +1;
end;
end; // .function CompareMemoryBlocks
function FindMemoryRedirection (Addr: pointer; Size: integer; out {i} BlockInd: integer): boolean;
var
{U} Redirection: PMemRedirection;
LeftInd: integer;
RightInd: integer;
ComparisonRes: integer;
begin
{!} Assert(Size >= 0);
Redirection := nil;
// * * * * * //
result := false;
LeftInd := 0;
RightInd := MemRedirections.Count - 1;
while (LeftInd <= RightInd) and not result do begin
BlockInd := LeftInd + (RightInd - LeftInd) div 2;
Redirection := MemRedirections[BlockInd];
ComparisonRes := CompareMemoryBlocks(Addr, Size, Redirection.OldAddr, Redirection.BlockSize);
result := ComparisonRes = 0;
if ComparisonRes < 0 then begin
RightInd := BlockInd - 1;
end else if ComparisonRes > 0 then begin
LeftInd := BlockInd + 1;
end;
end; // .while
if not result then begin
BlockInd := LeftInd;
end;
end; // .function FindMemoryRedirection
procedure RedirectMemoryBlock (OldAddr: pointer; BlockSize: integer; NewAddr: pointer);
var
{U} OldRedirection: PMemRedirection;
{O} NewRedirection: PMemRedirection;
BlockInd: integer;
begin
{!} Assert(OldAddr <> nil);
{!} Assert(BlockSize > 0);
{!} Assert(NewAddr <> nil);
OldRedirection := nil;
NewRedirection := nil;
// * * * * * //
if not FindMemoryRedirection(OldAddr, BlockSize, BlockInd) then begin
New(NewRedirection);
NewRedirection.OldAddr := OldAddr;
NewRedirection.BlockSize := BlockSize;
NewRedirection.NewAddr := NewAddr;
MemRedirections.Insert(NewRedirection, BlockInd); NewRedirection := nil;
end else begin
OldRedirection := MemRedirections[BlockInd];
Debug.FatalError
(
'Cannot redirect block at address $' +
SysUtils.Format('%x', [integer(OldAddr)]) +
' of size ' + SysUtils.IntToStr(BlockSize) +
' to address $' + SysUtils.Format('%x', [integer(NewAddr)]) +
#13#10' because there already exists a redirection from address ' +
SysUtils.Format('%x', [integer(OldRedirection.OldAddr)]) +
' of size ' + SysUtils.IntToStr(OldRedirection.BlockSize) +
' to address $' + SysUtils.Format('%x', [integer(OldRedirection.NewAddr)])
);
end; // .else
// * * * * * //
FreeMem(NewRedirection);
end; // .procedure RedirectMemoryBlock
function GetRealAddr (Addr: pointer): pointer;
var
{U} Redirection: PMemRedirection;
BlockInd: integer;
begin
Redirection := nil;
// * * * * * //
result := Addr;
if FindMemoryRedirection(Addr, sizeof(byte), BlockInd) then begin
Redirection := MemRedirections[BlockInd];
result := Utils.PtrOfs(Redirection.NewAddr, integer(Addr) - integer(Redirection.OldAddr));
end;
end; // .function GetRealAddr
function GetMapDir: string;
begin
if MapDir = '' then begin
if Heroes.IsCampaign then begin
MapDir := GameDir + '\Maps\Resources\' + SysUtils.ChangeFileExt(Heroes.GetCampaignFileName, '') + '\' + SysUtils.IntToStr(Heroes.GetCampaignMapInd + 1);
end else begin
MapDir := GameDir + '\Maps\Resources\' + SysUtils.ChangeFileExt(Heroes.GetMapFileName, '');
end;
end;
result := MapDir;
end;
function GetMapDirName: string;
begin
if Heroes.IsCampaign then begin
result := SysUtils.ChangeFileExt(Heroes.GetCampaignFileName, '') + '\' + SysUtils.IntToStr(Heroes.GetCampaignMapInd + 1);
end else begin
result := SysUtils.ChangeFileExt(Heroes.GetMapFileName, '');
end;
end;
procedure SetMapDir (const NewMapDir: string);
begin
MapDir := NewMapDir;
end;
function GetMapResourcePath (const RelResourcePath: string): string;
begin
result := GetMapDir + '\' + RelResourcePath;
end;
function LoadMapRscFile (const RelResourcePath: string; out FileContents: string): boolean;
begin
result := Files.ReadFileContents(GetMapResourcePath(RelResourcePath), FileContents);
end;
function ClearDebugDirFilter (const FileName, RelPath, FilePath: string; IsDirectory: boolean): boolean;
begin
result := RelPath <> EraSettings.LOG_FILE_NAME;
end;
procedure ClearDebugDir;
begin
Files.ClearDir(GameDir + '\' + EraSettings.DEBUG_DIR, ClearDebugDirFilter);
end;
procedure GenerateDebugInfoWithoutCleanup;
begin
EventMan.GetInstance.Fire('OnGenerateDebugInfo');
end;
procedure GenerateDebugInfo;
begin
ClearDebugDir;
GenerateDebugInfoWithoutCleanup;
end;
procedure DumpEventList;
begin
EventMan.GetInstance.DumpEventList(GameDir + '\' + DEBUG_EVENT_LIST_PATH);
end;
procedure DumpPatchList;
var
i: integer;
begin
BinPatching.PatchList.Sort;
with FilesEx.WriteFormattedOutput(GameDir + '\' + DEBUG_PATCH_LIST_PATH) do begin
Line('> Format: [Patch name] (Patch size)');
EmptyLine;
for i := 0 to BinPatching.PatchList.Count - 1 do begin
Line(Format('%s (%d)', [BinPatching.PatchList[i], integer(BinPatching.PatchList.Values[i])]));
end;
end;
end; // .procedure DumpPatchList
procedure DumpModList;
var
{O} MappingsReport: pchar;
begin
MappingsReport := VfsImport.GetMappingsReportA;
Files.WriteFileContents(MappingsReport, GameDir + '\' + DEBUG_MOD_LIST_PATH);
// * * * * * //
VfsImport.MemFree(MappingsReport);
end;
procedure OnGenerateDebugInfo (Event: PEvent); stdcall;
begin
DumpModList;
DumpEventList;
DumpPatchList;
PatchApi.GetPatcher().SaveDump(pchar(GameDir + '\' + DEBUG_X86_PATCH_LIST_PATH));
end;
(*
Loads and returns list of mods from the highest priority mod to the lowest one. Each mod is described
by existing absolute path to some directory.
Pass CMDLINE_ARG_MODLIST command line argument to set custom path to file with mods list.
*)
function LoadModsList: {O} Lists.TStringList;
var
{O} FileLines: Lists.TStringList;
ModListFilePath: string;
ModListText: string;
ModName: string;
ModPath: string;
ModInd: integer;
i: integer;
begin
FileLines := Lists.NewSimpleStrList();
result := Lists.NewSimpleStrList();
// * * * * * //
result.CaseInsensitive := true;
ModListFilePath := CmdApp.GetArg(CMDLINE_ARG_MODLIST);
if ModListFilePath = '' then begin
ModListFilePath := DEFAULT_MOD_LIST_FILE;
end;
if Files.ReadFileContents(ModListFilePath, ModListText) then begin
FileLines.LoadFromText(ModListText, #13#10);
for i := FileLines.Count - 1 downto 0 do begin
ModName := SysUtils.ExcludeTrailingBackslash( SysUtils.ExtractFileName( SysUtils.Trim(FileLines[i]) ) );
if ModName <> '' then begin
ModPath := SysUtils.ExpandFileName(ModsDir + '\' + ModName);
if not result.Find(ModPath, ModInd) and Files.DirExists(ModPath) then begin
result.Add(ModPath);
end;
end;
end; // .for
end; // .if
// * * * * * //
SysUtils.FreeAndNil(FileLines);
end; // .function LoadModsList
procedure AssignVersionsInfoToCredits;
begin
if ReportedPluginVersions <> nil then begin
VersionsInfo := '{ERA ' + ERA_VERSION_STR + '}'#10'WoG 3.59 (TE 2005)'#10'--------------------------------'#10 + ReportedPluginVersions.ToText(#10);
SysUtils.FreeAndNil(ReportedPluginVersions);
WoGVersionStrEng^ := pchar(VersionsInfo);
WoGVersionStrRus^ := pchar(VersionsInfo);
end;
end;
procedure Init (hDll: integer);
var
ModListFilePath: string;
begin
hEra := hDll;
// Ensure, that Memory manager is thread safe. Hooks and API can be called from multiple threads.
System.IsMultiThread := true;
ModsDir := GameDir + '\' + MODS_DIR;
Files.ForcePath(GameDir + '\' + DEBUG_DIR);
Files.ForcePath(GameDir + '\' + RUNTIME_DIR);
Files.ForcePath(GameDir + '\' + RANDOM_MAPS_DIR);
Files.ForcePath(GameDir + '\' + SAVED_GAMES_DIR);
EraSettings.LoadSettings(GameDir);
EraLog.InstallLoggers(GameDir);
Log.Write('Core', 'CheckVersion', 'Result: ' + ERA_VERSION_STR);
// Allow other units to load necessary settings
EventMan.GetInstance.Fire('$OnLoadEraSettings', NO_EVENT_DATA, 0);
// Run VFS
ModListFilePath := CmdApp.GetArg(CMDLINE_ARG_MODLIST);
if ModListFilePath = '' then begin
ModListFilePath := GameDir + '\' + DEFAULT_MOD_LIST_FILE;
end;
VfsImport.MapModsFromListA(pchar(GameDir), pchar(ModsDir), pchar(ModListFilePath));
Log.Write('Core', 'ReportModList', #13#10 + VfsImport.GetMappingsReportA);
if EraSettings.GetDebugBoolOpt('Debug.DumpVirtualFileSystem', false) then begin
Log.Write('Core', 'DumpVFS', #13#10 + VfsImport.GetDetailedMappingsReportA);
end;
VfsImport.RunVfs(VfsImport.SORT_FIFO);
VfsImport.RunWatcherA(pchar(GameDir + '\Mods'), 250);
EventMan.GetInstance.Fire('OnAfterVfsInit', NO_EVENT_DATA, 0);
LoadPlugins('era');
EventMan.GetInstance.Fire('$OnAfterLoadEraPlugins', NO_EVENT_DATA, 0);
EventMan.GetInstance.Fire('OnBeforeWoG', NO_EVENT_DATA, 0);
BinPatching.ApplyPatches(GameDir + '\' + PATCHES_PATH + '\BeforeWoG');
InitWoG;
LoadPlugins('dll');
EventMan.GetInstance.Fire('OnAfterWoG', NO_EVENT_DATA, 0);
BinPatching.ApplyPatches(GameDir + '\' + PATCHES_PATH + '\AfterWoG');
EventMan.GetInstance.On('OnGenerateDebugInfo', OnGenerateDebugInfo);
EventMan.GetInstance.Fire('OnReportVersion');
AssignVersionsInfoToCredits;
EventMan.GetInstance.Fire('OnAfterStructRelocations');
end; // .procedure Init
procedure AssertHandler (const Mes, FileName: string; LineNumber: integer; Address: pointer);
var
CrashMes: string;
begin
CrashMes := StrLib.BuildStr
(
'Assert violation in file "~FileName~" on line ~Line~.'#13#10'Error at address: $~Address~.'#13#10'Message: "~Message~"',
[
'FileName', FileName,
'Line', SysUtils.IntToStr(LineNumber),
'Address', SysUtils.Format('%x', [integer(Address)]),
'Message', Mes
],
'~'
);
Log.Write('Core', 'AssertHandler', CrashMes);
DlgMes.MsgError(CrashMes);
// Better callstack
pinteger(0)^ := 0;
end; // .procedure AssertHandler
begin
AssertErrorProc := AssertHandler;
PluginsList := DataLib.NewStrList(not Utils.OWNS_ITEMS, DataLib.CASE_INSENSITIVE);
MemRedirections := DataLib.NewList(not Utils.OWNS_ITEMS);
ReportedPluginVersions := DataLib.NewStrList(not Utils.OWNS_ITEMS, DataLib.CASE_INSENSITIVE);
// Find out path to game directory and force it as current directory
GameDir := StrLib.ExtractDirPathW(WinUtils.GetExePath());
{!} Assert(GameDir <> '', 'Failed to obtain game directory path');
SysUtils.SetCurrentDir(GameDir);
Debug.SetDebugMapsDir(GameDir + '\' + DEBUG_MAPS_DIR);
Windows.GetSystemTime(ProcessStartTime);
ApiJack.SetCodeWriter(WriteAtCode);
end.