/
GameManager.cpp
603 lines (489 loc) · 17.1 KB
/
GameManager.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
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
#include "GameManager.h"
#include "i18n.h"
#include "iregistry.h"
#include "itextstream.h"
#include "ifiletypes.h"
#include "ifilesystem.h"
#include "settings/PreferenceSystem.h"
#include "ui/prefdialog/PrefDialog.h"
#include "ui/prefdialog/GameSetupDialog.h"
#include "os/file.h"
#include "os/dir.h"
#include "os/path.h"
#include "os/fs.h"
#include "string/convert.h"
#include "string/replace.h"
#include "string/predicate.h"
#include "GameFileLoader.h"
#include "wxutil/dialog/MessageBox.h"
#include "Win32Registry.h"
#include "modulesystem/StaticModule.h"
#include "modulesystem/ApplicationContextImpl.h"
#include <sigc++/bind.h>
#include <iostream>
namespace game
{
namespace {
const std::string RKEY_GAME_TYPE = "user/game/type";
const std::string RKEY_FS_GAME = "user/game/fs_game";
const std::string RKEY_FS_GAME_BASE = "user/game/fs_game_base";
const char* const GKEY_PREFAB_FOLDER = "/mapFormat/prefabFolder";
const char* const GKEY_MAPS_FOLDER = "/mapFormat/mapFolder";
}
Manager::Manager() :
_enginePathInitialised(false)
{}
const std::string& Manager::getName() const {
static std::string _name(MODULE_GAMEMANAGER);
return _name;
}
const StringSet& Manager::getDependencies() const {
static StringSet _dependencies;
if (_dependencies.empty()) {
_dependencies.insert(MODULE_XMLREGISTRY);
_dependencies.insert(MODULE_PREFERENCESYSTEM);
_dependencies.insert(MODULE_FILETYPES);
}
return _dependencies;
}
void Manager::initialiseModule(const ApplicationContext& ctx)
{
initialise(ctx.getRuntimeDataPath());
initEnginePath();
}
const std::string& Manager::getFSGame() const {
return _fsGame;
}
const std::string& Manager::getFSGameBase() const {
return _fsGameBase;
}
const std::string& Manager::getModPath() const {
// Return the fs_game path if available
return (!_modPath.empty()) ? _modPath : _modBasePath;
}
const std::string& Manager::getModBasePath() const
{
return _modBasePath;
}
IGamePtr Manager::currentGame()
{
if (_currentGameName.empty())
{
// No game type selected, bail out, the program will crash anyway on module load
wxutil::Messagebox::ShowFatalError(_("GameManager: No game type selected, can't continue."), NULL);
}
return _games[_currentGameName];
}
const Manager::GameList& Manager::getSortedGameList()
{
return _sortedGames;
}
void Manager::constructPreferences()
{
IPreferencePage& page = GetPreferenceSystem().getPage(_("Game"));
ComboBoxValueList gameList;
for (const IGamePtr& game : _sortedGames)
{
gameList.push_back(game->getKeyValue("name"));
}
page.appendCombo(_("Select a Game:"), RKEY_GAME_TYPE, gameList, true);
page.appendPathEntry(_("Engine Path"), RKEY_ENGINE_PATH, true);
page.appendEntry(_("Mod (fs_game)"), RKEY_FS_GAME);
page.appendEntry(_("Mod Base (fs_game_base, optional)"), RKEY_FS_GAME_BASE);
}
void Manager::initialise(const std::string& appPath)
{
// Scan the <applicationpath>/games folder for .game files
loadGameFiles(appPath);
if (_games.empty())
{
// No game types available, bail out, the program would crash anyway on
// module load
wxutil::Messagebox::ShowFatalError(
_("GameManager: No valid game files found, can't continue."), NULL
);
}
// Add the settings widgets to the Preference Dialog, we might need it
constructPreferences();
// Find the user's selected game from the XML registry, and attempt to find
// it in the set of available games.
std::string gameType = GlobalRegistry().get(RKEY_GAME_TYPE);
GameMap::iterator i = _games.find(gameType);
if (gameType.empty() || i == _games.end())
{
// We have at least one game type available, select the first
// Store the name of the only game into the Registry
rMessage() << "No game selected, will choose the highest ranked one." << std::endl;
if (_sortedGames.empty())
{
wxutil::Messagebox::ShowFatalError(
"GameManager: Sorted game list is empty, can't continue.", nullptr
);
}
GlobalRegistry().set(RKEY_GAME_TYPE, _sortedGames.front()->getKeyValue("name"));
}
// Load the value from the registry, there should be one selected at this point
_currentGameName = GlobalRegistry().get(RKEY_GAME_TYPE);
// The game type should be selected now
if (!_currentGameName.empty())
{
rMessage() << "GameManager: Selected game type: "
<< _currentGameName << std::endl;
}
else {
// No game type selected, bail out, the program would crash anyway on module load
wxutil::Messagebox::ShowFatalError(_("No game type selected."));
}
}
std::string Manager::getUserEnginePath()
{
#if defined(POSIX)
// First check for a local copy of the game tree, e.g. ~/.doom3
std::string localGamePrefix = currentGame()->getKeyValue("prefix");
if (!localGamePrefix.empty())
{
std::string homeDir = getenv("HOME");
fs::path localPath = fs::path(homeDir) / localGamePrefix;
if (fs::exists(localPath))
{
return os::standardPathWithSlash(localPath);
}
}
#endif
// Otherwise (Windows, or no local mod path found) return the regular engine
// path
return _enginePath;
}
void Manager::constructPaths()
{
_enginePath = GlobalRegistry().get(RKEY_ENGINE_PATH);
// Make sure it's a well formatted path
_enginePath = os::standardPathWithSlash(_enginePath);
// Read command line parameters, these override any existing preference setting
const ApplicationContext::ArgumentList& args(
module::ModuleRegistry::Instance().getApplicationContext().getCmdLineArgs()
);
for (ApplicationContext::ArgumentList::const_iterator i = args.begin();
i != args.end();
++i)
{
// get the argument and investigate it
std::string arg = *i;
if (string::istarts_with(arg, "fs_game="))
{
GlobalRegistry().set(RKEY_FS_GAME, arg.substr(8));
}
else if (string::istarts_with(arg, "fs_game_base="))
{
GlobalRegistry().set(RKEY_FS_GAME_BASE, arg.substr(13));
}
}
// Load the fsGame and fsGameBase from the registry
_fsGame = GlobalRegistry().get(RKEY_FS_GAME);
_fsGameBase = GlobalRegistry().get(RKEY_FS_GAME_BASE);
if (!_fsGameBase.empty())
{
// greebo: #3480 check if the mod base path is absolute. If not, append it to the engine path
_modBasePath = fs::path(_fsGameBase).is_absolute() ? _fsGameBase : getUserEnginePath() + _fsGameBase;
// Normalise the path as last step
_modBasePath = os::standardPathWithSlash(_modBasePath);
}
else
{
// No fs_game_base, no mod base path
_modBasePath = "";
}
if (!_fsGame.empty())
{
// greebo: #3480 check if the mod path is absolute. If not, append it to the engine path
_modPath = fs::path(_fsGame).is_absolute() ? _fsGame : getUserEnginePath() + _fsGame;
// Normalise the path as last step
_modPath = os::standardPathWithSlash(_modPath);
}
else
{
// No fs_game, no modpath
_modPath = "";
}
}
bool Manager::userWantsToCorrectSettings() const
{
std::stringstream msg("<b>Warning:</b>\n");
if (!os::fileOrDirExists(_enginePath))
{
msg << fmt::format(_("Engine path \"{0}\" does not exist.\n"), _enginePath);
}
if (!_fsGame.empty() && !os::fileOrDirExists(_modPath))
{
msg << fmt::format(_("The fs_game folder \"{0}\" does not exist.\n"), _modPath);
}
if (!_fsGameBase.empty() && !os::fileOrDirExists(_modBasePath))
{
msg << fmt::format(_("The fs_game_base folder \"{0}\" does not exist.\n"), _modBasePath);
}
msg << _("Do you want to correct these settings?");
return wxutil::Messagebox::Show(_("Invalid Settings"),
msg.str(), ui::IDialog::MESSAGE_ASK, NULL) == ui::IDialog::RESULT_YES;
}
void Manager::initEnginePath()
{
// Try to retrieve a saved value for the engine path
std::string enginePath = GlobalRegistry().get(RKEY_ENGINE_PATH);
xml::NodeList gameNodeList = GlobalRegistry().findXPath("game");
if (enginePath.empty() && gameNodeList.size() > 0) {
// No engine path known, but we have a valid game description
// Try to deduce the engine path from the Registry settings (Win32 only)
std::string regKey = gameNodeList[0].getAttributeValue("registryKey");
std::string regValue = gameNodeList[0].getAttributeValue("registryValue");
rMessage() << "GameManager: Querying Windows Registry for game path: "
<< "HKEY_LOCAL_MACHINE\\"
<< regKey << "\\" << regValue << std::endl;
// Query the Windows Registry for a default installation path
// This will return "" for non-Windows environments
enginePath = Win32Registry::getKeyValue(regKey, regValue);
rMessage() << "GameManager: Windows Registry returned result: "
<< enginePath << std::endl;
}
// If the engine path is still empty, consult the .game file for a fallback value
if (enginePath.empty()) {
// No engine path set so far, search the game file for default values
const std::string ENGINEPATH_ATTRIBUTE =
#if defined(WIN32)
"enginepath_win32"
#elif defined(__linux__) || defined (__FreeBSD__)
"enginepath_linux"
#elif defined(__APPLE__)
"enginepath_macos"
#else
#error "unknown platform"
#endif
;
enginePath = os::standardPathWithSlash(
currentGame()->getKeyValue(ENGINEPATH_ATTRIBUTE)
);
}
// Normalise the path in any case
enginePath = os::standardPathWithSlash(enginePath);
// Take this path and store it into the Registry, it's expected to be there
GlobalRegistry().set(RKEY_ENGINE_PATH, enginePath);
// Try to do something with the information currently in the Registry
// It should be enough to know the engine path and the fs_game.
constructPaths();
// Check loop, continue, till the user specifies a valid setting
while (!settingsValid())
{
// Engine path doesn't exist, ask the user
ui::GameSetupDialog::Show(cmd::ArgumentList());
//ui::PrefDialog::ShowDialog(_("Game"));
// After the dialog, the settings are located in the registry.
// Construct the paths with the settings found there
constructPaths();
if (!settingsValid() && !userWantsToCorrectSettings())
{
break;
}
}
// Register as observer, to get notified about future engine path changes
observeKey(RKEY_ENGINE_PATH);
observeKey(RKEY_FS_GAME);
observeKey(RKEY_FS_GAME_BASE);
// Force an update ((re-)initialises the VFS)
updateEnginePath(true);
// Add the note to the preference page
IPreferencePage& page = GetPreferenceSystem().getPage(_("Game"));
page.appendLabel(_("<b>Note</b>: You will have to restart DarkRadiant\nfor the changes to take effect."));
}
void Manager::observeKey(const std::string& key)
{
// Hide std::string signal argument, replace with bound false value for
// updateEnginePath().
GlobalRegistry().signalForKey(key).connect(
sigc::bind(sigc::mem_fun(this, &Manager::updateEnginePath), false)
);
}
void Manager::addVFSSearchPath(const std::string &path)
{
// If this path is searched earlier then the file would be found the first time.
for (PathList::iterator i = _vfsSearchPaths.begin();
i != _vfsSearchPaths.end(); ++i)
{
if (*i == path)
{
return;
}
}
_vfsSearchPaths.push_back(path);
}
bool Manager::settingsValid() const
{
if (os::fileOrDirExists(_enginePath)) {
// Check the mod base path, if appropriate
if (!_fsGameBase.empty() && !os::fileOrDirExists(_modBasePath)) {
// Mod base name is not empty, but folder doesnt' exist
return false;
}
// Check the mod path, if appropriate
if (!_fsGame.empty() && !os::fileOrDirExists(_modPath)) {
// Mod name is not empty, but mod folder doesnt' exist
return false;
}
return true; // all settings there
}
// Engine path doesn't exist
return false;
}
void Manager::setMapAndPrefabPaths(const std::string& baseGamePath)
{
// Construct the map path and make sure the folder exists
std::string mapPath;
// Get the maps folder (e.g. "maps/")
std::string mapFolder = currentGame()->getLocalXPath(GKEY_MAPS_FOLDER)[0].getAttributeValue("value");
if (mapFolder.empty()) {
mapFolder = "maps/";
}
if (_fsGame.empty() && _fsGameBase.empty()) {
mapPath = baseGamePath + mapFolder;
}
else if (!_fsGame.empty()) {
mapPath = _modPath + mapFolder;
}
else { // fsGameBase is not empty
mapPath = _modBasePath + mapFolder;
}
rMessage() << "GameManager: Map path set to " << mapPath << std::endl;
os::makeDirectory(mapPath);
// Save the map path to the registry
GlobalRegistry().set(RKEY_MAP_PATH, mapPath);
// Setup the prefab path
std::string prefabPath = mapPath;
std::string pfbFolder = currentGame()->getLocalXPath(GKEY_PREFAB_FOLDER)[0].getAttributeValue("value");
// Replace the "maps/" with "prefabs/"
string::replace_last(prefabPath, mapFolder, pfbFolder);
// Store the path into the registry
rMessage() << "GameManager: Prefab path set to " << prefabPath << std::endl;
GlobalRegistry().set(RKEY_PREFAB_PATH, prefabPath);
}
void Manager::updateEnginePath(bool forced)
{
// Clean the new path
std::string newPath = os::standardPathWithSlash(
GlobalRegistry().get(RKEY_ENGINE_PATH)
);
std::string newFSGame = GlobalRegistry().get(RKEY_FS_GAME);
std::string newFSGameBase = GlobalRegistry().get(RKEY_FS_GAME_BASE);
// Only update if any settings were changed, or if this is a "forced" update
if (newPath != _enginePath || newFSGame != _fsGame || newFSGameBase != _fsGameBase || forced)
{
bool enginePathWasInitialised = _enginePathInitialised;
// Check, if the engine path was already initialised in this session
// If yes, shutdown the virtual filesystem.
if (enginePathWasInitialised)
{
GlobalFileSystem().shutdown();
GlobalRegistry().set(RKEY_MAP_PATH, "");
_enginePathInitialised = false;
_vfsSearchPaths.clear();
}
// Set the new fs_game and engine paths
_fsGame = newFSGame;
_fsGameBase = newFSGameBase;
_enginePath = newPath;
// Reconstruct the paths basing on these two, the _modBasePath may be out of date
constructPaths();
if (!_enginePathInitialised)
{
if (!_fsGame.empty()) {
// We have a MOD, register this directory first
addVFSSearchPath(_modPath);
#if defined(POSIX)
// On Linux, the above was in ~/.doom3/, search the engine mod path as well
std::string baseModPath = os::standardPathWithSlash(_enginePath + _fsGame);
addVFSSearchPath(baseModPath);
#endif
}
if (!_fsGameBase.empty()) {
// We have a MOD base, register this directory as second
addVFSSearchPath(_modBasePath);
#if defined(POSIX)
// On Linux, the above was in ~/.doom3/, search the engine mod path as well
std::string baseModPath = os::standardPathWithSlash(_enginePath + _fsGameBase);
addVFSSearchPath(baseModPath);
#endif
}
// On UNIX this is the user-local enginepath, e.g. ~/.doom3/base/
// On Windows this will be the same as global engine path
std::string userBasePath = os::standardPathWithSlash(
getUserEnginePath() + // ~/.doom3
currentGame()->getKeyValue("basegame") // base
);
addVFSSearchPath(userBasePath);
// Register the base game folder (/usr/local/games/doom3/<basegame>) last
// This will always be searched, but *after* the other paths
std::string baseGame = os::standardPathWithSlash(
_enginePath + currentGame()->getKeyValue("basegame")
);
addVFSSearchPath(baseGame);
// Update map and prefab paths
setMapAndPrefabPaths(userBasePath);
_enginePathInitialised = true;
rMessage() << "VFS Search Path priority is: " << std::endl;
for (PathList::iterator i = _vfsSearchPaths.begin();
i != _vfsSearchPaths.end(); ++i)
{
rMessage() << "- " << (*i) << std::endl;
}
if (enginePathWasInitialised)
{
// Re-initialise the filesystem, if we were initialised before
GlobalFileSystem().initialise();
}
}
}
}
const Manager::PathList& Manager::getVFSSearchPaths() const {
// Should not be called before the list is initialised
if (_vfsSearchPaths.empty()) {
rConsole() << "GameManager: Warning, VFS search paths not yet initialised." << std::endl;
}
return _vfsSearchPaths;
}
const std::string& Manager::getEnginePath() const {
return _enginePath;
}
void Manager::loadGameFiles(const std::string& appPath)
{
std::string gamePath = appPath + "games/";
rMessage() << "GameManager: Scanning for game description files: " << gamePath << std::endl;
// Invoke a GameFileLoader functor on every file in the games/ dir.
GameFileLoader gameFileLoader(_games, gamePath);
try
{
os::foreachItemInDirectory(gamePath, gameFileLoader);
rMessage() << "GameManager: Found game definitions: " << std::endl;
for (GameMap::value_type& pair : _games)
{
rMessage() << " " << pair.first << std::endl;
}
// Populate the sorted games list
_sortedGames.clear();
// Sort the games by their index
std::multimap<int, GamePtr> sortedGameMap;
for (const GameMap::value_type& pair : _games)
{
int index = string::convert<int>(pair.second->getKeyValue("index"), 9999);
sortedGameMap.insert(std::make_pair(index, pair.second));
}
for (const auto& pair : sortedGameMap)
{
_sortedGames.push_back(pair.second);
}
rMessage() << std::endl;
}
catch (os::DirectoryNotFoundException&)
{
rError() << "Could not find directory with game files in " << gamePath << std::endl;
}
}
} // namespace game
// The static module definition (self-registers)
module::StaticModule<game::Manager> gameManagerModule;