/
MapResource.cpp
467 lines (381 loc) · 11.9 KB
/
MapResource.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
#include "MapResource.h"
#include "i18n.h"
#include <sstream>
#include <fstream>
#include <iostream>
#include "ifiletypes.h"
#include "ientity.h"
#include "iarchive.h"
#include "igroupnode.h"
#include "ifilesystem.h"
#include "iregistry.h"
#include "imapinfofile.h"
#include "map/Map.h"
#include "map/RootNode.h"
#include "mapfile.h"
#include "gamelib.h"
#include "debugging/debugging.h"
#include "os/path.h"
#include "os/file.h"
#include "os/fs.h"
#include "scene/Traverse.h"
#include "scenelib.h"
#include <functional>
#include <fmt/format.h>
#include "infofile/InfoFile.h"
#include "string/string.h"
#include "algorithm/MapExporter.h"
#include "algorithm/Import.h"
#include "infofile/InfoFileExporter.h"
#include "messages/MapFileOperation.h"
#include "NodeCounter.h"
#include "MapResourceLoader.h"
namespace map
{
namespace
{
const char* const GKEY_INFO_FILE_EXTENSION = "/mapFormat/infoFileExtension";
// name may be absolute or relative
inline std::string rootPath(const std::string& name) {
return GlobalFileSystem().findRoot(
path_is_absolute(name.c_str()) ? name : GlobalFileSystem().findFile(name)
);
}
}
MapResource::MapResource(const std::string& resourcePath)
{
constructPaths(resourcePath);
}
void MapResource::rename(const std::string& fullPath)
{
constructPaths(fullPath);
// Rename the map root as well
_mapRoot->setName(_name);
}
void MapResource::constructPaths(const std::string& resourcePath)
{
// Since the resource path can contain dots like this ".."
// pass the filename part only to getExtension().
_extension = os::getExtension(os::getFilename(resourcePath));
// Try to find a folder part of the VFS and use that as base path
// Will result to an empty string if the path is outside the VFS
_path = rootPath(resourcePath);
// Try to create a relative path, based on the VFS directories
// If no relative path can be deducted, use the absolute resourcePath
// in unmodified form.
_name = os::getRelativePath(resourcePath, _path);
}
std::string MapResource::getAbsoluteResourcePath()
{
// Concatenate path+name, since they either contain base + relative:
// _path == "c:/games/darkmod/"
// _name == "maps/arkham.map"
// or an empty _path with _name holding the full path:
// _path == ""
// _name == "c:/some/non/vfs/folder/arkham.map"
return _path + _name;
}
bool MapResource::load()
{
if (!_mapRoot)
{
// Map not loaded yet, acquire map root node from loader
_mapRoot = loadMapNode();
connectMap();
mapSave();
}
return _mapRoot != nullptr;
}
bool MapResource::isReadOnly()
{
return !FileIsWriteable(getAbsoluteResourcePath());
}
void MapResource::save(const MapFormatPtr& mapFormat)
{
// For saving, take the default map format for this game type
MapFormatPtr format = mapFormat ? mapFormat : GlobalMapFormatManager().getMapFormatForGameType(
GlobalGameManager().currentGame()->getKeyValue("type"), _extension
);
if (!format)
{
rError() << "Could not locate map format module." << std::endl;
throw OperationException(_("Failed to locate map format module"));
}
rMessage() << "Using " << format->getMapFormatName() << " format to save the resource." << std::endl;
std::string fullpath = getAbsoluteResourcePath();
// Save a backup of the existing file (rename it to .bak) if it exists in the first place
if (os::fileOrDirExists(fullpath) && !saveBackup())
{
// angua: if backup creation is not possible, still save the map
// but create message in the console
rError() << "Could not create backup (Map is possibly open in Doom3)" << std::endl;
}
if (!path_is_absolute(fullpath.c_str()))
{
rError() << "Map path is not absolute: " << fullpath << std::endl;
throw OperationException(fmt::format(_("Map path is not absolute: {0}"), fullpath));
}
// Save the actual file (throws on fail)
saveFile(*format, _mapRoot, scene::traverse, fullpath);
mapSave();
}
bool MapResource::saveBackup()
{
fs::path fullpath = getAbsoluteResourcePath();
if (path_is_absolute(fullpath.string().c_str()))
{
// Save a backup if possible. This is done by renaming the original,
// which won't work if the existing map is currently open by Doom 3
// in the background.
if (!fs::exists(fullpath))
{
return false;
}
fs::path auxFile = fullpath;
auxFile.replace_extension(GetInfoFileExtension());
fs::path backup = fullpath;
backup.replace_extension(".bak");
// replace_extension() doesn't accept something like ".darkradiant.bak", so roll our own
fs::path auxFileBackup = auxFile.string() + ".bak";
bool errorOccurred = false;
try
{
// remove backup
if (fs::exists(backup))
{
fs::remove(backup);
}
// rename current to backup
fs::rename(fullpath, backup);
}
catch (fs::filesystem_error& ex)
{
rWarning() << "Error while creating backups: " << ex.what() <<
", the file is possibly opened by the game." << std::endl;
errorOccurred = true;
}
// Handle the .darkradiant file only if the above succeeded
if (!errorOccurred)
{
try
{
// remove aux file backup
if (fs::exists(auxFileBackup))
{
fs::remove(auxFileBackup);
}
// Check if the .darkradiant file exists in the first place
if (fs::exists(auxFile))
{
// rename current to backup
fs::rename(auxFile, auxFileBackup);
}
}
catch (fs::filesystem_error & ex)
{
rWarning() << "Error while creating backups: " << ex.what() <<
", the file is possibly opened by the game." << std::endl;
errorOccurred = true;
}
}
return !errorOccurred;
}
return false;
}
const scene::IMapRootNodePtr& MapResource::getRootNode()
{
return _mapRoot;
}
void MapResource::setRootNode(const scene::IMapRootNodePtr& root)
{
_mapRoot = root;
}
void MapResource::clear()
{
_mapRoot = std::make_shared<RootNode>("");
connectMap();
}
void MapResource::onMapChanged()
{
GlobalMap().setModified(true);
}
void MapResource::connectMap()
{
if (_mapRoot)
{
// Reroute the changed callback to the onMapChanged() call.
_mapRoot->getUndoChangeTracker().setChangedCallback(std::bind(&MapResource::onMapChanged, this));
}
}
void MapResource::mapSave()
{
if (_mapRoot)
{
_mapRoot->getUndoChangeTracker().save();
}
}
RootNodePtr MapResource::loadMapNode()
{
RootNodePtr rootNode;
// Open a stream - will throw on failure
auto stream = openMapfileStream();
if (!stream || !stream->isOpen())
{
throw OperationException(_("Could not open map stream"));
}
try
{
// Get the mapformat
auto format = algorithm::determineMapFormat(stream->getStream(), _extension);
if (!format)
{
throw OperationException(_("Could not determine map format"));
}
// Instantiate a loader to process the map file stream
MapResourceLoader loader(stream->getStream(), *format);
// Load the root from the primary stream (throws on failure or cancel)
rootNode = loader.load();
if (rootNode)
{
rootNode->setName(_name);
}
// Check if an info file is supported by this map format
if (format->allowInfoFileCreation())
{
auto infoFileStream = openInfofileStream();
if (infoFileStream && infoFileStream->isOpen())
{
loader.loadInfoFile(infoFileStream->getStream(), rootNode);
}
}
}
catch (const OperationException& ex)
{
// Re-throw the exception, prepending the map file path to the message (if not cancelled)
throw ex.operationCancelled() ? ex :
OperationException(fmt::format(_("Failure reading map file:\n{0}\n\n{1}"), getAbsoluteResourcePath(), ex.what()));
}
return rootNode;
}
stream::MapResourceStream::Ptr MapResource::openFileStream(const std::string& path)
{
// Call the factory method to acquire a stream
auto stream = stream::MapResourceStream::OpenFromPath(path);
if (!stream->isOpen())
{
throw OperationException(fmt::format(_("Could not open file:\n{0}"), path));
}
return stream;
}
stream::MapResourceStream::Ptr MapResource::openMapfileStream()
{
return openFileStream(getAbsoluteResourcePath());
}
stream::MapResourceStream::Ptr MapResource::openInfofileStream()
{
try
{
auto fullpath = getAbsoluteResourcePath();
auto infoFilename = fullpath.substr(0, fullpath.rfind('.'));
infoFilename += GetInfoFileExtension();
return openFileStream(infoFilename);
}
catch (const OperationException& ex)
{
// Info file load file does not stop us, just issue a warning
rWarning() << ex.what() << std::endl;
return stream::MapResourceStream::Ptr();
}
}
std::string MapResource::GetInfoFileExtension()
{
std::string extension = game::current::getValue<std::string>(GKEY_INFO_FILE_EXTENSION);
if (!extension.empty() && extension[0] != '.')
{
extension = "." + extension;
}
return extension;
}
bool MapResource::FileIsWriteable(const fs::path& path)
{
return !os::fileOrDirExists(path.string()) || os::fileIsWritable(path);
}
void MapResource::throwIfNotWriteable(const fs::path& path)
{
// Check writeability of the given file
if (!FileIsWriteable(path))
{
// File is write-protected
rError() << "File is write-protected." << std::endl;
throw OperationException(fmt::format(_("File is write-protected: {0}"), path.string()));
}
}
void MapResource::saveFile(const MapFormat& format, const scene::IMapRootNodePtr& root,
const GraphTraversalFunc& traverse, const std::string& filename)
{
// Actual output file paths
fs::path outFile = filename;
fs::path auxFile = outFile;
auxFile.replace_extension(GetInfoFileExtension());
// Check writeability of the primary output file
throwIfNotWriteable(outFile);
// Test opening the output file
rMessage() << "Opening file " << outFile.string();
// Open the stream to the primary output file
std::ofstream outFileStream(outFile.string());
std::unique_ptr<std::ofstream> auxFileStream; // aux stream is optional
// Check writeability of the auxiliary output file if necessary
if (format.allowInfoFileCreation())
{
rMessage() << " and auxiliary file " << auxFile.string();
throwIfNotWriteable(auxFile);
auxFileStream.reset(new std::ofstream(auxFile.string()));
}
rMessage() << " for writing... ";
if (!outFileStream.is_open())
{
throw OperationException(fmt::format(_("Could not open file for writing: {0}"), outFile.string()));
}
if (auxFileStream && !auxFileStream->is_open())
{
throw OperationException(fmt::format(_("Could not open file for writing: {0}"), auxFile.string()));
}
rMessage() << "success" << std::endl;
// Check the total count of nodes to traverse
NodeCounter counter;
traverse(root, counter);
// Create our main MapExporter walker, and pass the desired
// format to it. The constructor will prepare the scene
// and the destructor will clean it up afterwards. That way
// we ensure a nice and tidy scene when exceptions are thrown.
MapExporterPtr exporter;
auto mapWriter = format.getMapWriter();
if (format.allowInfoFileCreation())
{
exporter.reset(new MapExporter(*mapWriter, root, outFileStream, *auxFileStream, counter.getCount()));
}
else
{
exporter.reset(new MapExporter(*mapWriter, root, outFileStream, counter.getCount())); // no aux stream
}
try
{
// Pass the traversal function and the root of the subgraph to export
exporter->exportMap(root, traverse);
}
catch (FileOperation::OperationCancelled&)
{
throw OperationException(_("Map writing cancelled"));
}
exporter.reset();
// Check for any stream failures now that we're done writing
if (outFileStream.fail())
{
throw OperationException(fmt::format(_("Failure writing to file {0}"), outFile.string()));
}
if (auxFileStream && auxFileStream->fail())
{
throw OperationException(fmt::format(_("Failure writing to file {0}"), auxFile.string()));
}
}
} // namespace map