Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/particles/particle_system.cc @ 7320

Last change on this file since 7320 was 7301, checked in by bensch, 19 years ago

less debug, and music should rewind now

File size: 14.0 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11   ### File Specific:
12   main-programmer: Benjamin Grauer
13   co-programmer: ...
14*/
15
16#define DEBUG_SPECIAL_MODULE DEBUG_MODULE_GRAPHICS
17
18#include "particle_system.h"
19
20#include "particle_emitter.h"
21
22#include "field.h"
23#include "model.h"
24
25#include "util/loading/load_param.h"
26#include "util/loading/factory.h"
27#include "material.h"
28#include "state.h"
29#include "shell_command.h"
30
31#include "parser/tinyxml/tinyxml.h"
32#include <algorithm>
33
34using namespace std;
35/**
36 *  standard constructor
37 * @param maxCount the Count of particles in the System
38 * @param type The Type of the ParticleSystem
39*/
40ParticleSystem::ParticleSystem (unsigned int maxCount)
41{
42  this->setClassID(CL_PARTICLE_SYSTEM, "ParticleSystem");
43
44  this->setMaxCount(PARTICLE_DEFAULT_MAX_COUNT);
45  this->count = 0;
46  this->particles = NULL;
47  this->deadList = NULL;
48  this->conserve = 1.0;
49  this->lifeSpan = 1.0; this->randomLifeSpan = 0.0;
50
51  this->toList(OM_ENVIRON);
52
53  this->maxCount = maxCount;
54}
55
56/**
57 *  standard deconstructor
58*/
59ParticleSystem::~ParticleSystem()
60{
61  // deleting all the living Particles
62  while (this->particles)
63  {
64    Particle* tmpDelPart = this->particles;
65    this->particles = this->particles->next;
66    delete tmpDelPart;
67  }
68
69  // deleting all the dead particles
70  while (this->deadList)
71  {
72    Particle* tmpDelPart = this->deadList;
73    this->deadList = this->deadList->next;
74    delete tmpDelPart;
75  }
76
77  while(!this->emitters.empty())
78  {
79    this->removeEmitter(this->emitters.front());
80  }
81
82}
83
84
85/**
86 * loads Parameters from a TiXmlElement
87 * @param root the XML-element to load from.
88 */
89void ParticleSystem::loadParams(const TiXmlElement* root)
90{
91  WorldEntity::loadParams(root);
92  PhysicsInterface::loadParams(root);
93
94  LoadParam(root, "max-count", this, ParticleSystem, setMaxCount)
95  .describe("the maximal count of Particles, that can be emitted into this system");
96
97  LoadParam(root, "life-span", this, ParticleSystem, setLifeSpan)
98  .describe("sets the life-span of the Particles.");
99
100  LoadParam(root, "conserve", this, ParticleSystem, setConserve)
101  .describe("sets the Conserve factor of the Particles (1.0: they keep all their energy, 0.0:they keep no energy)");
102
103  LoadParamXML(root, "emitters", this, ParticleSystem, loadEmitters);
104
105  LOAD_PARAM_START_CYCLE(root, element);
106  {
107    element->ToText();
108    // PER-PARTICLE-ATTRIBUTES:
109    LoadParam_CYCLE(element, "radius", this, ParticleSystem, setRadius)
110    .describe("The Radius of each particle over time (TimeIndex [0-1], radius at TimeIndex, randomRadius at TimeIndex)");
111
112    LoadParam_CYCLE(element, "mass", this, ParticleSystem, setMass)
113    .describe("The Mass of each particle over time (TimeIndex: [0-1], mass at TimeIndex, randomMass at TimeIndex)");
114
115    LoadParam_CYCLE(element, "color", this, ParticleSystem, setColor)
116    .describe("The Color of each particle over time (TimeIndex: [0-1], red: [0-1], green: [0-1], blue: [0-1], alpha: [0-1])");
117  }
118  LOAD_PARAM_END_CYCLE(element);
119
120  LoadParam(root, "precache", this, ParticleSystem, precache)
121  .describe("Precaches the ParticleSystem for %1 seconds, %2 times per Second")
122  .defaultValues(1.0, 25.0);
123}
124
125/**
126 * @brief loads the Emitters from An XML-Root
127 * @param root the XML-Element to load all emitters from
128 */
129void ParticleSystem::loadEmitters(const TiXmlElement* root)
130{
131  LOAD_PARAM_START_CYCLE(root, element);
132  {
133    BaseObject* emitter = Factory::fabricate(element);
134    if (emitter != NULL)
135    {
136      if (emitter->isA(CL_PARTICLE_EMITTER))
137        this->addEmitter(dynamic_cast<ParticleEmitter*>(emitter));
138      else
139      {
140        PRINTF(2)("Tried to load an Element of type '%s' that should be a ParticleEmitter onto '%s::%s'.\n",
141                  emitter->getClassName(), this->getClassName(), this->getName());
142        delete emitter;
143      }
144    }
145    else
146    {
147      PRINTF(2)("Could not Generate Emitter for system %s::%s (wrong type in XML-format)\n", this->getClassName(), getName());
148    }
149  }
150  LOAD_PARAM_END_CYCLE(element);
151}
152
153/**
154 * @param maxCount the maximum count of particles that can be emitted
155 */
156void ParticleSystem::setMaxCount(unsigned int maxCount)
157{
158  this->maxCount = maxCount;
159  PRINTF(4)("MAXCOUNT of %s::%s is %d\n", this->getClassName(), this->getName(),maxCount);
160}
161
162// setting properties
163/**
164 * @brief Sets the lifespan of newly created particles
165 * @param lifeSpan the LifeSpan of each particle in the System
166 * @param randomLifeSpan the Deviation from lifeSpan (random Value).
167*/
168void ParticleSystem::setLifeSpan(float lifeSpan, float randomLifeSpan)
169{
170  this->lifeSpan = lifeSpan;
171  this->randomLifeSpan = randomLifeSpan;
172  PRINTF(4)("LifeTime of %s::%s is %f\n", this->getClassName(), this->getName(), lifeSpan);
173}
174
175/**
176 * @brief sets the conserve Factor of newly created particles
177 * @param conserve sets the conserve factor of each particle.
178 * Conserve is the ammount of energy a particle takes from the last Frame into the next.
179 * A Value of 1 means, that all energy is conserved, a Value of 0 means infinit friction.
180 */
181void ParticleSystem::setConserve(float conserve)
182{
183  if (conserve > 1.0)
184    this->conserve = 1.0;
185  else if (conserve < 0.0)
186    this->conserve = 0.0;
187  else
188    this->conserve = conserve;
189
190  PRINTF(4)("Conserve of %s::%s is %f\n", this->getClassName(), this->getName(),conserve);
191}
192
193/////////////////////////////
194/* Per-Particle Attributes */
195/////////////////////////////
196/**
197 * @brief sets a key in the radius-animation on a per-particle basis
198 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
199 * @param radius the radius at this position
200 * @param randRadius the randRadius at this position
201*/
202void ParticleSystem::setRadius(float lifeCycleTime, float radius, float randRadius)
203{
204  this->radiusAnim.changeEntry(lifeCycleTime, radius);
205  this->randRadiusAnim.changeEntry(lifeCycleTime, randRadius);
206
207  PRINTF(4)("Radius of %s::%s at timeSlice %f is %f with a Random of %f\n",
208    this->getClassName(), this->getName(),lifeCycleTime, radius, randRadius);
209}
210
211/**
212 * @brief sets a key in the mass-animation on a per-particle basis
213 * @param lifeCycleTime the time (partilceLifeTime/particleAge) [0-1]
214 * @param mass the mass at this position
215 * @param randMass the randomMass at this position
216*/
217void ParticleSystem::setMass(float lifeCycleTime, float mass, float randMass)
218{
219  this->massAnim.changeEntry(lifeCycleTime, mass);
220  this->randMassAnim.changeEntry(lifeCycleTime, randMass);
221}
222
223/**
224 * @brief sets a key in the color-animation on a per-particle basis
225 * @param lifeCycleTime: the time (partilceLifeTime/particleAge) [0-1]
226 * @param red: red
227 * @param green: green
228 * @param blue: blue
229 * @param alpha: alpha
230*/
231void ParticleSystem::setColor(float lifeCycleTime, float red, float green, float blue, float alpha)
232{
233  this->colorAnim[0].changeEntry(lifeCycleTime, red);
234  this->colorAnim[1].changeEntry(lifeCycleTime, green);
235  this->colorAnim[2].changeEntry(lifeCycleTime, blue);
236  this->colorAnim[3].changeEntry(lifeCycleTime, alpha);
237
238  PRINTF(4)("Color of %s::%s on timeslice %f is r:%f g:%f b:%f a:%f\n",
239    this->getClassName(), this->getName(), lifeCycleTime, red, green, blue, alpha);
240}
241
242/**
243 * @brief adds an Emitter to this System.
244 * @param emitter the Emitter to add.
245 */
246void ParticleSystem::addEmitter(ParticleEmitter* emitter)
247{
248  assert (emitter != NULL);
249  if (emitter->getSystem() != NULL)
250    emitter->getSystem()->removeEmitter(emitter);
251  emitter->system = this;
252  this->emitters.push_back(emitter);
253}
254
255/**
256 * @brief removes a ParticleEmitter from this System
257 * @param emitter the Emitter to remove
258 */
259void ParticleSystem::removeEmitter(ParticleEmitter* emitter)
260{
261  assert (emitter != NULL);
262  emitter->system = NULL;
263  this->emitters.remove(emitter);
264  /*  std::list<ParticleEmitter*>::iterator it = std::find(this->emitters.begin(), this->emitters.end(), emitter);
265  if (it != this->emitters.end())
266    this->emitters.erase(it);*/
267}
268
269/**
270 * @brief does a Precaching, meaning, that the ParticleSystem(and its emitters) will be ticked force
271 * @param seconds: seconds
272 * @param ticksPerSeconds times per Second.
273 */
274void ParticleSystem::precache(unsigned int seconds, unsigned int ticksPerSecond)
275{
276  std::list<ParticleEmitter*>::iterator emitter;
277  for (emitter = this->emitters.begin(); emitter != this->emitters.end(); emitter++)
278    (*emitter)->updateNode(.1), (*emitter)->updateNode(.1);
279
280  PRINTF(4)("Precaching %s::%s %d seconds %d timesPerSecond\n", this->getClassName(), this->getName(), seconds, ticksPerSecond);
281  this->debug();
282  for (unsigned int i = 0; i < seconds*ticksPerSecond; i++)
283    this->tick(1.0/(float)ticksPerSecond);
284}
285
286
287/**
288 * @brief ticks the system.
289 * @param dt the time to tick all the Particles of the System
290
291   this is used to get all the particles some motion
292*/
293void ParticleSystem::tick(float dt)
294{
295  Particle* tickPart = particles;  // the particle to Tick
296  Particle* prevPart = NULL;
297  while (likely(tickPart != NULL))
298  {
299    // applying force to the System.
300    if (likely (tickPart->mass > 0.0))
301      tickPart->velocity += tickPart->extForce / tickPart->mass * dt;
302
303    tickPart->radius = radiusAnim.getValue(tickPart->lifeCycle)
304                       + randRadiusAnim.getValue(tickPart->lifeCycle) * tickPart->radiusRand;
305
306    tickPart->mass = massAnim.getValue(tickPart->lifeCycle)
307                     + randMassAnim.getValue(tickPart->lifeCycle) * tickPart->massRand;
308
309    tickPart->extForce = Vector(0,0,0);
310
311    // applying Color
312    tickPart->color[0] = this->colorAnim[0].getValue(tickPart->lifeCycle);
313    tickPart->color[1] = this->colorAnim[1].getValue(tickPart->lifeCycle);
314    tickPart->color[2] = this->colorAnim[2].getValue(tickPart->lifeCycle);
315    tickPart->color[3] = this->colorAnim[3].getValue(tickPart->lifeCycle);
316
317    // rendering new position.
318    tickPart->position += tickPart->velocity * dt;
319    tickPart->orientation *= tickPart->momentum *dt;
320
321    // many more to come
322
323    if (this->conserve < 1.0)
324    {
325      tickPart->velocity *= this->conserve;
326      tickPart->momentum *= this->conserve;
327    }
328    // find out if we have to delete tickPart
329    if (unlikely((tickPart->lifeCycle += dt/tickPart->lifeTime) >= 1.0))
330    {
331      // remove the particle from the list
332      if (likely(prevPart != NULL))
333      {
334        prevPart->next = tickPart->next;
335        tickPart->next = this->deadList;
336        this->deadList = tickPart;
337        tickPart = prevPart->next;
338      }
339      else
340      {
341        prevPart = NULL;
342        this->particles = tickPart->next;
343        tickPart->next = this->deadList;
344        this->deadList = tickPart;
345        tickPart = this->particles;
346      }
347      --this->count;
348    }
349    else
350    {
351      prevPart = tickPart;
352      tickPart = tickPart->next;
353    }
354  }
355
356  std::list<ParticleEmitter*>::iterator emitter;
357  for (emitter = this->emitters.begin(); emitter != this->emitters.end(); emitter++)
358    (*emitter)->tick(dt);
359}
360
361/**
362  *  applies some force to a Particle.
363  * @param field the Field to apply.
364 */
365void ParticleSystem::applyField(const Field* field)
366{
367  Particle* tickPart = particles;
368  while (tickPart)
369  {
370    tickPart->extForce += field->calcForce(tickPart->position);
371    tickPart = tickPart->next;
372  }
373}
374
375
376/**
377 * @returns the count of Faces of this ParticleSystem
378 */
379unsigned int ParticleSystem::getFaceCount() const
380{
381  return this->count;
382}
383
384/**
385 * @brief adds a new Particle to the System
386 * @param position the initial position, where the particle gets emitted.
387 * @param velocity the initial velocity of the particle.
388 * @param orientation the initial orientation of the Paritcle.
389 * @param momentum the initial momentum of the Particle (the speed of its rotation).
390 * @param data some more data given by the emitter
391*/
392void ParticleSystem::addParticle(const Vector& position, const Vector& velocity, const Quaternion& orientation, const Quaternion& momentum, unsigned int data)
393{
394  if (this->count <= this->maxCount)
395  {
396    // if it is the first Particle
397    if (unlikely(particles == NULL))
398    {
399      if (likely(deadList != NULL))
400      {
401        this->particles = this->deadList;
402        deadList = deadList->next;
403      }
404      else
405      {
406        PRINTF(5)("Generating new Particle\n");
407        this->particles = new Particle;
408      }
409      this->particles->next = NULL;
410    }
411    // filling the List from the beginning
412    else
413    {
414      Particle* tmpPart;
415      if (likely(deadList != NULL))
416      {
417        tmpPart = this->deadList;
418        deadList = deadList->next;
419      }
420      else
421      {
422        PRINTF(5)("Generating new Particle\n");
423        tmpPart = new Particle;
424      }
425      tmpPart->next = this->particles;
426      this->particles = tmpPart;
427    }
428    particles->lifeTime = this->lifeSpan + (float)(rand()/RAND_MAX)* this->randomLifeSpan;
429    particles->lifeCycle = 0.0;
430    particles->position = position;
431    particles->velocity = velocity;
432
433    particles->orientation = orientation;
434    particles->momentum = momentum;
435
436    //  particle->rotation = ; //! @todo rotation is once again something to be done.
437    particles->massRand = 2*(float)rand()/RAND_MAX -1;
438    particles->radiusRand = 2* (float)rand()/RAND_MAX -1;
439    particles->mass = this->massAnim.getValue(0.0) + this->randMassAnim.getValue(0.0)*particles->massRand;
440    particles->radius = this->radiusAnim.getValue(0.0) + this->randRadiusAnim.getValue(0.0)*particles->radiusRand;
441
442    ++this->count;
443  }
444  else
445    PRINTF(4)("maximum count of particles reached not adding any more\n");
446}
447
448/**
449 *  outputs some nice debug information
450*/
451void ParticleSystem::debug() const
452{
453  PRINT(0)("  ParticleCount: %d emitters: %d, maximumCount: %d :: filled %d%%\n",
454           this->count,
455           this->emitters.size(),
456           this->maxCount,
457           ((this->maxCount!=0)?100*this->count/this->maxCount:0));
458  if (this->deadList)
459  {
460    PRINT(0)("  - ParticleDeadList is used: ");
461    int i = 1;
462    Particle* tmpPart = this->deadList;
463    while (tmpPart = tmpPart->next) ++i;
464    PRINT(0)("count: %d\n", i);
465  }
466}
Note: See TracBrowser for help on using the repository browser.