1 // particles.cxx - classes to manage particles
2 // started in 2008 by Tiago Gusmão, using animation.hxx as reference
3 // Copyright (C) 2008 Tiago Gusmão
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License as
7 // published by the Free Software Foundation; either version 2 of the
8 // License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful, but
11 // WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 # include <simgear_config.h>
24 #include <simgear/math/SGMath.hxx>
25 #include <simgear/math/SGGeod.hxx>
26 #include <simgear/misc/sg_path.hxx>
27 #include <simgear/props/props.hxx>
28 #include <simgear/props/props_io.hxx>
30 #include <osgParticle/SmokeTrailEffect>
31 #include <osgParticle/FireEffect>
32 #include <osgParticle/ConnectedParticleSystem>
33 #include <osgParticle/MultiSegmentPlacer>
34 #include <osgParticle/SectorPlacer>
35 #include <osgParticle/ConstantRateCounter>
36 #include <osgParticle/ParticleSystemUpdater>
37 #include <osgParticle/ParticleSystem>
38 #include <osgParticle/FluidProgram>
42 #include <osg/MatrixTransform>
45 #include "particles.hxx"
49 void GlobalParticleCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
52 = SGQuatd::fromLonLatDeg(modelRoot->getFloatValue("/position/longitude-deg",0),
53 modelRoot->getFloatValue("/position/latitude-deg",0));
54 osg::Matrix om(q.osg());
55 osg::Vec3 v(0,0,9.81);
56 gravity = om.preMult(v);
57 const osg::Vec3& zUpWind = Particles::getWindVector();
58 osg::Vec3 w(zUpWind.y(), zUpWind.x(), - zUpWind.z());
61 //SG_LOG(SG_GENERAL, SG_ALERT, "wind vector:"<<w[0]<<","<<w[1]<<","<<w[2]<<"\n");
66 osg::Vec3 GlobalParticleCallback::gravity;
67 osg::Vec3 GlobalParticleCallback::wind;
69 osg::ref_ptr<osg::Group> Particles::commonRoot;
70 osg::ref_ptr<osgParticle::ParticleSystemUpdater> Particles::psu = new osgParticle::ParticleSystemUpdater;
71 osg::ref_ptr<osg::Geode> Particles::commonGeode = new osg::Geode;;
72 osg::Vec3 Particles::_wind;
74 Particles::Particles() :
80 template <typename Object>
83 PointerGuard() : _ptr(0) {}
84 Object* get() { return _ptr; }
85 Object* operator () ()
95 osg::Group* Particles::getCommonRoot()
97 if(!commonRoot.valid())
99 SG_LOG(SG_GENERAL, SG_DEBUG, "Particle common root called!\n");
100 commonRoot = new osg::Group;
101 commonRoot.get()->setName("common particle system root");
102 commonGeode.get()->setName("common particle system geode");
103 commonRoot.get()->addChild(commonGeode.get());
104 commonRoot.get()->addChild(psu.get());
106 return commonRoot.get();
109 // Enable this once particle fix is in OSG.
110 // #define OSG_PARTICLE_FIX 1
111 void transformParticles(osgParticle::ParticleSystem* particleSys,
112 const osg::Matrix& mat)
114 const int numParticles = particleSys->numParticles();
115 if (particleSys->areAllParticlesDead())
117 for (int i = 0; i < numParticles; ++i) {
118 osgParticle::Particle* P = particleSys->getParticle(i);
121 P->transformPositionVelocity(mat);
125 osg::Group * Particles::appendParticles(const SGPropertyNode* configNode,
126 SGPropertyNode* modelRoot,
127 const osgDB::ReaderWriter::Options*
130 SG_LOG(SG_GENERAL, SG_DEBUG, "Setting up a particle system!\n");
132 osgParticle::ParticleSystem *particleSys;
134 //create a generic particle system
135 std::string type = configNode->getStringValue("type", "normal");
136 if (type == "normal")
137 particleSys = new osgParticle::ParticleSystem;
139 particleSys = new osgParticle::ConnectedParticleSystem;
140 //may not be used depending on the configuration
141 PointerGuard<Particles> callback;
143 getPSU()->addParticleSystem(particleSys);
144 getPSU()->setUpdateCallback(new GlobalParticleCallback(modelRoot));
145 //contains counter, placer and shooter by default
146 osgParticle::ModularEmitter* emitter = new osgParticle::ModularEmitter;
148 emitter->setParticleSystem(particleSys);
150 // Set up the alignment node ("stolen" from animation.cxx)
151 // XXX Order of rotations is probably not correct.
152 osg::MatrixTransform *align = new osg::MatrixTransform;
153 osg::Matrix res_matrix;
154 res_matrix.makeRotate(
155 configNode->getFloatValue("offsets/pitch-deg", 0.0)*SG_DEGREES_TO_RADIANS,
157 configNode->getFloatValue("offsets/roll-deg", 0.0)*SG_DEGREES_TO_RADIANS,
159 configNode->getFloatValue("offsets/heading-deg", 0.0)*SG_DEGREES_TO_RADIANS,
163 tmat.makeTranslate(configNode->getFloatValue("offsets/x-m", 0.0),
164 configNode->getFloatValue("offsets/y-m", 0.0),
165 configNode->getFloatValue("offsets/z-m", 0.0));
166 align->setMatrix(res_matrix * tmat);
168 align->setName("particle align");
170 //if (dynamic_cast<CustomModularEmitter*>(emitter)==0) SG_LOG(SG_GENERAL, SG_ALERT, "observer error\n");
171 //align->addObserver(dynamic_cast<CustomModularEmitter*>(emitter));
173 align->addChild(emitter);
175 //this name can be used in the XML animation as if it was a submodel
176 std::string name = configNode->getStringValue("name", "");
178 align->setName(name);
179 std::string attach = configNode->getStringValue("attach", "world");
180 if (attach == "local") { //local means attached to the model and not the world
181 osg::Geode* g = new osg::Geode;
183 g->addDrawable(particleSys);
184 #ifndef OSG_PARTICLE_FIX
185 emitter->setReferenceFrame(osgParticle::Emitter::ABSOLUTE_RF);
188 #ifdef OSG_PARTICLE_FIX
189 callback()->particleFrame = new osg::MatrixTransform();
190 osg::Geode* g = new osg::Geode;
191 g->addDrawable(particleSys);
192 callback()->particleFrame->addChild(g);
193 getCommonRoot()->addChild(callback()->particleFrame.get());
195 getCommonGeode()->addDrawable(particleSys);
198 std::string textureFile;
199 if (configNode->hasValue("texture")) {
200 //SG_LOG(SG_GENERAL, SG_ALERT,
201 // "requested:"<<configNode->getStringValue("texture","")<<"\n");
202 textureFile= osgDB::findFileInPath(configNode->getStringValue("texture",
204 options->getDatabasePathList());
205 //SG_LOG(SG_GENERAL, SG_ALERT, "found:"<<textureFile<<"\n");
207 //for(unsigned i = 0; i < options->getDatabasePathList().size(); ++i)
208 // SG_LOG(SG_GENERAL, SG_ALERT,
209 // "opts:"<<options->getDatabasePathList()[i]<<"\n");
212 particleSys->setDefaultAttributes(textureFile,
213 configNode->getBoolValue("emissive",
215 configNode->getBoolValue("lighting",
218 std::string alignstr = configNode->getStringValue("align", "billboard");
220 if (alignstr == "fixed")
221 particleSys->setParticleAlignment(osgParticle::ParticleSystem::FIXED);
223 const SGPropertyNode* placernode = configNode->getChild("placer");
226 std::string emitterType = placernode->getStringValue("type", "point");
228 if (emitterType == "sector") {
229 osgParticle::SectorPlacer *splacer = new osgParticle::SectorPlacer;
230 float minRadius, maxRadius, minPhi, maxPhi;
232 minRadius = placernode->getFloatValue("radius-min-m",0);
233 maxRadius = placernode->getFloatValue("radius-max-m",1);
234 minPhi = (placernode->getFloatValue("phi-min-deg",0)
235 * SG_DEGREES_TO_RADIANS);
236 maxPhi = (placernode->getFloatValue("phi-max-deg",360.0f)
237 * SG_DEGREES_TO_RADIANS);
239 splacer->setRadiusRange(minRadius, maxRadius);
240 splacer->setPhiRange(minPhi, maxPhi);
241 emitter->setPlacer(splacer);
242 } else if (emitterType == "segments") {
243 std::vector<SGPropertyNode_ptr> segments
244 = placernode->getChildren("vertex");
245 if (segments.size()>1) {
246 osgParticle::MultiSegmentPlacer *msplacer
247 = new osgParticle::MultiSegmentPlacer();
250 for (unsigned i = 0; i < segments.size(); ++i) {
251 x = segments[i]->getFloatValue("x-m",0);
252 y = segments[i]->getFloatValue("y-m",0);
253 z = segments[i]->getFloatValue("z-m",0);
254 msplacer->addVertex(x, y, z);
256 emitter->setPlacer(msplacer);
258 SG_LOG(SG_GENERAL, SG_ALERT,
259 "Detected particle system using segment(s) with less than 2 vertices\n");
261 } //else the default placer in ModularEmitter is used (PointPlacer)
264 const SGPropertyNode* shnode = configNode->getChild("shooter");
267 float minTheta, maxTheta, minPhi, maxPhi, speed, spread;
269 minTheta = (shnode->getFloatValue("theta-min-deg",0)
270 * SG_DEGREES_TO_RADIANS);
271 maxTheta = (shnode->getFloatValue("theta-max-deg",360.0f)
272 * SG_DEGREES_TO_RADIANS);
273 minPhi = shnode->getFloatValue("phi-min-deg",0)* SG_DEGREES_TO_RADIANS;
274 maxPhi = (shnode->getFloatValue("phi-max-deg",360.0f)
275 * SG_DEGREES_TO_RADIANS);
277 osgParticle::RadialShooter *shooter = new osgParticle::RadialShooter;
278 emitter->setShooter(shooter);
280 shooter->setThetaRange(minTheta, maxTheta);
281 shooter->setPhiRange(minPhi, maxPhi);
283 const SGPropertyNode* speednode = shnode->getChild("speed-mps");
286 if (speednode->hasValue("value")) {
287 speed = speednode->getFloatValue("value",0);
288 spread = speednode->getFloatValue("spread",0);
289 shooter->setInitialSpeedRange(speed-spread, speed+spread);
291 callback()->setupShooterSpeedData(speednode, modelRoot);
295 const SGPropertyNode* rotspeednode = shnode->getChild("rotation-speed");
298 float x1,y1,z1,x2,y2,z2;
299 x1 = rotspeednode->getFloatValue("x-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
300 y1 = rotspeednode->getFloatValue("y-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
301 z1 = rotspeednode->getFloatValue("z-min-deg-sec",0) * SG_DEGREES_TO_RADIANS;
302 x2 = rotspeednode->getFloatValue("x-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
303 y2 = rotspeednode->getFloatValue("y-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
304 z2 = rotspeednode->getFloatValue("z-max-deg-sec",0) * SG_DEGREES_TO_RADIANS;
305 shooter->setInitialRotationalSpeedRange(osg::Vec3f(x1,y1,z1), osg::Vec3f(x2,y2,z2));
307 } //else ModularEmitter uses the default RadialShooter
310 const SGPropertyNode* conditionNode = configNode->getChild("condition");
311 const SGPropertyNode* counternode = configNode->getChild("counter");
313 if (conditionNode || counternode) {
314 osgParticle::RandomRateCounter* counter
315 = new osgParticle::RandomRateCounter;
316 emitter->setCounter(counter);
317 float pps = 0.0f, spread = 0.0f;
320 const SGPropertyNode* ppsnode = counternode->getChild("particles-per-sec");
322 if (ppsnode->hasValue("value")) {
323 pps = ppsnode->getFloatValue("value",0);
324 spread = ppsnode->getFloatValue("spread",0);
325 counter->setRateRange(pps-spread, pps+spread);
327 callback()->setupCounterData(ppsnode, modelRoot);
333 callback()->setupCounterCondition(conditionNode, modelRoot);
334 callback()->setupCounterCondition(pps, spread);
336 } //TODO: else perhaps set higher values than default?
338 const SGPropertyNode* particlenode = configNode->getChild("particle");
340 osgParticle::Particle &particle
341 = particleSys->getDefaultParticleTemplate();
342 float r1=0, g1=0, b1=0, a1=1, r2=0, g2=0, b2=0, a2=1;
343 const SGPropertyNode* startcolornode
344 = particlenode->getNode("start/color");
345 if (startcolornode) {
346 const SGPropertyNode* componentnode
347 = startcolornode->getChild("red");
349 if (componentnode->hasValue("value"))
350 r1 = componentnode->getFloatValue("value",0);
352 callback()->setupColorComponent(componentnode, modelRoot,
355 componentnode = startcolornode->getChild("green");
357 if (componentnode->hasValue("value"))
358 g1 = componentnode->getFloatValue("value", 0);
360 callback()->setupColorComponent(componentnode, modelRoot,
363 componentnode = startcolornode->getChild("blue");
365 if (componentnode->hasValue("value"))
366 b1 = componentnode->getFloatValue("value",0);
368 callback()->setupColorComponent(componentnode, modelRoot,
371 componentnode = startcolornode->getChild("alpha");
373 if (componentnode->hasValue("value"))
374 a1 = componentnode->getFloatValue("value",0);
376 callback()->setupColorComponent(componentnode, modelRoot,
380 const SGPropertyNode* endcolornode = particlenode->getNode("end/color");
382 const SGPropertyNode* componentnode = endcolornode->getChild("red");
385 if (componentnode->hasValue("value"))
386 r2 = componentnode->getFloatValue("value",0);
388 callback()->setupColorComponent(componentnode, modelRoot,
391 componentnode = endcolornode->getChild("green");
393 if (componentnode->hasValue("value"))
394 g2 = componentnode->getFloatValue("value",0);
396 callback()->setupColorComponent(componentnode, modelRoot,
399 componentnode = endcolornode->getChild("blue");
401 if (componentnode->hasValue("value"))
402 b2 = componentnode->getFloatValue("value",0);
404 callback()->setupColorComponent(componentnode, modelRoot,
407 componentnode = endcolornode->getChild("alpha");
409 if (componentnode->hasValue("value"))
410 a2 = componentnode->getFloatValue("value",0);
412 callback()->setupColorComponent(componentnode, modelRoot,
416 particle.setColorRange(osgParticle::rangev4(osg::Vec4(r1,g1,b1,a1),
417 osg::Vec4(r2,g2,b2,a2)));
419 float startsize=1, endsize=0.1f;
420 const SGPropertyNode* startsizenode = particlenode->getNode("start/size");
422 if (startsizenode->hasValue("value"))
423 startsize = startsizenode->getFloatValue("value",0);
425 callback()->setupStartSizeData(startsizenode, modelRoot);
427 const SGPropertyNode* endsizenode = particlenode->getNode("end/size");
429 if (endsizenode->hasValue("value"))
430 endsize = endsizenode->getFloatValue("value",0);
432 callback()->setupEndSizeData(endsizenode, modelRoot);
434 particle.setSizeRange(osgParticle::rangef(startsize, endsize));
436 const SGPropertyNode* lifenode = particlenode->getChild("life-sec");
438 if (lifenode->hasValue("value"))
439 life = lifenode->getFloatValue("value",0);
441 callback()->setupLifeData(lifenode, modelRoot);
444 particle.setLifeTime(life);
445 if (particlenode->hasValue("radius-m"))
446 particle.setRadius(particlenode->getFloatValue("radius-m",0));
447 if (particlenode->hasValue("mass-kg"))
448 particle.setMass(particlenode->getFloatValue("mass-kg",0));
449 if (callback.get()) {
450 callback.get()->setupStaticColorComponent(r1, g1, b1, a1,
452 callback.get()->setupStaticSizeData(startsize, endsize);
454 //particle.setColorRange(osgParticle::rangev4( osg::Vec4(r1, g1, b1, a1), osg::Vec4(r2, g2, b2, a2)));
457 const SGPropertyNode* programnode = configNode->getChild("program");
458 osgParticle::FluidProgram *program = new osgParticle::FluidProgram();
461 std::string fluid = programnode->getStringValue("fluid", "air");
464 program->setFluidToAir();
466 program->setFluidToWater();
468 if (programnode->getBoolValue("gravity", true)) {
469 #ifdef OSG_PARTICLE_FIX
470 program->setToGravity();
472 if (attach == "world")
473 callback()->setupProgramGravity(true);
475 program->setToGravity();
478 program->setAcceleration(osg::Vec3(0,0,0));
480 if (programnode->getBoolValue("wind", true))
481 callback()->setupProgramWind(true);
483 program->setWind(osg::Vec3(0,0,0));
485 align->addChild(program);
487 program->setParticleSystem(particleSys);
490 if (callback.get()) { //this means we want property-driven changes
491 SG_LOG(SG_GENERAL, SG_DEBUG, "setting up particle system user data and callback\n");
492 //setup data and callback
493 callback.get()->setGeneralData(dynamic_cast<osgParticle::RadialShooter*>(emitter->getShooter()),
494 dynamic_cast<osgParticle::RandomRateCounter*>(emitter->getCounter()),
495 particleSys, program);
496 emitter->setUpdateCallback(callback.get());
502 void Particles::operator()(osg::Node* node, osg::NodeVisitor* nv)
504 //SG_LOG(SG_GENERAL, SG_ALERT, "callback!\n");
507 shooter->setInitialSpeedRange(shooterValue->getValue(),
508 (shooterValue->getValue()
509 + shooterExtraRange));
511 counter->setRateRange(counterValue->getValue(),
512 counterValue->getValue() + counterExtraRange);
513 else if (counterCond)
514 counter->setRateRange(counterStaticValue,
515 counterStaticValue + counterStaticExtraRange);
516 if (counterCond && !counterCond->test())
517 counter->setRateRange(0, 0);
518 bool colorchange=false;
519 for (int i = 0; i < 8; ++i) {
520 if (colorComponents[i]) {
521 staticColorComponents[i] = colorComponents[i]->getValue();
526 particleSys->getDefaultParticleTemplate().setColorRange(osgParticle::rangev4( Vec4(staticColorComponents[0], staticColorComponents[1], staticColorComponents[2], staticColorComponents[3]), Vec4(staticColorComponents[4], staticColorComponents[5], staticColorComponents[6], staticColorComponents[7])));
528 startSize = startSizeValue->getValue();
530 endSize = endSizeValue->getValue();
531 if (startSizeValue || endSizeValue)
532 particleSys->getDefaultParticleTemplate().setSizeRange(osgParticle::rangef(startSize, endSize));
534 particleSys->getDefaultParticleTemplate().setLifeTime(lifeValue->getValue());
535 #ifdef OSG_PARTICLE_FIX
536 if (particleFrame.valid()) {
537 MatrixList mlist = node->getWorldMatrices();
538 if (!mlist.empty()) {
539 const Matrix& particleMat = particleFrame->getMatrix();
540 Vec3d emitOrigin(mlist[0](3, 0), mlist[0](3, 1), mlist[0](3, 2));
542 = emitOrigin - Vec3d(particleMat(3, 0), particleMat(3, 1),
544 if (displace * displace > 10000.0 * 10000.0) {
545 // Make new frame for particle system, coincident with
546 // the emitter frame, but oriented with local Z.
547 SGGeod geod = SGGeod::fromCart(SGVec3d(emitOrigin));
548 Matrix newParticleMat = geod.makeZUpFrame();
549 Matrix changeParticleFrame
550 = particleMat * Matrix::inverse(newParticleMat);
551 particleFrame->setMatrix(newParticleMat);
552 transformParticles(particleSys.get(), changeParticleFrame);
556 if (program.valid() && useWind)
557 program->setWind(_wind);
559 if (program.valid()) {
561 program->setAcceleration(GlobalParticleCallback::getGravityVector());
563 program->setWind(GlobalParticleCallback::getWindVector());
567 } // namespace simgear