1 // animation.cxx - classes to manage model animation.
2 // Written by David Megginson, started 2002.
4 // This file is in the Public Domain, and comes with no warranty.
7 # include <simgear_config.h>
10 #include "SGMaterialAnimation.hxx"
12 #include <osg/AlphaFunc>
14 #include <osg/Drawable>
16 #include <osg/Geometry>
17 #include <osg/Material>
18 #include <osg/StateSet>
19 #include <osgDB/FileNameUtils>
20 #include <osgDB/FileUtils>
21 #include <osgDB/ReadFile>
23 #include <simgear/props/condition.hxx>
24 #include <simgear/props/props.hxx>
25 #include <simgear/scene/material/Effect.hxx>
26 #include <simgear/scene/material/EffectGeode.hxx>
27 #include <simgear/scene/material/Pass.hxx>
28 #include <simgear/scene/material/Technique.hxx>
29 #include <simgear/scene/model/model.hxx>
30 #include <simgear/scene/model/ConditionNode.hxx>
31 #include <simgear/scene/util/OsgMath.hxx>
34 using namespace simgear;
38 * Get a color from properties.
41 float red, green, blue;
44 SGPropertyNode_ptr red_prop;
45 SGPropertyNode_ptr green_prop;
46 SGPropertyNode_ptr blue_prop;
47 SGPropertyNode_ptr factor_prop;
48 SGPropertyNode_ptr offset_prop;
51 ColorSpec(const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
59 red = configNode->getFloatValue("red", -1.0);
60 green = configNode->getFloatValue("green", -1.0);
61 blue = configNode->getFloatValue("blue", -1.0);
62 factor = configNode->getFloatValue("factor", 1.0);
63 offset = configNode->getFloatValue("offset", 0.0);
67 const SGPropertyNode *node;
68 node = configNode->getChild("red-prop");
70 red_prop = modelRoot->getNode(node->getStringValue(), true);
71 node = configNode->getChild("green-prop");
73 green_prop = modelRoot->getNode(node->getStringValue(), true);
74 node = configNode->getChild("blue-prop");
76 blue_prop = modelRoot->getNode(node->getStringValue(), true);
77 node = configNode->getChild("factor-prop");
79 factor_prop = modelRoot->getNode(node->getStringValue(), true);
80 node = configNode->getChild("offset-prop");
82 offset_prop = modelRoot->getNode(node->getStringValue(), true);
86 return red >= 0 || green >= 0 || blue >= 0;
89 return red_prop || green_prop || blue_prop
90 || factor_prop || offset_prop;
94 red = red_prop->getFloatValue();
96 green = green_prop->getFloatValue();
98 blue = blue_prop->getFloatValue();
100 factor = factor_prop->getFloatValue();
102 offset = offset_prop->getFloatValue();
103 v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
104 v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
105 v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
112 return toOsg(rgba());
115 SGVec4f &initialRgba() {
116 v[0] = SGMiscf::clip(red*factor + offset, 0, 1);
117 v[1] = SGMiscf::clip(green*factor + offset, 0, 1);
118 v[2] = SGMiscf::clip(blue*factor + offset, 0, 1);
125 * Get a property value from a property.
133 SGPropertyNode_ptr value_prop;
134 SGPropertyNode_ptr factor_prop;
135 SGPropertyNode_ptr offset_prop;
137 PropSpec(const char* valueName, const char* valuePropName,
138 const SGPropertyNode* configNode, SGPropertyNode* modelRoot)
144 value = configNode->getFloatValue(valueName, -1);
145 factor = configNode->getFloatValue("factor", 1);
146 offset = configNode->getFloatValue("offset", 0);
147 min = configNode->getFloatValue("min", 0);
148 max = configNode->getFloatValue("max", 1);
152 const SGPropertyNode *node;
153 node = configNode->getChild(valuePropName);
155 value_prop = modelRoot->getNode(node->getStringValue(), true);
156 node = configNode->getChild("factor-prop");
158 factor_prop = modelRoot->getNode(node->getStringValue(), true);
159 node = configNode->getChild("offset-prop");
161 offset_prop = modelRoot->getNode(node->getStringValue(), true);
163 bool dirty() { return value >= 0.0; }
164 bool live() { return value_prop || factor_prop || offset_prop; }
168 value = value_prop->getFloatValue();
170 offset = offset_prop->getFloatValue();
172 factor = factor_prop->getFloatValue();
173 return SGMiscf::clip(value*factor + offset, min, max);
175 float getInitialValue()
177 return SGMiscf::clip(value*factor + offset, min, max);
182 * The possible color properties supplied by a material animation.
193 const unsigned AMBIENT_DIFFUSE = AMBIENT | DIFFUSE;
195 const int allMaterialColors = (DIFFUSE | AMBIENT | SPECULAR | EMISSION
198 // Visitor for finding default material colors in the animation node's
199 // subgraph. This makes some assumptions about the subgraph i.e.,
200 // there will be one material and one color value found. This is
201 // probably true for ac3d models and most uses of material animations,
202 // but will break down if, for example, you animate the transparency
203 // of a vertex colored model.
204 class MaterialDefaultsVisitor : public osg::NodeVisitor {
206 MaterialDefaultsVisitor()
207 : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN),
208 ambientDiffuse(-1.0f, -1.0f, -1.0f, -1.0f)
210 setVisitorType(osg::NodeVisitor::NODE_VISITOR);
213 virtual void apply(osg::Node& node)
215 maybeGetMaterialValues(node.getStateSet());
219 virtual void apply(osg::Geode& node)
221 using namespace simgear;
222 EffectGeode* eg = dynamic_cast<EffectGeode*>(&node);
224 const Effect* effect = eg->getEffect();
226 for (vector<osg::ref_ptr<Technique> >::const_iterator itr
227 = effect->techniques.begin(), end = effect->techniques.end();
230 const Technique* tniq = itr->get();
231 for (vector<osg::ref_ptr<Pass> >::const_iterator pitr
232 = tniq->passes.begin(), pend = tniq->passes.end();
235 maybeGetMaterialValues(pitr->get());
238 maybeGetMaterialValues(node.getStateSet());
240 int numDrawables = node.getNumDrawables();
241 for (int i = 0; i < numDrawables; i++) {
242 osg::Geometry* geom = dynamic_cast<osg::Geometry*>(node.getDrawable(i));
243 if (!geom || geom->getColorBinding() != osg::Geometry::BIND_OVERALL)
245 maybeGetMaterialValues(geom->getStateSet());
246 osg::Array* colorArray = geom->getColorArray();
247 osg::Vec4Array* colorVec4 = dynamic_cast<osg::Vec4Array*>(colorArray);
249 ambientDiffuse = (*colorVec4)[0];
252 osg::Vec3Array* colorVec3 = dynamic_cast<osg::Vec3Array*>(colorArray);
254 ambientDiffuse = osg::Vec4((*colorVec3)[0], 1.0f);
260 void maybeGetMaterialValues(const osg::StateSet* stateSet)
264 const osg::Material* nodeMat
265 = dynamic_cast<const osg::Material*>(stateSet
266 ->getAttribute(osg::StateAttribute
273 osg::ref_ptr<const osg::Material> material;
274 osg::Vec4 ambientDiffuse;
277 class MaterialPropertyAdapter
280 MaterialPropertyAdapter(const SGPropertyNode* configNode,
281 SGPropertyNode* modelRoot) :
282 _ambient(configNode->getChild("ambient"), modelRoot),
283 _diffuse(configNode->getChild("diffuse"), modelRoot),
284 _specular(configNode->getChild("specular"), modelRoot),
285 _emission(configNode->getChild("emission"), modelRoot),
286 _shininess("shininess", "shininess-prop",
287 configNode/*->getChild("shininess")*/, modelRoot),
288 _transparency("alpha", "alpha-prop",
289 configNode->getChild("transparency"), modelRoot)
291 _shininess.max = 128;
292 _isAnimated = (_ambient.live() || _diffuse.live() || _specular.live()
293 || _emission.live() || _shininess.live()
294 || _transparency.live());
296 bool isAnimated() { return _isAnimated; }
297 // This takes a StateSet argument because the rendering bin will
298 // be changed if there is transparency.
299 void setMaterialValues(osg::StateSet* stateSet)
301 osg::StateAttribute* stateAttribute
302 = stateSet->getAttribute(osg::StateAttribute::MATERIAL);
303 osg::Material* material = dynamic_cast<osg::Material*>(stateAttribute);
305 if (_ambient.live() || _ambient.dirty())
306 material->setAmbient(osg::Material::FRONT_AND_BACK,
307 _ambient.rgbaVec4());
308 if (_diffuse.live() || _diffuse.dirty())
309 material->setDiffuse(osg::Material::FRONT_AND_BACK,
310 _diffuse.rgbaVec4());
311 if (_specular.live() || _specular.dirty())
312 material->setSpecular(osg::Material::FRONT_AND_BACK,
313 _specular.rgbaVec4());
314 if (_emission.live() || _emission.dirty())
315 material->setEmission(osg::Material::FRONT_AND_BACK,
316 _emission.rgbaVec4());
317 if (_shininess.live() || _shininess.dirty())
318 material->setShininess(osg::Material::FRONT_AND_BACK,
319 _shininess.getValue());
320 if (_transparency.live() || _transparency.dirty()) {
321 float alpha = _transparency.getValue();
322 material->setAlpha(osg::Material::FRONT_AND_BACK, alpha);
324 stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
325 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
327 stateSet->setRenderingHint(osg::StateSet::DEFAULT_BIN);
337 PropSpec _transparency;
342 class UpdateCallback : public osg::NodeCallback {
344 UpdateCallback(const osgDB::FilePathList& texturePathList,
345 const SGPropertyNode* configNode, SGPropertyNode* modelRoot) :
346 _materialProps(configNode, modelRoot),
347 _texturePathList(texturePathList),
350 const SGPropertyNode* node;
352 node = configNode->getChild("threshold-prop");
354 _thresholdProp = modelRoot->getNode(node->getStringValue(), true);
355 node = configNode->getChild("texture-prop");
357 _textureProp = modelRoot->getNode(node->getStringValue(), true);
360 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362 osg::StateSet* stateSet = node->getStateSet();
365 std::string textureName = _textureProp->getStringValue();
366 if (_textureName != textureName) {
367 while (stateSet->getTextureAttribute(0,
368 osg::StateAttribute::TEXTURE)) {
369 stateSet->removeTextureAttribute(0, osg::StateAttribute::TEXTURE);
371 std::string textureFile;
372 textureFile = osgDB::findFileInPath(textureName, _texturePathList);
373 if (!textureFile.empty()) {
374 osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
376 stateSet->setTextureAttribute(0, texture2D,
377 osg::StateAttribute::OVERRIDE);
378 stateSet->setTextureMode(0, GL_TEXTURE_2D,
379 osg::StateAttribute::ON);
380 _textureName = textureName;
385 if (_thresholdProp) {
386 osg::StateSet* stateSet = node->getOrCreateStateSet();
387 osg::StateAttribute* stateAttribute;
388 stateAttribute = stateSet->getAttribute(osg::StateAttribute::ALPHAFUNC);
389 osg::AlphaFunc* alphaFunc
390 = dynamic_cast<osg::AlphaFunc*>(stateAttribute);
392 alphaFunc->setReferenceValue(_thresholdProp->getFloatValue());
394 if (_materialProps.isAnimated() || !_prevState)
395 _materialProps.setMaterialValues(stateSet);
403 SGSharedPtr<const SGPropertyNode> _textureProp;
404 SGSharedPtr<const SGPropertyNode> _thresholdProp;
405 std::string _textureName;
406 MaterialPropertyAdapter _materialProps;
407 osgDB::FilePathList _texturePathList;
413 SGMaterialAnimation::SGMaterialAnimation(const SGPropertyNode* configNode,
414 SGPropertyNode* modelRoot,
415 const osgDB::Options*
416 options, const string &path) :
417 SGAnimation(configNode, modelRoot),
418 texturePathList(options->getDatabasePathList())
420 if (configNode->hasChild("global"))
421 SG_LOG(SG_IO, SG_ALERT, path <<
422 ": Use of <global> in material animation is "
423 "no longer supported.");
427 SGMaterialAnimation::createAnimationGroup(osg::Group& parent)
429 osg::Group* group = new osg::Group;
430 group->setName("material animation group");
432 SGPropertyNode* inputRoot = getModelRoot();
433 const SGPropertyNode* node = getConfig()->getChild("property-base");
435 inputRoot = getModelRoot()->getNode(node->getStringValue(), true);
436 osg::StateSet* stateSet = group->getOrCreateStateSet();
437 if (getConfig()->hasChild("texture")) {
438 std::string textureName = getConfig()->getStringValue("texture");
439 std::string textureFile;
440 textureFile = osgDB::findFileInPath(textureName, texturePathList);
441 if (!textureFile.empty()) {
442 osg::Texture2D* texture2D = SGLoadTexture2D(textureFile);
444 stateSet->setTextureAttribute(0, texture2D,
445 osg::StateAttribute::OVERRIDE);
446 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
447 if (texture2D->getImage()->isImageTranslucent()) {
448 stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
449 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
454 if (getConfig()->hasChild("threshold-prop") ||
455 getConfig()->hasChild("threshold")) {
456 osg::AlphaFunc* alphaFunc = new osg::AlphaFunc;
457 alphaFunc->setFunction(osg::AlphaFunc::GREATER);
458 float threshold = getConfig()->getFloatValue("threshold", 0);
459 alphaFunc->setReferenceValue(threshold);
460 stateSet->setAttribute(alphaFunc, osg::StateAttribute::OVERRIDE);
463 unsigned suppliedColors = 0;
464 if (getConfig()->hasChild("ambient"))
465 suppliedColors |= AMBIENT;
466 if (getConfig()->hasChild("diffuse"))
467 suppliedColors |= DIFFUSE;
468 if (getConfig()->hasChild("specular"))
469 suppliedColors |= SPECULAR;
470 if (getConfig()->hasChild("emission"))
471 suppliedColors |= EMISSION;
472 if (getConfig()->hasChild("shininess")
473 || getConfig()->hasChild("shininess-prop"))
474 suppliedColors |= SHININESS;
475 if (getConfig()->hasChild("transparency"))
476 suppliedColors |= TRANSPARENCY;
477 osg::Material* mat = 0;
478 if (suppliedColors != 0) {
479 if (defaultMaterial.valid()) {
480 mat = defaultMaterial.get();
483 mat = new osg::Material;
484 mat->setColorMode(osg::Material::AMBIENT_AND_DIFFUSE);
486 mat->setDataVariance(osg::Object::DYNAMIC);
487 unsigned defaultColorModeMask = 0;
488 mat->setUpdateCallback(0); // Just to make sure.
489 // XXX This should probably go away, as ac3d models always have a
490 // DIFFUSE color mode.
491 switch (mat->getColorMode()) {
492 case osg::Material::OFF:
493 defaultColorModeMask = 0;
495 case osg::Material::AMBIENT:
496 defaultColorModeMask = AMBIENT;
498 case osg::Material::DIFFUSE:
499 defaultColorModeMask = DIFFUSE;
501 case osg::Material::AMBIENT_AND_DIFFUSE:
502 defaultColorModeMask = AMBIENT | DIFFUSE;
504 case osg::Material::SPECULAR:
505 defaultColorModeMask = SPECULAR;
507 case osg::Material::EMISSION:
508 defaultColorModeMask = EMISSION;
511 // Copy the color found by traversing geometry into the material
512 // in case we need to specify it (e.g., transparency) and it is
513 // not specified by the animation.
514 if (defaultAmbientDiffuse.x() >= 0) {
515 if (defaultColorModeMask & AMBIENT)
516 mat->setAmbient(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
517 if (defaultColorModeMask & DIFFUSE)
518 mat->setDiffuse(osg::Material::FRONT_AND_BACK, defaultAmbientDiffuse);
520 // Compute which colors in the animation override colors set via
521 // colorMode / glColor, and set the colorMode for the animation's
522 // material accordingly.
523 if (suppliedColors & TRANSPARENCY) {
524 // All colors will be affected by the material. Hope all the
525 // defaults are fine, if needed.
526 mat->setColorMode(osg::Material::OFF);
527 } else if ((suppliedColors & defaultColorModeMask) != 0) {
528 // First deal with the complicated AMBIENT/DIFFUSE case.
529 if ((defaultColorModeMask & AMBIENT_DIFFUSE) != 0) {
530 // glColor can supply colors not specified by the animation.
531 unsigned matColorModeMask = ((~suppliedColors & defaultColorModeMask)
533 if ((matColorModeMask & DIFFUSE) != 0)
534 mat->setColorMode(osg::Material::DIFFUSE);
535 else if ((matColorModeMask & AMBIENT) != 0)
536 mat->setColorMode(osg::Material::AMBIENT);
538 mat->setColorMode(osg::Material::OFF);
540 // The animation overrides the glColor color.
541 mat->setColorMode(osg::Material::OFF);
544 // No overlap between the animation and color mode, so leave
545 // the color mode alone.
547 stateSet->setAttribute(mat,(osg::StateAttribute::ON
548 | osg::StateAttribute::OVERRIDE));
550 bool matAnimated = false;
552 MaterialPropertyAdapter adapter(getConfig(), inputRoot);
553 adapter.setMaterialValues(stateSet);
554 matAnimated = adapter.isAnimated();
556 if (matAnimated || getConfig()->hasChild("texture-prop")
557 || getConfig()->hasChild("threshold-prop") || getCondition()) {
558 stateSet->setDataVariance(osg::Object::DYNAMIC);
559 group->setUpdateCallback(new UpdateCallback(texturePathList,
560 getConfig(), inputRoot));
562 stateSet->setDataVariance(osg::Object::STATIC);
564 if (getCondition()) {
565 ConditionNode* cn = new ConditionNode;
566 cn->setCondition(getCondition());
567 osg::Group* modelGroup = new osg::Group;
568 group->addChild(modelGroup);
570 cn->addChild(modelGroup);
574 parent.addChild(group);
580 SGMaterialAnimation::install(osg::Node& node)
582 SGAnimation::install(node);
584 MaterialDefaultsVisitor defaultsVisitor;
585 node.accept(defaultsVisitor);
586 if (defaultsVisitor.material.valid()) {
588 = static_cast<osg::Material*>(defaultsVisitor.material->clone(osg::CopyOp::SHALLOW_COPY));
590 defaultAmbientDiffuse = defaultsVisitor.ambientDiffuse;
593 const char* colorNames[] =
601 // Build an effect which mimics the material color mode in a
602 // shader. The OpenGL material values will be overridden by the
603 // material animation's material.
605 // This is a hack to get the effect to respect the values set in the
606 // material, set up by the animation, which overrides the values in
607 // the effect's material attributes. Things will be different when
608 // material animations are implemented purely by manipulating effects.
611 SGMaterialAnimation::makeEffectProperties(const SGPropertyNode* animProp)
613 SGPropertyNode_ptr eRoot = new SGPropertyNode;
614 SGPropertyNode* inherit = makeNode(eRoot, "inherits-from");
615 if (animProp->hasChild("diffuse") || animProp->hasChild("transparency"))
616 inherit->setStringValue("Effects/material-off");
618 inherit->setStringValue("Effects/material-diffuse");