-
-
Notifications
You must be signed in to change notification settings - Fork 452
/
Copy pathCModManager.cpp
401 lines (328 loc) · 11.9 KB
/
CModManager.cpp
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
/*****************************************************************************
*
* PROJECT: Multi Theft Auto
* LICENSE: See LICENSE in the top level directory
* FILE: Client/core/CModManager.cpp
* PURPOSE: Game mod loading manager
*
* Multi Theft Auto is available from https://multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
#include "CModManager.h"
#include "CFilePathTranslator.h"
#include <game/CGame.h>
#define DECLARE_PROFILER_SECTION_CModManager
#include "profiler/SharedUtil.Profiler.h"
using SharedUtil::CalcMTASAPath;
template <>
CModManager* CSingleton<CModManager>::m_pSingleton = NULL;
CModManager::CModManager()
{
// Init
m_hClientDLL = NULL;
m_pClientBase = NULL;
m_bUnloadRequested = false;
// Default mod name defaults to "default"
m_strDefaultModName = "default";
// Load the modlist from the folders in "mta/mods"
InitializeModList(CalcMTASAPath("mods\\"));
}
CModManager::~CModManager()
{
// Unload the current loaded mod (if loaded)
Unload();
// Clear the modlist
Clear();
}
void CModManager::RequestLoad(const char* szModName, const char* szArguments)
{
// Reset an eventual old request (and free our strings)
ClearRequest();
// An unload is now requested
m_bUnloadRequested = true;
// Requested a mod name?
if (szModName)
{
// Store it
m_strRequestedMod = szModName;
// Arguments?
m_strRequestedModArguments = szArguments ? szArguments : "";
}
}
void CModManager::RequestLoadDefault(const char* szArguments)
{
RequestLoad(m_strDefaultModName.c_str(), szArguments);
}
void CModManager::RequestUnload()
{
RequestLoad(NULL, NULL);
CCore::GetSingletonPtr()->OnModUnload();
}
void CModManager::ClearRequest()
{
// Free the old mod name
m_strRequestedMod = "";
// Free the old mod arguments
m_strRequestedModArguments = "";
// No unload requested now
m_bUnloadRequested = false;
}
bool CModManager::IsLoaded()
{
return (m_hClientDLL != NULL);
}
CClientBase* CModManager::Load(const char* szName, const char* szArguments)
{
// Make sure we haven't already loaded a mod
Unload();
CMessageLoopHook::GetSingleton().SetRefreshMsgQueueEnabled(false);
// Get the entry for the given name
std::map<std::string, std::string>::iterator itMod = m_ModDLLFiles.find(szName);
if (itMod == m_ModDLLFiles.end())
{
CCore::GetSingleton().GetConsole()->Printf("Unable to load %s (unknown mod)", szName);
return NULL;
}
// Ensure DllDirectory has not been changed
SString strDllDirectory = GetSystemDllDirectory();
if (CalcMTASAPath("mta").CompareI(strDllDirectory) == false)
{
AddReportLog(3119, SString("DllDirectory wrong: DllDirectory:'%s' Path:'%s'", *strDllDirectory, *CalcMTASAPath("mta")));
SetDllDirectory(CalcMTASAPath("mta"));
}
// Load the library and use the supplied path as an extra place to search for dependencies
m_hClientDLL = LoadLibraryEx(itMod->second.c_str(), NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
if (!m_hClientDLL)
{
DWORD dwError = GetLastError();
char szError[2048];
char* p;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY, NULL, dwError, LANG_NEUTRAL, szError, sizeof(szError), NULL);
// Remove newlines from the error message
p = szError + strlen(szError) - 1;
while (p >= szError && (*p == '\r' || *p == '\n'))
{
*p = '\0';
--p;
}
CCore::GetSingleton().GetConsole()->Printf("Unable to load %s's DLL (reason: %s)", szName, szError);
return NULL;
}
// Get the address of InitClient
typedef CClientBase*(__cdecl pfnClientInitializer)(); /* FIXME: Should probably not be here */
pfnClientInitializer* pClientInitializer = reinterpret_cast<pfnClientInitializer*>(GetProcAddress(m_hClientDLL, "InitClient"));
if (pClientInitializer == NULL)
{
CCore::GetSingleton().GetConsole()->Printf("Unable to load %s's DLL (unknown mod)", szName, GetLastError());
FreeLibrary(m_hClientDLL);
m_hClientDLL = nullptr;
return NULL;
}
// Call InitClient and store the Client interface in m_pClientBase
m_pClientBase = pClientInitializer();
// Call the client base initializer
if (!m_pClientBase || m_pClientBase->ClientInitialize(szArguments, CCore::GetSingletonPtr()) != 0)
{
CCore::GetSingleton().GetConsole()->Printf("Unable to load %s's DLL (unable to init, bad version?)", szName, GetLastError());
FreeLibrary(m_hClientDLL);
m_pClientBase = nullptr;
m_hClientDLL = nullptr;
return NULL;
}
// HACK: make the console input active if its visible
if (CLocalGUI::GetSingleton().IsConsoleVisible())
CLocalGUI::GetSingleton().GetConsole()->ActivateInput();
// Tell chat to start handling input
CLocalGUI::GetSingleton().GetChat()->OnModLoad();
CMessageLoopHook::GetSingleton().SetRefreshMsgQueueEnabled(true);
// Return the interface
return m_pClientBase;
}
void CModManager::Unload()
{
CMessageLoopHook::GetSingleton().SetRefreshMsgQueueEnabled(false);
// If a mod is loaded, we call m_pClientBase->ClientShutdown and then free the library
if (m_hClientDLL != NULL)
{
// Call m_pClientBase->ClientShutdown
if (m_pClientBase)
{
m_pClientBase->ClientShutdown();
m_pClientBase = NULL;
}
// Unregister the commands it had registered
CCore::GetSingleton().GetCommands()->DeleteAll();
// Stop all screen grabs
CGraphics::GetSingleton().GetScreenGrabber()->ClearScreenShotQueue();
// Free the Client DLL
FreeLibrary(m_hClientDLL);
m_hClientDLL = NULL;
// Call the on mod unload func
CCore::GetSingletonPtr()->OnModUnload();
// Reset chatbox status (so it won't prevent further input), and clear it
/*CLocalGUI::GetSingleton ().GetChatBox ()->SetInputEnabled ( false );
CLocalGUI::GetSingleton ().GetChatBox ()->Clear ();*/
CLocalGUI::GetSingleton().GetChat()->SetInputVisible(false);
CLocalGUI::GetSingleton().GetChat()->Clear();
CLocalGUI::GetSingleton().SetChatBoxVisible(true);
// Reset the debugview status
CLocalGUI::GetSingleton().GetDebugView()->SetVisible(false, true);
CLocalGUI::GetSingleton().GetDebugView()->Clear();
CLocalGUI::GetSingleton().SetDebugViewVisible(false);
// NULL the message processor and the unhandled command handler
CCore::GetSingleton().SetClientMessageProcessor(NULL);
CCore::GetSingleton().GetCommands()->SetExecuteHandler(NULL);
// Reset cursor color
CCore::GetSingleton().GetGUI()->ResetCursorColor(255.f, 255.f, 255.f, 1.f);
// Reset the modules
CCore::GetSingleton().GetGame()->Reset();
CCore::GetSingleton().GetMultiplayer()->Reset();
CCore::GetSingleton().GetNetwork()->Reset();
assert(CCore::GetSingleton().GetNetwork()->GetServerBitStreamVersion() == 0);
// Enable the console again
CCore::GetSingleton().GetConsole()->SetEnabled(true);
// Force the mainmenu back
CCore::GetSingleton().SetConnected(false);
CLocalGUI::GetSingleton().GetMainMenu()->SetIsIngame(false);
CLocalGUI::GetSingleton().GetMainMenu()->SetVisible(true, false);
}
CMessageLoopHook::GetSingleton().SetRefreshMsgQueueEnabled(true);
}
void CModManager::DoPulsePreFrame()
{
if (m_pClientBase)
{
m_pClientBase->PreFrameExecutionHandler();
}
}
void CModManager::DoPulsePreHUDRender(bool bDidUnminimize, bool bDidRecreateRenderTargets)
{
if (m_pClientBase)
{
m_pClientBase->PreHUDRenderExecutionHandler(bDidUnminimize, bDidRecreateRenderTargets);
}
}
void CModManager::DoPulsePostFrame()
{
// Load/unload requested?
if (m_bUnloadRequested)
{
// Unload the current mod
Unload();
// Load a new mod?
if (m_strRequestedMod != "")
{
Load(m_strRequestedMod, m_strRequestedModArguments);
}
// Clear the request
ClearRequest();
}
// Pulse the client
if (m_pClientBase)
{
m_pClientBase->PostFrameExecutionHandler();
}
else
{
CCore::GetSingleton().GetNetwork()->DoPulse();
}
// Make sure frame rate limit gets applied
if (m_pClientBase)
CCore::GetSingleton().EnsureFrameRateLimitApplied(); // Catch missed frames
else
CCore::GetSingleton().ApplyFrameRateLimit(88); // Limit when not connected
// Load/unload requested?
if (m_bUnloadRequested)
{
// Unload the current mod
Unload();
// Load a new mod?
if (m_strRequestedMod != "")
{
Load(m_strRequestedMod, m_strRequestedModArguments);
}
// Clear the request
ClearRequest();
}
}
CClientBase* CModManager::GetCurrentMod()
{
return m_pClientBase;
}
void CModManager::RefreshMods()
{
// Clear the list, and load it again
Clear();
InitializeModList(CalcMTASAPath("mods\\"));
}
bool CModManager::TriggerCommand(const char* commandName, size_t commandNameLength, const void* userdata, size_t userdataSize) const
{
if (!m_pClientBase || commandName == nullptr || commandNameLength == 0)
return false;
return m_pClientBase->ProcessCommand(commandName, commandNameLength, userdata, userdataSize);
}
void CModManager::InitializeModList(const char* szModFolderPath)
{
// Variables used to search the mod directory
WIN32_FIND_DATAW FindData;
HANDLE hFind;
// Allocate a string with length of path + 5 letters to store searchpath plus "\*.*"
SString strPathWildchars("%s*.*", szModFolderPath);
// Set the working directory to the MTA folder
CFilePathTranslator filePathTranslator;
filePathTranslator.SetCurrentWorkingDirectory("mta");
// Create a search
hFind = FindFirstFileW(FromUTF8(strPathWildchars), &FindData);
// If we found a first file ...
if (hFind != INVALID_HANDLE_VALUE)
{
// Add it to the list
VerifyAndAddEntry(szModFolderPath, ToUTF8(FindData.cFileName));
// Search until there aren't any files left
while (FindNextFileW(hFind, &FindData) == TRUE)
{
VerifyAndAddEntry(szModFolderPath, ToUTF8(FindData.cFileName));
}
// End the search
FindClose(hFind);
}
// Reset the working directory
filePathTranslator.UnSetCurrentWorkingDirectory();
}
void CModManager::Clear()
{
// Clear the list
m_ModDLLFiles.clear();
}
void CModManager::VerifyAndAddEntry(const char* szModFolderPath, const char* szName)
{
// Name musn't be a . or .. link or we might load unwanted libraries
// Hack: Also skip race for now as it will crash the game!
if ((strcmp(szName, ".") != 0) && (strcmp(szName, "..") != 0) && (stricmp(szName, "race") != 0))
{
// Put together a modpath string and a MTA-relative path to Client(_d).dll
SString strClientDLL("%s%s\\%s", szModFolderPath, szName, CMODMANAGER_CLIENTDLL);
// Attempt to load the primary client DLL
HMODULE hDLL = LoadLibraryEx(strClientDLL, NULL, DONT_RESOLVE_DLL_REFERENCES);
if (hDLL != 0)
{
// Check if InitClient symbol exists
if (GetProcAddress(hDLL, "InitClient") != NULL)
{
// Add it to the list
m_ModDLLFiles[szName] = strClientDLL;
}
else
{
WriteErrorEvent(SString("Unknown mod DLL: %s", szName));
}
// Free the DLL
FreeLibrary(hDLL);
}
else
{
WriteErrorEvent(SString("Invalid mod DLL: %s (reason: %d)", szName, GetLastError()));
}
}
}