Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ParticleEmitterType.h"
21 :
22 : #include "graphics/Color.h"
23 : #include "graphics/ParticleEmitter.h"
24 : #include "graphics/ParticleManager.h"
25 : #include "graphics/SColor.h"
26 : #include "graphics/TextureManager.h"
27 : #include "lib/debug.h"
28 : #include "maths/MathUtil.h"
29 : #include "maths/Matrix3D.h"
30 : #include "maths/Quaternion.h"
31 : #include "maths/Vector3D.h"
32 : #include "ps/CLogger.h"
33 : #include "ps/CStr.h"
34 : #include "ps/Errors.h"
35 : #include "ps/Filesystem.h"
36 : #include "ps/XMB/XMBData.h"
37 : #include "ps/XMB/XMBStorage.h"
38 : #include "ps/XML/Xeromyces.h"
39 : #include "renderer/Renderer.h"
40 : #include "renderer/backend/Sampler.h"
41 :
42 : #include <algorithm>
43 : #include <cmath>
44 : #include <cstddef>
45 : #include <map>
46 : #include <random>
47 :
48 : /**
49 : * Interface for particle state variables, which get evaluated for each newly
50 : * constructed particle.
51 : */
52 : class IParticleVar
53 : {
54 : public:
55 0 : IParticleVar() : m_LastValue(0) { }
56 : virtual ~IParticleVar() {}
57 :
58 : /// Computes and returns a new value.
59 0 : float Evaluate(CParticleEmitter& emitter)
60 : {
61 0 : m_LastValue = Compute(emitter.m_Type, emitter);
62 0 : return m_LastValue;
63 : }
64 :
65 : /**
66 : * Returns the last value that Evaluate returned.
67 : * This is used for variables that depend on other variables (which is kind
68 : * of fragile since it's very order-dependent), so they don't get re-randomised
69 : * and don't have a danger of infinite recursion.
70 : */
71 0 : float LastValue() { return m_LastValue; }
72 :
73 : /**
74 : * Returns the minimum value that Evaluate might ever return,
75 : * for computing bounds.
76 : */
77 : virtual float Min(const CParticleEmitterType& type) = 0;
78 :
79 : /**
80 : * Returns the maximum value that Evaluate might ever return,
81 : * for computing bounds.
82 : */
83 : virtual float Max(const CParticleEmitterType& type) = 0;
84 :
85 : protected:
86 : virtual float Compute(const CParticleEmitterType& type, const CParticleEmitter& emitter) = 0;
87 :
88 : private:
89 : float m_LastValue;
90 : };
91 :
92 : /**
93 : * Particle variable that returns a constant value.
94 : */
95 : class CParticleVarConstant : public IParticleVar
96 : {
97 : public:
98 0 : CParticleVarConstant(float val) :
99 0 : m_Value(val)
100 : {
101 : }
102 :
103 0 : float Compute(const CParticleEmitterType&, const CParticleEmitter&) override
104 : {
105 0 : return m_Value;
106 : }
107 :
108 0 : float Min(const CParticleEmitterType&) override
109 : {
110 0 : return m_Value;
111 : }
112 :
113 0 : float Max(const CParticleEmitterType&) override
114 : {
115 0 : return m_Value;
116 : }
117 :
118 : private:
119 : float m_Value;
120 : };
121 :
122 : /**
123 : * Particle variable that returns a uniformly-distributed random value.
124 : */
125 : class CParticleVarUniform : public IParticleVar
126 : {
127 : public:
128 0 : CParticleVarUniform(float min, float max) :
129 0 : m_Distribution{min, max}
130 : {
131 : }
132 :
133 0 : float Compute(const CParticleEmitterType& type, const CParticleEmitter&) override
134 : {
135 0 : return m_Distribution(type.m_Manager.m_RNG);
136 : }
137 :
138 0 : float Min(const CParticleEmitterType&) override
139 : {
140 0 : return m_Distribution.a();
141 : }
142 :
143 0 : float Max(const CParticleEmitterType&) override
144 : {
145 0 : return m_Distribution.b();
146 : }
147 :
148 : private:
149 : std::uniform_real_distribution<float> m_Distribution;
150 : };
151 :
152 : /**
153 : * Particle variable that returns the same value as some other variable
154 : * (assuming that variable was evaluated before this one).
155 : */
156 : class CParticleVarCopy : public IParticleVar
157 : {
158 : public:
159 0 : CParticleVarCopy(int from) :
160 0 : m_From(from)
161 : {
162 : }
163 :
164 0 : float Compute(const CParticleEmitterType& type, const CParticleEmitter&) override
165 : {
166 0 : return type.m_Variables[m_From]->LastValue();
167 : }
168 :
169 0 : float Min(const CParticleEmitterType& type) override
170 : {
171 0 : return type.m_Variables[m_From]->Min(type);
172 : }
173 :
174 0 : float Max(const CParticleEmitterType& type) override
175 : {
176 0 : return type.m_Variables[m_From]->Max(type);
177 : }
178 :
179 : private:
180 : int m_From;
181 : };
182 :
183 : /**
184 : * A terrible ad-hoc attempt at handling some particular variable calculation,
185 : * which really needs to be cleaned up and generalised.
186 : */
187 : class CParticleVarExpr : public IParticleVar
188 : {
189 : public:
190 0 : CParticleVarExpr(const CStr& from, float mul, float max) :
191 0 : m_From(from), m_Mul(mul), m_Max(max)
192 : {
193 : }
194 :
195 0 : float Compute(const CParticleEmitterType&, const CParticleEmitter& emitter) override
196 : {
197 0 : float value{0.0f};
198 0 : if (auto it{emitter.m_EntityVariables.find(m_From)}; it != emitter.m_EntityVariables.end())
199 0 : value = it->second;
200 0 : return std::min(m_Max, value * m_Mul);
201 : }
202 :
203 0 : float Min(const CParticleEmitterType&) override
204 : {
205 0 : return 0.f;
206 : }
207 :
208 0 : float Max(const CParticleEmitterType&) override
209 : {
210 0 : return m_Max;
211 : }
212 :
213 : private:
214 : CStr m_From;
215 : float m_Mul;
216 : float m_Max;
217 : };
218 :
219 :
220 :
221 : /**
222 : * Interface for particle effectors, which get evaluated every frame to
223 : * update particles.
224 : */
225 : class IParticleEffector
226 : {
227 : public:
228 0 : IParticleEffector() { }
229 : virtual ~IParticleEffector() {}
230 :
231 : /// Updates all particles.
232 : virtual void Evaluate(std::vector<SParticle>& particles, float dt) = 0;
233 :
234 : /// Returns maximum acceleration caused by this effector.
235 : virtual CVector3D Max() = 0;
236 :
237 : };
238 :
239 : /**
240 : * Particle effector that applies a constant acceleration.
241 : */
242 : class CParticleEffectorForce : public IParticleEffector
243 : {
244 : public:
245 0 : CParticleEffectorForce(float x, float y, float z) :
246 0 : m_Accel(x, y, z)
247 : {
248 : }
249 :
250 0 : void Evaluate(std::vector<SParticle>& particles, float dt) override
251 : {
252 0 : CVector3D dv = m_Accel * dt;
253 :
254 0 : for (size_t i = 0; i < particles.size(); ++i)
255 0 : particles[i].velocity += dv;
256 0 : }
257 :
258 0 : CVector3D Max() override
259 : {
260 0 : return m_Accel;
261 : }
262 :
263 : private:
264 : CVector3D m_Accel;
265 : };
266 :
267 :
268 :
269 :
270 0 : CParticleEmitterType::CParticleEmitterType(CParticleManager& manager) :
271 0 : m_Manager(manager)
272 : {
273 0 : }
274 :
275 0 : bool CParticleEmitterType::Load(const VfsPath& path)
276 : {
277 0 : if (!LoadXML(path))
278 : return false;
279 :
280 : // Upper bound on number of particles depends on maximum rate and lifetime
281 0 : m_MaxLifetime = m_Variables[VAR_LIFETIME]->Max(*this);
282 0 : const uint32_t maximumNumberOfParticles{
283 0 : static_cast<uint32_t>(ceil(m_Variables[VAR_EMISSIONRATE]->Max(*this) * m_MaxLifetime))};
284 0 : constexpr uint16_t maximumSupportedNumberOfParticles{
285 : std::numeric_limits<uint16_t>::max() / 6};
286 0 : if (maximumNumberOfParticles > maximumSupportedNumberOfParticles)
287 : {
288 0 : LOGERROR("Too many particles per particle system: '{}' ({}/{})",
289 : path.string8(), maximumNumberOfParticles, maximumSupportedNumberOfParticles);
290 0 : m_MaxParticles = maximumSupportedNumberOfParticles;
291 : }
292 : else
293 0 : m_MaxParticles = maximumNumberOfParticles;
294 :
295 :
296 : // Compute the worst-case bounds of all possible particles,
297 : // based on the min/max values of positions and velocities and accelerations
298 : // and sizes. (This isn't a guaranteed bound but it should be sufficient for
299 : // culling.)
300 :
301 : // Assuming constant acceleration,
302 : // p = p0 + v0*t + 1/2 a*t^2
303 : // => dp/dt = v0 + a*t
304 : // = 0 at t = -v0/a
305 : // max(p) is at t=0, or t=tmax, or t=-v0/a if that's between 0 and tmax
306 : // => max(p) = max(p0, p0 + v0*tmax + 1/2 a*tmax, p0 - 1/2 v0^2/a)
307 :
308 : // Compute combined acceleration (assume constant)
309 0 : CVector3D accel;
310 0 : for (size_t i = 0; i < m_Effectors.size(); ++i)
311 0 : accel += m_Effectors[i]->Max();
312 :
313 0 : CVector3D vmin(m_Variables[VAR_VELOCITY_X]->Min(*this), m_Variables[VAR_VELOCITY_Y]->Min(*this), m_Variables[VAR_VELOCITY_Z]->Min(*this));
314 0 : CVector3D vmax(m_Variables[VAR_VELOCITY_X]->Max(*this), m_Variables[VAR_VELOCITY_Y]->Max(*this), m_Variables[VAR_VELOCITY_Z]->Max(*this));
315 :
316 : // Start by assuming p0 = 0; compute each XYZ component individually
317 0 : m_MaxBounds.SetEmpty();
318 : // Lower/upper bounds at t=0, t=tmax
319 0 : m_MaxBounds[0].X = std::min(0.f, vmin.X*m_MaxLifetime + 0.5f*accel.X*m_MaxLifetime*m_MaxLifetime);
320 0 : m_MaxBounds[0].Y = std::min(0.f, vmin.Y*m_MaxLifetime + 0.5f*accel.Y*m_MaxLifetime*m_MaxLifetime);
321 0 : m_MaxBounds[0].Z = std::min(0.f, vmin.Z*m_MaxLifetime + 0.5f*accel.Z*m_MaxLifetime*m_MaxLifetime);
322 0 : m_MaxBounds[1].X = std::max(0.f, vmax.X*m_MaxLifetime + 0.5f*accel.X*m_MaxLifetime*m_MaxLifetime);
323 0 : m_MaxBounds[1].Y = std::max(0.f, vmax.Y*m_MaxLifetime + 0.5f*accel.Y*m_MaxLifetime*m_MaxLifetime);
324 0 : m_MaxBounds[1].Z = std::max(0.f, vmax.Z*m_MaxLifetime + 0.5f*accel.Z*m_MaxLifetime*m_MaxLifetime);
325 : // Extend bounds to include position at t where dp/dt=0, if 0 < t < tmax
326 0 : if (accel.X && 0 < -vmin.X/accel.X && -vmin.X/accel.X < m_MaxLifetime)
327 0 : m_MaxBounds[0].X = std::min(m_MaxBounds[0].X, -0.5f*vmin.X*vmin.X / accel.X);
328 0 : if (accel.Y && 0 < -vmin.Y/accel.Y && -vmin.Y/accel.Y < m_MaxLifetime)
329 0 : m_MaxBounds[0].Y = std::min(m_MaxBounds[0].Y, -0.5f*vmin.Y*vmin.Y / accel.Y);
330 0 : if (accel.Z && 0 < -vmin.Z/accel.Z && -vmin.Z/accel.Z < m_MaxLifetime)
331 0 : m_MaxBounds[0].Z = std::min(m_MaxBounds[0].Z, -0.5f*vmin.Z*vmin.Z / accel.Z);
332 0 : if (accel.X && 0 < -vmax.X/accel.X && -vmax.X/accel.X < m_MaxLifetime)
333 0 : m_MaxBounds[1].X = std::max(m_MaxBounds[1].X, -0.5f*vmax.X*vmax.X / accel.X);
334 0 : if (accel.Y && 0 < -vmax.Y/accel.Y && -vmax.Y/accel.Y < m_MaxLifetime)
335 0 : m_MaxBounds[1].Y = std::max(m_MaxBounds[1].Y, -0.5f*vmax.Y*vmax.Y / accel.Y);
336 0 : if (accel.Z && 0 < -vmax.Z/accel.Z && -vmax.Z/accel.Z < m_MaxLifetime)
337 0 : m_MaxBounds[1].Z = std::max(m_MaxBounds[1].Z, -0.5f*vmax.Z*vmax.Z / accel.Z);
338 :
339 : // Offset by the initial positions
340 0 : m_MaxBounds[0] += CVector3D(m_Variables[VAR_POSITION_X]->Min(*this), m_Variables[VAR_POSITION_Y]->Min(*this), m_Variables[VAR_POSITION_Z]->Min(*this));
341 0 : m_MaxBounds[1] += CVector3D(m_Variables[VAR_POSITION_X]->Max(*this), m_Variables[VAR_POSITION_Y]->Max(*this), m_Variables[VAR_POSITION_Z]->Max(*this));
342 :
343 0 : return true;
344 : }
345 :
346 0 : CParticleEmitterType::~CParticleEmitterType() = default;
347 :
348 0 : int CParticleEmitterType::GetVariableID(const std::string& name)
349 : {
350 0 : if (name == "emissionrate") return VAR_EMISSIONRATE;
351 0 : if (name == "lifetime") return VAR_LIFETIME;
352 0 : if (name == "position.x") return VAR_POSITION_X;
353 0 : if (name == "position.y") return VAR_POSITION_Y;
354 0 : if (name == "position.z") return VAR_POSITION_Z;
355 0 : if (name == "angle") return VAR_ANGLE;
356 0 : if (name == "velocity.x") return VAR_VELOCITY_X;
357 0 : if (name == "velocity.y") return VAR_VELOCITY_Y;
358 0 : if (name == "velocity.z") return VAR_VELOCITY_Z;
359 0 : if (name == "velocity.angle") return VAR_VELOCITY_ANGLE;
360 0 : if (name == "size") return VAR_SIZE;
361 0 : if (name == "size.growthRate") return VAR_SIZE_GROWTHRATE;
362 0 : if (name == "color.r") return VAR_COLOR_R;
363 0 : if (name == "color.g") return VAR_COLOR_G;
364 0 : if (name == "color.b") return VAR_COLOR_B;
365 0 : LOGWARNING("Particle sets unknown variable '{}'", name);
366 0 : return -1;
367 : }
368 :
369 0 : bool CParticleEmitterType::LoadXML(const VfsPath& path)
370 : {
371 : // Initialise with sane defaults
372 0 : m_Variables.clear();
373 0 : m_Variables.resize(VAR__MAX);
374 0 : m_Variables[VAR_EMISSIONRATE] = std::make_unique<CParticleVarConstant>(10.f);
375 0 : m_Variables[VAR_LIFETIME] = std::make_unique<CParticleVarConstant>(3.f);
376 0 : m_Variables[VAR_POSITION_X] = std::make_unique<CParticleVarConstant>(0.f);
377 0 : m_Variables[VAR_POSITION_Y] = std::make_unique<CParticleVarConstant>(0.f);
378 0 : m_Variables[VAR_POSITION_Z] = std::make_unique<CParticleVarConstant>(0.f);
379 0 : m_Variables[VAR_ANGLE] = std::make_unique<CParticleVarConstant>(0.f);
380 0 : m_Variables[VAR_VELOCITY_X] = std::make_unique<CParticleVarConstant>(0.f);
381 0 : m_Variables[VAR_VELOCITY_Y] = std::make_unique<CParticleVarConstant>(1.f);
382 0 : m_Variables[VAR_VELOCITY_Z] = std::make_unique<CParticleVarConstant>(0.f);
383 0 : m_Variables[VAR_VELOCITY_ANGLE] = std::make_unique<CParticleVarConstant>(0.f);
384 0 : m_Variables[VAR_SIZE] = std::make_unique<CParticleVarConstant>(1.f);
385 0 : m_Variables[VAR_SIZE_GROWTHRATE] = std::make_unique<CParticleVarConstant>(0.f);
386 0 : m_Variables[VAR_COLOR_R] = std::make_unique<CParticleVarConstant>(1.f);
387 0 : m_Variables[VAR_COLOR_G] = std::make_unique<CParticleVarConstant>(1.f);
388 0 : m_Variables[VAR_COLOR_B] = std::make_unique<CParticleVarConstant>(1.f);
389 0 : m_BlendMode = BlendMode::ADD;
390 0 : m_SortMode = SortMode::UNSPECIFIED;
391 0 : m_StartFull = false;
392 0 : m_UseLocalSpace = false;
393 0 : m_UseRelativePosition = false;
394 0 : m_UseRelativeVelocity = false;
395 0 : m_Texture = g_Renderer.GetTextureManager().GetErrorTexture();
396 :
397 0 : CXeromyces XeroFile;
398 0 : PSRETURN ret = XeroFile.Load(g_VFS, path, "particle");
399 0 : if (ret != PSRETURN_OK)
400 : {
401 0 : LOGERROR("Failed to load particle: '{}'", path.string8());
402 0 : return false;
403 : }
404 :
405 : // Define all the elements and attributes used in the XML file
406 : #define EL(x) int el_##x = XeroFile.GetElementID(#x)
407 : #define AT(x) int at_##x = XeroFile.GetAttributeID(#x)
408 0 : EL(blend);
409 0 : EL(constant);
410 0 : EL(copy);
411 0 : EL(expr);
412 0 : EL(force);
413 0 : EL(fixed_orientation);
414 0 : EL(particle);
415 0 : EL(sort);
416 0 : EL(start_full);
417 0 : EL(texture);
418 0 : EL(uniform);
419 0 : EL(use_local_space);
420 0 : EL(use_relative_position);
421 0 : EL(use_relative_velocity);
422 0 : AT(from);
423 0 : AT(max);
424 0 : AT(min);
425 0 : AT(mode);
426 0 : AT(mul);
427 0 : AT(name);
428 0 : AT(value);
429 0 : AT(x);
430 0 : AT(y);
431 0 : AT(z);
432 : #undef AT
433 : #undef EL
434 :
435 0 : XMBElement Root = XeroFile.GetRoot();
436 :
437 0 : for (XMBElement Child : Root.GetChildNodes())
438 : {
439 0 : if (Child.GetNodeName() == el_texture)
440 : {
441 0 : CTextureProperties textureProps(Child.GetText().FromUTF8());
442 0 : textureProps.SetAddressMode(
443 : Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
444 0 : m_Texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
445 0 : }
446 0 : else if (Child.GetNodeName() == el_blend)
447 : {
448 0 : const CStr mode = Child.GetAttributes().GetNamedItem(at_mode);
449 0 : if (mode == "add")
450 0 : m_BlendMode = BlendMode::ADD;
451 0 : else if (mode == "subtract")
452 0 : m_BlendMode = BlendMode::SUBTRACT;
453 0 : else if (mode == "over")
454 0 : m_BlendMode = BlendMode::OVERLAY;
455 0 : else if (mode == "multiply")
456 0 : m_BlendMode = BlendMode::MULTIPLY;
457 0 : }
458 0 : else if (Child.GetNodeName() == el_sort)
459 : {
460 0 : const CStr mode{Child.GetAttributes().GetNamedItem(at_mode)};
461 0 : if (mode == "closest_in_front")
462 0 : m_SortMode = SortMode::CLOSEST_IN_FRONT;
463 0 : else if (mode == "youngest_in_front")
464 0 : m_SortMode = SortMode::YOUNGEST_IN_FRONT;
465 0 : else if (mode == "oldest_in_front")
466 0 : m_SortMode = SortMode::OLDEST_IN_FRONT;
467 0 : }
468 0 : else if (Child.GetNodeName() == el_start_full)
469 : {
470 0 : m_StartFull = true;
471 : }
472 0 : else if (Child.GetNodeName() == el_use_local_space)
473 : {
474 0 : m_UseLocalSpace = true;
475 : }
476 0 : else if (Child.GetNodeName() == el_use_relative_position)
477 : {
478 0 : m_UseRelativePosition = true;
479 : }
480 0 : else if (Child.GetNodeName() == el_use_relative_velocity)
481 : {
482 0 : m_UseRelativeVelocity = true;
483 : }
484 0 : else if (Child.GetNodeName() == el_constant)
485 : {
486 0 : int id = GetVariableID(Child.GetAttributes().GetNamedItem(at_name));
487 0 : if (id != -1)
488 : {
489 0 : m_Variables[id] = std::make_unique<CParticleVarConstant>(
490 0 : Child.GetAttributes().GetNamedItem(at_value).ToFloat()
491 0 : );
492 : }
493 : }
494 0 : else if (Child.GetNodeName() == el_uniform)
495 : {
496 0 : int id = GetVariableID(Child.GetAttributes().GetNamedItem(at_name));
497 0 : if (id != -1)
498 : {
499 0 : float min = Child.GetAttributes().GetNamedItem(at_min).ToFloat();
500 0 : float max = Child.GetAttributes().GetNamedItem(at_max).ToFloat();
501 : // To avoid hangs in the RNG, only use it if [min, max) is non-empty
502 0 : if (min < max)
503 0 : m_Variables[id] = std::make_unique<CParticleVarUniform>(min, max);
504 : else
505 0 : m_Variables[id] = std::make_unique<CParticleVarConstant>(min);
506 : }
507 : }
508 0 : else if (Child.GetNodeName() == el_copy)
509 : {
510 0 : int id = GetVariableID(Child.GetAttributes().GetNamedItem(at_name));
511 0 : int from = GetVariableID(Child.GetAttributes().GetNamedItem(at_from));
512 0 : if (id != -1 && from != -1)
513 0 : m_Variables[id] = std::make_unique<CParticleVarCopy>(from);
514 : }
515 0 : else if (Child.GetNodeName() == el_expr)
516 : {
517 0 : int id = GetVariableID(Child.GetAttributes().GetNamedItem(at_name));
518 0 : CStr from = Child.GetAttributes().GetNamedItem(at_from);
519 0 : float mul = Child.GetAttributes().GetNamedItem(at_mul).ToFloat();
520 0 : float max = Child.GetAttributes().GetNamedItem(at_max).ToFloat();
521 0 : if (id != -1)
522 0 : m_Variables[id] = std::make_unique<CParticleVarExpr>(from, mul, max);
523 0 : }
524 0 : else if (Child.GetNodeName() == el_force)
525 : {
526 0 : float x = Child.GetAttributes().GetNamedItem(at_x).ToFloat();
527 0 : float y = Child.GetAttributes().GetNamedItem(at_y).ToFloat();
528 0 : float z = Child.GetAttributes().GetNamedItem(at_z).ToFloat();
529 0 : m_Effectors.push_back(std::make_unique<CParticleEffectorForce>(x, y, z));
530 : }
531 0 : else if (Child.GetNodeName() == el_particle)
532 : {
533 0 : for (XMBElement particleChild : Child.GetChildNodes())
534 : {
535 0 : if (particleChild.GetNodeName() == el_fixed_orientation)
536 : {
537 0 : CVector3D axis{
538 0 : particleChild.GetAttributes().GetNamedItem(at_x).ToFloat(),
539 0 : particleChild.GetAttributes().GetNamedItem(at_y).ToFloat(),
540 0 : particleChild.GetAttributes().GetNamedItem(at_z).ToFloat()};
541 : // The axis must be a non-zero vector else it's not valid.
542 0 : const float axisLength{axis.Length()};
543 0 : if (axisLength > 0.0f)
544 0 : axis *= 1.0f / axisLength;
545 : else
546 0 : axis = CVector3D{0.0f, 0.0f, 0.0f};
547 0 : if (particleChild.GetAttributes().GetNamedItem(at_name) == "axisX")
548 : {
549 0 : m_AxisX = axis;
550 0 : m_UseRelativeAxisX = particleChild.GetAttributes().GetNamedItem(at_mode) == "relative";
551 0 : m_UseVelocityAsAxisX = particleChild.GetAttributes().GetNamedItem(at_mode) == "velocity";
552 : }
553 0 : else if (particleChild.GetAttributes().GetNamedItem(at_name) == "axisY")
554 : {
555 0 : m_AxisY = axis;
556 0 : m_UseRelativeAxisY = particleChild.GetAttributes().GetNamedItem(at_mode) == "relative";
557 : }
558 : }
559 : }
560 : }
561 : }
562 :
563 0 : return true;
564 0 : }
565 :
566 0 : void CParticleEmitterType::UpdateEmitter(CParticleEmitter& emitter, float dt) const
567 : {
568 : // If dt is very large, we should do the update in multiple small
569 : // steps to prevent all the particles getting clumped together at
570 : // low framerates
571 :
572 0 : const float maxStepLength = 0.2f;
573 :
574 : // Avoid wasting time by computing periods longer than the lifetime
575 : // period of the particles
576 0 : dt = std::min(dt, m_MaxLifetime);
577 :
578 0 : while (dt > maxStepLength)
579 : {
580 0 : UpdateEmitterStep(emitter, maxStepLength);
581 0 : dt -= maxStepLength;
582 : }
583 :
584 0 : UpdateEmitterStep(emitter, dt);
585 0 : }
586 :
587 0 : void CParticleEmitterType::UpdateEmitterStep(CParticleEmitter& emitter, float dt) const
588 : {
589 0 : ENSURE(&emitter.m_Type == this);
590 :
591 0 : if (emitter.m_Active)
592 : {
593 0 : float emissionRate = m_Variables[VAR_EMISSIONRATE]->Evaluate(emitter);
594 :
595 : // Find how many new particles to spawn, and accumulate any rounding errors
596 : // (to maintain a constant emission rate even if dt is very small)
597 0 : int newParticles = floor(emitter.m_EmissionRoundingError + dt*emissionRate);
598 0 : emitter.m_EmissionRoundingError += dt*emissionRate - newParticles;
599 :
600 : // If dt was very large, there's no point spawning new particles that
601 : // we'll immediately overwrite, so clamp it
602 0 : newParticles = std::min(newParticles, (int)m_MaxParticles);
603 :
604 0 : const CMatrix3D rotationMatrix{emitter.GetRotation().ToMatrix()};
605 0 : const CVector3D axisX{!m_UseLocalSpace && m_UseRelativeAxisX ? rotationMatrix.Transform(m_AxisX) : m_AxisX};
606 0 : const CVector3D axisY{!m_UseLocalSpace && m_UseRelativeAxisY ? rotationMatrix.Transform(m_AxisY) : m_AxisY};
607 :
608 0 : for (int i = 0; i < newParticles; ++i)
609 : {
610 : // Compute new particle state based on variables
611 0 : SParticle particle;
612 :
613 0 : particle.pos.X = m_Variables[VAR_POSITION_X]->Evaluate(emitter);
614 0 : particle.pos.Y = m_Variables[VAR_POSITION_Y]->Evaluate(emitter);
615 0 : particle.pos.Z = m_Variables[VAR_POSITION_Z]->Evaluate(emitter);
616 :
617 0 : particle.velocity.X = m_Variables[VAR_VELOCITY_X]->Evaluate(emitter);
618 0 : particle.velocity.Y = m_Variables[VAR_VELOCITY_Y]->Evaluate(emitter);
619 0 : particle.velocity.Z = m_Variables[VAR_VELOCITY_Z]->Evaluate(emitter);
620 :
621 0 : if (!m_UseLocalSpace)
622 : {
623 0 : if (m_UseRelativeVelocity)
624 0 : particle.velocity = rotationMatrix.Transform(particle.velocity);
625 0 : if (m_UseRelativePosition)
626 0 : particle.pos = rotationMatrix.Transform(particle.pos);
627 0 : particle.pos += emitter.m_Pos;
628 : }
629 :
630 0 : particle.angle = m_Variables[VAR_ANGLE]->Evaluate(emitter);
631 0 : particle.angleSpeed = m_Variables[VAR_VELOCITY_ANGLE]->Evaluate(emitter);
632 :
633 0 : particle.size = m_Variables[VAR_SIZE]->Evaluate(emitter);
634 0 : particle.sizeGrowthRate = m_Variables[VAR_SIZE_GROWTHRATE]->Evaluate(emitter);
635 :
636 0 : RGBColor color;
637 0 : color.X = m_Variables[VAR_COLOR_R]->Evaluate(emitter);
638 0 : color.Y = m_Variables[VAR_COLOR_G]->Evaluate(emitter);
639 0 : color.Z = m_Variables[VAR_COLOR_B]->Evaluate(emitter);
640 0 : particle.color = ConvertRGBColorTo4ub(color);
641 :
642 0 : particle.age = 0.f;
643 0 : particle.maxAge = m_Variables[VAR_LIFETIME]->Evaluate(emitter);
644 :
645 0 : particle.axisX = axisX;
646 0 : particle.axisY = axisY;
647 :
648 0 : if (m_UseVelocityAsAxisX)
649 : {
650 0 : const float velocityLength{particle.velocity.Length()};
651 0 : if (velocityLength > 1e-3f)
652 0 : particle.axisX = particle.velocity * (1.0f / velocityLength);
653 : }
654 :
655 0 : emitter.AddParticle(particle);
656 : }
657 : }
658 :
659 : // Update particle states
660 0 : for (size_t i = 0; i < emitter.m_Particles.size(); ++i)
661 : {
662 0 : SParticle& p = emitter.m_Particles[i];
663 :
664 : // Don't bother updating particles already at the end of their life
665 0 : if (p.age > p.maxAge)
666 0 : continue;
667 :
668 0 : p.pos += p.velocity * dt;
669 0 : p.angle += p.angleSpeed * dt;
670 0 : p.age += dt;
671 0 : p.size += p.sizeGrowthRate * dt;
672 :
673 0 : if (m_UseVelocityAsAxisX)
674 : {
675 0 : const float velocityLength{p.velocity.Length()};
676 0 : if (velocityLength > 1e-3f)
677 0 : p.axisX = p.velocity * (1.0f / velocityLength);
678 : }
679 :
680 : // Make alpha fade in/out nicely
681 : // TODO: this should probably be done as a variable or something,
682 : // instead of hardcoding
683 0 : float ageFrac = p.age / p.maxAge;
684 0 : float a = std::min(1.f - ageFrac, 5.f * ageFrac);
685 0 : p.color.A = Clamp(static_cast<int>(a * 255.f), 0, 255);
686 : }
687 :
688 0 : for (size_t i = 0; i < m_Effectors.size(); ++i)
689 : {
690 0 : m_Effectors[i]->Evaluate(emitter.m_Particles, dt);
691 : }
692 0 : }
693 :
694 0 : CBoundingBoxAligned CParticleEmitterType::CalculateBounds(CVector3D emitterPos, CBoundingBoxAligned emittedBounds) const
695 : {
696 0 : CBoundingBoxAligned bounds = m_MaxBounds;
697 0 : bounds[0] += emitterPos;
698 0 : bounds[1] += emitterPos;
699 :
700 0 : bounds += emittedBounds;
701 :
702 : // The current bounds is for the particles' centers, so expand by
703 : // sqrt(2) * max_size/2 to ensure any rotated billboards fit in
704 0 : bounds.Expand(m_Variables[VAR_SIZE]->Max(*this)/2.f * sqrt(2.f));
705 :
706 0 : return bounds;
707 : }
|