Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/new_class_id/src/lib/particles/particle_system.cc @ 9715

Last change on this file since 9715 was 9715, checked in by bensch, 18 years ago

renamed newclassid to classid and newobjectlist to objectlist

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