/
ParticlesManager.cpp
402 lines (310 loc) · 10.3 KB
/
ParticlesManager.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
#include "ParticlesManager.h"
#include "ParticleDef.h"
#include "StageDef.h"
#include "ParticleNode.h"
#include "RenderableParticle.h"
#include "icommandsystem.h"
#include "itextstream.h"
#include "ifilesystem.h"
#include "ifiletypes.h"
#include "iarchive.h"
#include "igame.h"
#include "i18n.h"
#include "parser/DefTokeniser.h"
#include "decl/SpliceHelper.h"
#include "stream/TemporaryOutputStream.h"
#include "math/Vector4.h"
#include "os/fs.h"
#include "debugging/ScopedDebugTimer.h"
#include <fstream>
#include <iostream>
#include <functional>
#include <regex>
#include "string/predicate.h"
#include "module/StaticModule.h"
namespace particles
{
namespace
{
inline void writeParticleCommentHeader(std::ostream& str)
{
// The comment at the head of the decl
str << "/*" << std::endl
<< "\tGenerated by DarkRadiant's Particle Editor."
<< std::endl << "*/" << std::endl;
}
}
ParticlesManager::ParticlesManager() :
_defLoader(std::bind(&ParticlesManager::reloadParticleDefs, this))
{}
sigc::signal<void> ParticlesManager::signal_particlesReloaded() const
{
return _particlesReloadedSignal;
}
// Visit all of the particle defs
void ParticlesManager::forEachParticleDef(const ParticleDefVisitor& v)
{
ensureDefsLoaded();
// Invoke the visitor for each ParticleDef object
for (const ParticleDefMap::value_type& pair : _particleDefs)
{
v(*pair.second);
}
}
IParticleDefPtr ParticlesManager::getDefByName(const std::string& name)
{
ensureDefsLoaded();
ParticleDefMap::const_iterator found = _particleDefs.find(name);
return found != _particleDefs.end() ? found->second : IParticleDefPtr();
}
IParticleNodePtr ParticlesManager::createParticleNode(const std::string& name)
{
std::string nameCleaned = name;
// Cut off the ".prt" from the end of the particle name
if (string::ends_with(nameCleaned, ".prt"))
{
nameCleaned = nameCleaned.substr(0, nameCleaned.length() - 4);
}
ensureDefsLoaded();
ParticleDefMap::const_iterator found = _particleDefs.find(nameCleaned);
if (found == _particleDefs.end())
{
return IParticleNodePtr();
}
RenderableParticlePtr renderable(new RenderableParticle(found->second));
return ParticleNodePtr(new ParticleNode(renderable));
}
IRenderableParticlePtr ParticlesManager::getRenderableParticle(const std::string& name)
{
ensureDefsLoaded();
ParticleDefMap::const_iterator found = _particleDefs.find(name);
if (found != _particleDefs.end())
{
return RenderableParticlePtr(new RenderableParticle(found->second));
}
else
{
return IRenderableParticlePtr();
}
}
IParticleDefPtr ParticlesManager::findOrInsertParticleDef(const std::string& name)
{
ensureDefsLoaded();
return findOrInsertParticleDefInternal(name);
}
ParticleDefPtr ParticlesManager::findOrInsertParticleDefInternal(const std::string& name)
{
ParticleDefMap::iterator i = _particleDefs.find(name);
if (i != _particleDefs.end())
{
// Particle def is already existing in the map
return i->second;
}
// Not existing, add a new ParticleDef to the map
std::pair<ParticleDefMap::iterator, bool> result = _particleDefs.insert(
ParticleDefMap::value_type(name, ParticleDefPtr(new ParticleDef(name))));
// Return the iterator from the insertion result
return result.first->second;
}
void ParticlesManager::removeParticleDef(const std::string& name)
{
ensureDefsLoaded();
ParticleDefMap::iterator i = _particleDefs.find(name);
if (i != _particleDefs.end())
{
_particleDefs.erase(i);
}
}
void ParticlesManager::ensureDefsLoaded()
{
_defLoader.ensureFinished();
}
// Parse particle defs from string
void ParticlesManager::parseStream(std::istream& contents, const std::string& filename)
{
// Usual ritual, get a parser::DefTokeniser and start tokenising the DEFs
parser::BasicDefTokeniser<std::istream> tok(contents);
while (tok.hasMoreTokens())
{
parseParticleDef(tok, filename);
}
}
// Parse a single particle def
void ParticlesManager::parseParticleDef(parser::DefTokeniser& tok, const std::string& filename)
{
// Standard DEF, starts with "particle <name> {"
std::string declName = tok.nextToken();
// Check for a valid particle declaration, some .prt files contain materials
if (declName != "particle")
{
// No particle, skip name plus whole block
tok.skipTokens(1);
tok.assertNextToken("{");
for (std::size_t level = 1; level > 0;)
{
std::string token = tok.nextToken();
if (token == "}")
{
level--;
}
else if (token == "{")
{
level++;
}
}
return;
}
// Valid particle declaration, go ahead parsing the name
std::string name = tok.nextToken();
tok.assertNextToken("{");
// Find the particle def (use the non-blocking, internal lookup)
ParticleDefPtr pdef = findOrInsertParticleDefInternal(name);
pdef->setFilename(filename);
// Let the particle construct itself from the token stream
pdef->parseFromTokens(tok);
}
const std::string& ParticlesManager::getName() const
{
static std::string _name(MODULE_PARTICLESMANAGER);
return _name;
}
const StringSet& ParticlesManager::getDependencies() const
{
static StringSet _dependencies;
if (_dependencies.empty())
{
_dependencies.insert(MODULE_VIRTUALFILESYSTEM);
_dependencies.insert(MODULE_COMMANDSYSTEM);
_dependencies.insert(MODULE_FILETYPES);
}
return _dependencies;
}
void ParticlesManager::initialiseModule(const IApplicationContext& ctx)
{
rMessage() << "ParticlesManager::initialiseModule called" << std::endl;
// Load the .prt files in a new thread, public methods will block until
// this has been completed
_defLoader.start();
// Register the "ReloadParticles" commands
GlobalCommandSystem().addCommand("ReloadParticles", std::bind(&ParticlesManager::reloadParticleDefs, this));
// Register the particle file extension
GlobalFiletypes().registerPattern("particle", FileTypePattern(_("Particle File"), "prt", "*.prt"));
}
void ParticlesManager::reloadParticleDefs()
{
ScopedDebugTimer timer("Particle definitions parsed: ");
GlobalFileSystem().forEachFile(
PARTICLES_DIR, PARTICLES_EXT,
[&](const vfs::FileInfo& fileInfo)
{
// Attempt to open the file in text mode
ArchiveTextFilePtr file = GlobalFileSystem().openTextFile(PARTICLES_DIR + fileInfo.name);
if (file != NULL)
{
// File is open, so parse the tokens
try
{
std::istream is(&(file->getInputStream()));
parseStream(is, fileInfo.name);
}
catch (parser::ParseException& e)
{
rError() << "[particles] Failed to parse " << fileInfo.name
<< ": " << e.what() << std::endl;
}
}
else
{
rError() << "[particles] Unable to open " << fileInfo.name << std::endl;
}
},
1 // depth == 1: don't search subdirectories
);
rMessage() << "Found " << _particleDefs.size() << " particle definitions." << std::endl;
// Notify observers about this event
_particlesReloadedSignal.emit();
}
void ParticlesManager::saveParticleDef(const std::string& particleName)
{
ensureDefsLoaded();
ParticleDefMap::const_iterator found = _particleDefs.find(particleName);
if (found == _particleDefs.end())
{
throw std::runtime_error(_("Cannot save particle, it has not been registered yet."));
}
ParticleDefPtr particle = found->second;
std::string relativePath = PARTICLES_DIR + particle->getFilename();
fs::path targetPath = GlobalGameManager().getModPath();
if (targetPath.empty())
{
targetPath = GlobalGameManager().getUserEnginePath();
rMessage() << "No mod base path found, falling back to user engine path to save particle file: " <<
targetPath.string() << std::endl;
}
targetPath /= PARTICLES_DIR;
// Ensure the particles folder exists
fs::create_directories(targetPath);
fs::path targetFile = targetPath / particle->getFilename();
// If the file doesn't exist yet, let's check if we need to inherit stuff first from the VFS
if (!fs::exists(targetFile))
{
ArchiveTextFilePtr inheritFile = GlobalFileSystem().openTextFile(relativePath);
if (inheritFile)
{
// There is a file with that name already in the VFS, copy it to the target file
TextInputStream& inheritStream = inheritFile->getInputStream();
std::ofstream outFile(targetFile.string().c_str());
if (!outFile.is_open())
{
throw std::runtime_error(
fmt::format(_("Cannot open file for writing: {0}"), targetFile.string()));
}
char buf[16384];
std::size_t bytesRead = inheritStream.read(buf, sizeof(buf));
while (bytesRead > 0)
{
outFile.write(buf, bytesRead);
bytesRead = inheritStream.read(buf, sizeof(buf));
}
outFile.close();
}
}
// Open a temporary file
stream::TemporaryOutputStream tempStream(targetFile);
std::string tempString;
auto& stream = tempStream.getStream();
// If a previous file exists, open it for reading and filter out the particle def we'll be writing
if (fs::exists(targetFile))
{
std::ifstream inheritStream(targetFile.string().c_str());
if (!inheritStream.is_open())
{
throw std::runtime_error(
fmt::format(_("Cannot open file for reading: {0}"), targetFile.string()));
}
// Write the file to the output stream, up to the point the particle def should be written to
std::regex pattern("^[\\s]*particle[\\s]+" + particleName + "\\s*(\\{)*\\s*$");
decl::SpliceHelper::PipeStreamUntilInsertionPoint(inheritStream, stream, pattern);
if (inheritStream.eof())
{
// Particle def was not found in the inherited stream, write our comment
stream << std::endl << std::endl;
writeParticleCommentHeader(stream);
}
// We're at the insertion point (which might as well be EOF of the inheritStream)
// Write the particle declaration
stream << *particle << std::endl;
stream << inheritStream.rdbuf();
inheritStream.close();
}
else
{
// Just put the particle def into the file and that's it, leave a comment at the head of the decl
writeParticleCommentHeader(stream);
// Write the particle declaration
stream << *particle << std::endl;
}
tempStream.closeAndReplaceTargetFile();
}
module::StaticModuleRegistration<ParticlesManager> particlesManagerModule;
} // namespace particles