1 // Copyright (C) 2008 - 2010 Tim Moore timoore33@gmail.com
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Library General Public License for more details.
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 # include <simgear_config.h>
22 #include "EffectBuilder.hxx"
23 #include "EffectGeode.hxx"
24 #include "Technique.hxx"
26 #include "TextureBuilder.hxx"
27 #include "parseBlendFunc.hxx"
34 #include <boost/tr1/unordered_map.hpp>
36 #include <boost/bind.hpp>
37 #include <boost/foreach.hpp>
38 #include <boost/functional/hash.hpp>
39 #include <boost/tuple/tuple.hpp>
40 #include <boost/tuple/tuple_comparison.hpp>
42 #include <osg/AlphaFunc>
43 #include <osg/BlendFunc>
44 #include <osg/CullFace>
46 #include <osg/Drawable>
47 #include <osg/Material>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/Program>
52 #include <osg/Referenced>
53 #include <osg/RenderInfo>
54 #include <osg/ShadeModel>
55 #include <osg/StateSet>
56 #include <osg/Stencil>
58 #include <osg/Texture1D>
59 #include <osg/Texture2D>
60 #include <osg/Texture3D>
61 #include <osg/TextureRectangle>
62 #include <osg/Uniform>
64 #include <osgUtil/CullVisitor>
65 #include <osgDB/FileUtils>
66 #include <osgDB/Input>
67 #include <osgDB/ParameterOutput>
68 #include <osgDB/ReadFile>
69 #include <osgDB/Registry>
71 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
72 #include <simgear/scene/tgdb/userdata.hxx>
73 #include <simgear/scene/util/OsgMath.hxx>
74 #include <simgear/scene/util/SGSceneFeatures.hxx>
75 #include <simgear/scene/util/StateAttributeFactory.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/structure/SGExpression.hxx>
78 #include <simgear/props/vectorPropTemplates.hxx>
85 using namespace osgUtil;
87 using namespace effect;
90 : _cache(0), _isRealized(false)
94 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
95 : osg::Object(rhs,copyop), root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
96 _isRealized(rhs._isRealized)
98 typedef vector<ref_ptr<Technique> > TechniqueList;
99 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
100 end = rhs.techniques.end();
103 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
105 generator = rhs.generator;
108 // Assume that the last technique is always valid.
109 StateSet* Effect::getDefaultStateSet()
111 Technique* tniq = techniques.back().get();
114 Pass* pass = tniq->passes.front().get();
118 int Effect::getGenerator(Effect::Generator what) const
120 std::map<Generator,int>::const_iterator it = generator.find(what);
121 if(it == generator.end()) return -1;
122 else return it->second;
125 // There should always be a valid technique in an effect.
127 Technique* Effect::chooseTechnique(RenderInfo* info)
129 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
131 if (technique->valid(info) == Technique::VALID)
132 return technique.get();
137 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
139 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
141 technique->resizeGLObjectBuffers(maxSize);
145 void Effect::releaseGLObjects(osg::State* state) const
147 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
149 technique->releaseGLObjects(state);
158 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
159 const SGReaderWriterOptions* options)
161 Pass* pass = new Pass;
162 tniq->passes.push_back(pass);
163 for (int i = 0; i < prop->nChildren(); ++i) {
164 const SGPropertyNode* attrProp = prop->getChild(i);
165 PassAttributeBuilder* builder
166 = PassAttributeBuilder::find(attrProp->getNameString());
168 builder->buildAttribute(effect, pass, attrProp, options);
170 SG_LOG(SG_INPUT, SG_ALERT,
171 "skipping unknown pass attribute " << attrProp->getName());
175 // Default names for vector property components
176 const char* vec3Names[] = {"x", "y", "z"};
177 const char* vec4Names[] = {"x", "y", "z", "w"};
179 osg::Vec4f getColor(const SGPropertyNode* prop)
181 if (prop->nChildren() == 0) {
182 if (prop->getType() == props::VEC4D) {
183 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
184 } else if (prop->getType() == props::VEC3D) {
185 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
187 SG_LOG(SG_INPUT, SG_ALERT,
188 "invalid color property " << prop->getName() << " "
189 << prop->getStringValue());
190 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
194 static const char* colors[] = {"r", "g", "b"};
195 for (int i = 0; i < 3; ++i) {
196 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
197 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
199 const SGPropertyNode* alphaProp = prop->getChild("a");
200 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
205 struct LightingBuilder : public PassAttributeBuilder
207 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
208 const SGReaderWriterOptions* options);
211 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
212 const SGPropertyNode* prop,
213 const SGReaderWriterOptions* options)
215 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
218 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
219 : StateAttribute::OFF));
222 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
224 struct ShadeModelBuilder : public PassAttributeBuilder
226 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
227 const SGReaderWriterOptions* options)
229 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
232 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
233 string propVal = realProp->getStringValue();
234 if (propVal == "flat")
235 pass->setAttribute(attrFact->getFlatShadeModel());
236 else if (propVal == "smooth")
237 pass->setAttribute(attrFact->getSmoothShadeModel());
239 SG_LOG(SG_INPUT, SG_ALERT,
240 "invalid shade model property " << propVal);
244 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
246 struct CullFaceBuilder : PassAttributeBuilder
248 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
249 const SGReaderWriterOptions* options)
251 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
253 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
256 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
257 string propVal = realProp->getStringValue();
258 if (propVal == "front")
259 pass->setAttributeAndModes(attrFact->getCullFaceFront());
260 else if (propVal == "back")
261 pass->setAttributeAndModes(attrFact->getCullFaceBack());
262 else if (propVal == "front-back")
263 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
264 else if (propVal == "off")
265 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
267 SG_LOG(SG_INPUT, SG_ALERT,
268 "invalid cull face property " << propVal);
272 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
274 struct ColorMaskBuilder : PassAttributeBuilder
276 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
277 const SGReaderWriterOptions* options)
279 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
283 ColorMask *mask = new ColorMask;
284 Vec4 m = getColor(realProp);
285 mask->setMask(m.r() > 0.0, m.g() > 0.0, m.b() > 0.0, m.a() > 0.0);
286 pass->setAttributeAndModes(mask);
290 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
292 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
294 { "default", StateSet::DEFAULT_BIN },
295 { "opaque", StateSet::OPAQUE_BIN },
296 { "transparent", StateSet::TRANSPARENT_BIN }
299 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
301 struct HintBuilder : public PassAttributeBuilder
303 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
304 const SGReaderWriterOptions* options)
306 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
309 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
310 findAttr(renderingHints, realProp, renderingHint);
311 pass->setRenderingHint(renderingHint);
315 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
317 struct RenderBinBuilder : public PassAttributeBuilder
319 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
320 const SGReaderWriterOptions* options)
322 if (!isAttributeActive(effect, prop))
324 const SGPropertyNode* binProp = prop->getChild("bin-number");
325 binProp = getEffectPropertyNode(effect, binProp);
326 const SGPropertyNode* nameProp = prop->getChild("bin-name");
327 nameProp = getEffectPropertyNode(effect, nameProp);
328 if (binProp && nameProp) {
329 pass->setRenderBinDetails(binProp->getIntValue(),
330 nameProp->getStringValue());
333 SG_LOG(SG_INPUT, SG_ALERT,
334 "No render bin number specified in render bin section");
336 SG_LOG(SG_INPUT, SG_ALERT,
337 "No render bin name specified in render bin section");
342 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
344 struct MaterialBuilder : public PassAttributeBuilder
346 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
347 const SGReaderWriterOptions* options);
350 EffectNameValue<Material::ColorMode> colorModeInit[] =
352 { "ambient", Material::AMBIENT },
353 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
354 { "diffuse", Material::DIFFUSE },
355 { "emissive", Material::EMISSION },
356 { "specular", Material::SPECULAR },
357 { "off", Material::OFF }
359 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
361 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
362 const SGPropertyNode* prop,
363 const SGReaderWriterOptions* options)
365 if (!isAttributeActive(effect, prop))
367 Material* mat = new Material;
368 const SGPropertyNode* color = 0;
369 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
370 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
371 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
372 mat->setAmbient(Material::FRONT, getColor(color));
373 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
374 mat->setAmbient(Material::BACK, getColor(color));
375 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
376 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
377 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
378 mat->setDiffuse(Material::FRONT, getColor(color));
379 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
380 mat->setDiffuse(Material::BACK, getColor(color));
381 if ((color = getEffectPropertyChild(effect, prop, "specular")))
382 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
383 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
384 mat->setSpecular(Material::FRONT, getColor(color));
385 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
386 mat->setSpecular(Material::BACK, getColor(color));
387 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
388 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
389 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
390 mat->setEmission(Material::FRONT, getColor(color));
391 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
392 mat->setEmission(Material::BACK, getColor(color));
393 const SGPropertyNode* shininess = 0;
394 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
395 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
396 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
397 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
398 mat->setShininess(Material::FRONT, shininess->getFloatValue());
399 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
400 mat->setShininess(Material::BACK, shininess->getFloatValue());
401 Material::ColorMode colorMode = Material::OFF;
402 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
404 mat->setColorMode(colorMode);
405 pass->setAttribute(mat);
408 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
410 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
412 {"dst-alpha", BlendFunc::DST_ALPHA},
413 {"dst-color", BlendFunc::DST_COLOR},
414 {"one", BlendFunc::ONE},
415 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
416 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
417 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
418 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
419 {"src-alpha", BlendFunc::SRC_ALPHA},
420 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
421 {"src-color", BlendFunc::SRC_COLOR},
422 {"constant-color", BlendFunc::CONSTANT_COLOR},
423 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
424 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
425 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
426 {"zero", BlendFunc::ZERO}
428 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
430 struct BlendBuilder : public PassAttributeBuilder
432 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
433 const SGReaderWriterOptions* options)
435 if (!isAttributeActive(effect, prop))
437 // XXX Compatibility with early <blend> syntax; should go away
439 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
442 if (realProp->nChildren() == 0) {
443 pass->setMode(GL_BLEND, (realProp->getBoolValue()
445 : StateAttribute::OFF));
449 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
451 // XXX When dynamic parameters are supported, this code should
452 // create the blend function even if the mode is off.
453 if (pmode && !pmode->getValue<bool>()) {
454 pass->setMode(GL_BLEND, StateAttribute::OFF);
460 getEffectPropertyChild(effect, prop, "source"),
461 getEffectPropertyChild(effect, prop, "destination"),
462 getEffectPropertyChild(effect, prop, "source-rgb"),
463 getEffectPropertyChild(effect, prop, "destination-rgb"),
464 getEffectPropertyChild(effect, prop, "source-alpha"),
465 getEffectPropertyChild(effect, prop, "destination-alpha")
470 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
473 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
475 {"never", Stencil::NEVER },
476 {"less", Stencil::LESS},
477 {"equal", Stencil::EQUAL},
478 {"less-or-equal", Stencil::LEQUAL},
479 {"greater", Stencil::GREATER},
480 {"not-equal", Stencil::NOTEQUAL},
481 {"greater-or-equal", Stencil::GEQUAL},
482 {"always", Stencil::ALWAYS}
485 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
487 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
489 {"keep", Stencil::KEEP},
490 {"zero", Stencil::ZERO},
491 {"replace", Stencil::REPLACE},
492 {"increase", Stencil::INCR},
493 {"decrease", Stencil::DECR},
494 {"invert", Stencil::INVERT},
495 {"increase-wrap", Stencil::INCR_WRAP},
496 {"decrease-wrap", Stencil::DECR_WRAP}
499 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
501 struct StencilBuilder : public PassAttributeBuilder
503 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
504 const SGReaderWriterOptions* options)
506 if (!isAttributeActive(effect, prop))
509 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
511 if (pmode && !pmode->getValue<bool>()) {
512 pass->setMode(GL_STENCIL, StateAttribute::OFF);
515 const SGPropertyNode* pfunction
516 = getEffectPropertyChild(effect, prop, "function");
517 const SGPropertyNode* pvalue
518 = getEffectPropertyChild(effect, prop, "value");
519 const SGPropertyNode* pmask
520 = getEffectPropertyChild(effect, prop, "mask");
521 const SGPropertyNode* psfail
522 = getEffectPropertyChild(effect, prop, "stencil-fail");
523 const SGPropertyNode* pzfail
524 = getEffectPropertyChild(effect, prop, "z-fail");
525 const SGPropertyNode* ppass
526 = getEffectPropertyChild(effect, prop, "pass");
528 Stencil::Function func = Stencil::ALWAYS; // Always pass
530 unsigned int mask = ~0u; // All bits on
531 Stencil::Operation sfailop = Stencil::KEEP; // Keep the old values as default
532 Stencil::Operation zfailop = Stencil::KEEP;
533 Stencil::Operation passop = Stencil::KEEP;
535 ref_ptr<Stencil> stencilFunc = new Stencil;
538 findAttr(stencilFunction, pfunction, func);
540 ref = pvalue->getIntValue();
542 mask = pmask->getIntValue();
545 findAttr(stencilOperation, psfail, sfailop);
547 findAttr(stencilOperation, pzfail, zfailop);
549 findAttr(stencilOperation, ppass, passop);
551 // Set the stencil operation
552 stencilFunc->setFunction(func, ref, mask);
554 // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
555 stencilFunc->setOperation(sfailop, zfailop, passop);
557 // Add the operation to pass
558 pass->setAttributeAndModes(stencilFunc.get());
562 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
564 struct AlphaToCoverageBuilder : public PassAttributeBuilder
566 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
567 const SGReaderWriterOptions* options);
570 #ifndef GL_SAMPLE_ALPHA_TO_COVERAGE_ARB
571 #define GL_SAMPLE_ALPHA_TO_COVERAGE_ARB 0x809E
574 void AlphaToCoverageBuilder::buildAttribute(Effect* effect, Pass* pass,
575 const SGPropertyNode* prop,
576 const SGReaderWriterOptions* options)
578 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
581 pass->setMode(GL_SAMPLE_ALPHA_TO_COVERAGE_ARB, (realProp->getValue<bool>() ?
582 StateAttribute::ON : StateAttribute::OFF));
585 InstallAttributeBuilder<AlphaToCoverageBuilder> installAlphaToCoverage("alpha-to-coverage");
587 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
589 {"never", AlphaFunc::NEVER},
590 {"less", AlphaFunc::LESS},
591 {"equal", AlphaFunc::EQUAL},
592 {"lequal", AlphaFunc::LEQUAL},
593 {"greater", AlphaFunc::GREATER},
594 {"notequal", AlphaFunc::NOTEQUAL},
595 {"gequal", AlphaFunc::GEQUAL},
596 {"always", AlphaFunc::ALWAYS}
598 EffectPropertyMap<AlphaFunc::ComparisonFunction>
599 alphaComparison(alphaComparisonInit);
601 struct AlphaTestBuilder : public PassAttributeBuilder
603 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
604 const SGReaderWriterOptions* options)
606 if (!isAttributeActive(effect, prop))
608 // XXX Compatibility with early <alpha-test> syntax; should go away
610 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
613 if (realProp->nChildren() == 0) {
614 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
616 : StateAttribute::OFF));
620 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
622 // XXX When dynamic parameters are supported, this code should
623 // create the blend function even if the mode is off.
624 if (pmode && !pmode->getValue<bool>()) {
625 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
628 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
630 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
633 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
634 float refValue = 1.0f;
636 findAttr(alphaComparison, pComp, func);
638 refValue = pRef->getValue<float>();
639 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
640 pass->setAttributeAndModes(StateAttributeFactory::instance()
641 ->getStandardAlphaFunc());
643 AlphaFunc* alphaFunc = new AlphaFunc;
644 alphaFunc->setFunction(func);
645 alphaFunc->setReferenceValue(refValue);
646 pass->setAttributeAndModes(alphaFunc);
651 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
653 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
655 // Shader key, used both for shaders with relative and absolute names
656 typedef pair<string, int> ShaderKey;
658 inline ShaderKey makeShaderKey(SGPropertyNode_ptr& ptr, int shaderType)
660 return ShaderKey(ptr->getStringValue(), shaderType);
665 typedef pair<string, int> AttribKey;
666 osgDB::FilePathList paths;
667 vector<ShaderKey> shaders;
668 vector<AttribKey> attributes;
671 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
673 return (lhs.paths.size() == rhs.paths.size()
674 && equal(lhs.paths.begin(), lhs.paths.end(),
676 && lhs.shaders.size() == rhs.shaders.size()
677 && equal (lhs.shaders.begin(), lhs.shaders.end(),
679 && lhs.attributes.size() == rhs.attributes.size()
680 && equal(lhs.attributes.begin(), lhs.attributes.end(),
681 rhs.attributes.begin()));
686 size_t hash_value(const ProgramKey& key)
689 boost::hash_range(seed, key.paths.begin(), key.paths.end());
690 boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
691 boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
695 // XXX Should these be protected by a mutex? Probably
697 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
698 boost::hash<ProgramKey>, ProgramKey::EqualTo>
700 ProgramMap programMap;
701 ProgramMap resolvedProgramMap; // map with resolved shader file names
703 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
707 void reload_shaders()
709 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
711 Shader *shader = sitr->second.get();
712 string fileName = SGModelLib::findDataFile(sitr->first.first);
713 if (!fileName.empty()) {
714 shader->loadShaderSourceFromFile(fileName);
719 struct ShaderProgramBuilder : PassAttributeBuilder
721 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
722 const SGReaderWriterOptions* options);
726 EffectNameValue<GLint> geometryInputTypeInit[] =
728 {"points", GL_POINTS},
730 {"lines-adjacency", GL_LINES_ADJACENCY_EXT},
731 {"triangles", GL_TRIANGLES},
732 {"triangles-adjacency", GL_TRIANGLES_ADJACENCY_EXT},
734 EffectPropertyMap<GLint>
735 geometryInputType(geometryInputTypeInit);
738 EffectNameValue<GLint> geometryOutputTypeInit[] =
740 {"points", GL_POINTS},
741 {"line-strip", GL_LINE_STRIP},
742 {"triangle-strip", GL_TRIANGLE_STRIP}
744 EffectPropertyMap<GLint>
745 geometryOutputType(geometryOutputTypeInit);
747 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
748 const SGPropertyNode* prop,
749 const SGReaderWriterOptions*
752 using namespace boost;
753 if (!isAttributeActive(effect, prop))
755 PropertyList pVertShaders = prop->getChildren("vertex-shader");
756 PropertyList pGeomShaders = prop->getChildren("geometry-shader");
757 PropertyList pFragShaders = prop->getChildren("fragment-shader");
758 PropertyList pAttributes = prop->getChildren("attribute");
760 std::back_insert_iterator<vector<ShaderKey> > inserter(prgKey.shaders);
761 transform(pVertShaders.begin(), pVertShaders.end(), inserter,
762 boost::bind(makeShaderKey, _1, Shader::VERTEX));
763 transform(pGeomShaders.begin(), pGeomShaders.end(), inserter,
764 boost::bind(makeShaderKey, _1, Shader::GEOMETRY));
765 transform(pFragShaders.begin(), pFragShaders.end(), inserter,
766 boost::bind(makeShaderKey, _1, Shader::FRAGMENT));
767 for (PropertyList::iterator itr = pAttributes.begin(),
768 e = pAttributes.end();
771 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
773 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
775 if (!pName || ! pIndex)
776 throw BuilderException("malformed attribute property");
778 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
779 pIndex->getValue<int>()));
782 prgKey.paths = options->getDatabasePathList();
783 Program* program = 0;
784 ProgramMap::iterator pitr = programMap.find(prgKey);
785 if (pitr != programMap.end()) {
786 program = pitr->second.get();
787 pass->setAttributeAndModes(program);
790 // The program wasn't in the map using the load path passed in with
791 // the options, but it might have already been loaded using a
792 // different load path i.e., its shaders were found in the fg data
793 // directory. So, resolve the shaders' file names and look in the
794 // resolvedProgramMap for a program using those shaders.
795 ProgramKey resolvedKey;
796 resolvedKey.attributes = prgKey.attributes;
797 BOOST_FOREACH(const ShaderKey& shaderKey, prgKey.shaders)
799 const string& shaderName = shaderKey.first;
800 Shader::Type stype = (Shader::Type)shaderKey.second;
801 string fileName = SGModelLib::findDataFile(shaderName, options);
802 if (fileName.empty())
803 throw BuilderException(string("couldn't find shader ") +
805 resolvedKey.shaders.push_back(ShaderKey(fileName, stype));
807 ProgramMap::iterator resitr = resolvedProgramMap.find(resolvedKey);
808 if (resitr != resolvedProgramMap.end()) {
809 program = resitr->second.get();
810 programMap.insert(ProgramMap::value_type(prgKey, program));
811 pass->setAttributeAndModes(program);
814 program = new Program;
815 BOOST_FOREACH(const ShaderKey& skey, resolvedKey.shaders)
817 const string& fileName = skey.first;
818 Shader::Type stype = (Shader::Type)skey.second;
819 ShaderMap::iterator sitr = shaderMap.find(skey);
820 if (sitr != shaderMap.end()) {
821 program->addShader(sitr->second.get());
823 ref_ptr<Shader> shader = new Shader(stype);
824 shader->setName(fileName);
825 if (shader->loadShaderSourceFromFile(fileName)) {
826 program->addShader(shader.get());
827 shaderMap.insert(ShaderMap::value_type(skey, shader));
831 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
832 program->addBindAttribLocation(key.first, key.second);
834 const SGPropertyNode* pGeometryVerticesOut
835 = getEffectPropertyChild(effect, prop, "geometry-vertices-out");
836 if (pGeometryVerticesOut)
837 program->setParameter(GL_GEOMETRY_VERTICES_OUT_EXT,
838 pGeometryVerticesOut->getIntValue());
839 const SGPropertyNode* pGeometryInputType
840 = getEffectPropertyChild(effect, prop, "geometry-input-type");
841 if (pGeometryInputType) {
843 findAttr(geometryInputType, pGeometryInputType->getStringValue(), type);
844 program->setParameter(GL_GEOMETRY_INPUT_TYPE_EXT, type);
846 const SGPropertyNode* pGeometryOutputType
847 = getEffectPropertyChild(effect, prop, "geometry-output-type");
848 if (pGeometryOutputType) {
850 findAttr(geometryOutputType, pGeometryOutputType->getStringValue(),
852 program->setParameter(GL_GEOMETRY_OUTPUT_TYPE_EXT, type);
854 programMap.insert(ProgramMap::value_type(prgKey, program));
855 resolvedProgramMap.insert(ProgramMap::value_type(resolvedKey, program));
856 pass->setAttributeAndModes(program);
859 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
861 EffectNameValue<Uniform::Type> uniformTypesInit[] =
863 {"bool", Uniform::BOOL},
864 {"int", Uniform::INT},
865 {"float", Uniform::FLOAT},
866 {"float-vec3", Uniform::FLOAT_VEC3},
867 {"float-vec4", Uniform::FLOAT_VEC4},
868 {"sampler-1d", Uniform::SAMPLER_1D},
869 {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
870 {"sampler-2d", Uniform::SAMPLER_2D},
871 {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
872 {"sampler-3d", Uniform::SAMPLER_3D},
873 {"sampler-cube", Uniform::SAMPLER_CUBE}
875 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
877 // Optimization hack for common uniforms.
878 // XXX protect these with a mutex?
880 ref_ptr<Uniform> texture0;
881 ref_ptr<Uniform> colorMode[3];
883 struct UniformBuilder :public PassAttributeBuilder
885 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
886 const SGReaderWriterOptions* options)
888 if (!texture0.valid()) {
889 texture0 = new Uniform(Uniform::SAMPLER_2D, "texture");
891 texture0->setDataVariance(Object::STATIC);
892 for (int i = 0; i < 3; ++i) {
893 colorMode[i] = new Uniform(Uniform::INT, "colorMode");
894 colorMode[i]->set(i);
895 colorMode[i]->setDataVariance(Object::STATIC);
898 if (!isAttributeActive(effect, prop))
900 const SGPropertyNode* nameProp = prop->getChild("name");
901 const SGPropertyNode* typeProp = prop->getChild("type");
902 const SGPropertyNode* positionedProp = prop->getChild("positioned");
903 const SGPropertyNode* valProp = prop->getChild("value");
905 Uniform::Type uniformType = Uniform::FLOAT;
907 name = nameProp->getStringValue();
909 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
913 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
918 props::Type propType = valProp->getType();
921 uniformType = Uniform::BOOL;
924 uniformType = Uniform::INT;
928 break; // default float type;
930 uniformType = Uniform::FLOAT_VEC3;
933 uniformType = Uniform::FLOAT_VEC4;
936 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
941 findAttr(uniformTypes, typeProp, uniformType);
943 ref_ptr<Uniform> uniform = new Uniform;
944 uniform->setName(name);
945 uniform->setType(uniformType);
946 switch (uniformType) {
948 initFromParameters(effect, valProp, uniform.get(),
949 static_cast<bool (Uniform::*)(bool)>(&Uniform::set),
953 initFromParameters(effect, valProp, uniform.get(),
954 static_cast<bool (Uniform::*)(float)>(&Uniform::set),
957 case Uniform::FLOAT_VEC3:
958 initFromParameters(effect, valProp, uniform.get(),
959 static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
962 case Uniform::FLOAT_VEC4:
963 initFromParameters(effect, valProp, uniform.get(),
964 static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
968 case Uniform::SAMPLER_1D:
969 case Uniform::SAMPLER_2D:
970 case Uniform::SAMPLER_3D:
971 case Uniform::SAMPLER_1D_SHADOW:
972 case Uniform::SAMPLER_2D_SHADOW:
973 case Uniform::SAMPLER_CUBE:
974 initFromParameters(effect, valProp, uniform.get(),
975 static_cast<bool (Uniform::*)(int)>(&Uniform::set),
978 default: // avoid compiler warning
981 // optimize common uniforms
982 if (uniformType == Uniform::SAMPLER_2D || uniformType == Uniform::INT)
985 uniform->get(val); // 'val' remains unchanged in case of error (Uniform is a non-scalar)
986 if (uniformType == Uniform::SAMPLER_2D && val == 0
987 && name == "texture") {
989 } else if (uniformType == Uniform::INT && val >= 0 && val < 3
990 && name == "colorMode") {
991 uniform = colorMode[val];
994 pass->addUniform(uniform.get());
995 if (positionedProp && positionedProp->getBoolValue() && uniformType == Uniform::FLOAT_VEC4) {
997 uniform->get(offset);
998 pass->addPositionedUniform( name, offset );
1003 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
1005 // Not sure what to do with "name". At one point I wanted to use it to
1006 // order the passes, but I do support render bin and stuff too...
1008 struct NameBuilder : public PassAttributeBuilder
1010 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1011 const SGReaderWriterOptions* options)
1013 // name can't use <use>
1014 string name = prop->getStringValue();
1016 pass->setName(name);
1020 InstallAttributeBuilder<NameBuilder> installName("name");
1022 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
1024 {"fill", PolygonMode::FILL},
1025 {"line", PolygonMode::LINE},
1026 {"point", PolygonMode::POINT}
1028 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
1030 struct PolygonModeBuilder : public PassAttributeBuilder
1032 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1033 const SGReaderWriterOptions* options)
1035 if (!isAttributeActive(effect, prop))
1037 const SGPropertyNode* frontProp
1038 = getEffectPropertyChild(effect, prop, "front");
1039 const SGPropertyNode* backProp
1040 = getEffectPropertyChild(effect, prop, "back");
1041 ref_ptr<PolygonMode> pmode = new PolygonMode;
1042 PolygonMode::Mode frontMode = PolygonMode::FILL;
1043 PolygonMode::Mode backMode = PolygonMode::FILL;
1045 findAttr(polygonModeModes, frontProp, frontMode);
1046 pmode->setMode(PolygonMode::FRONT, frontMode);
1049 findAttr(polygonModeModes, backProp, backMode);
1050 pmode->setMode(PolygonMode::BACK, backMode);
1052 pass->setAttribute(pmode.get());
1056 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
1058 struct PolygonOffsetBuilder : public PassAttributeBuilder
1060 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1061 const SGReaderWriterOptions* options)
1063 if (!isAttributeActive(effect, prop))
1066 const SGPropertyNode* factor
1067 = getEffectPropertyChild(effect, prop, "factor");
1068 const SGPropertyNode* units
1069 = getEffectPropertyChild(effect, prop, "units");
1071 ref_ptr<PolygonOffset> polyoffset = new PolygonOffset;
1073 polyoffset->setFactor(factor->getFloatValue());
1074 polyoffset->setUnits(units->getFloatValue());
1076 SG_LOG(SG_INPUT, SG_BULK,
1077 "Set PolygonOffset to " << polyoffset->getFactor() << polyoffset->getUnits() );
1079 pass->setAttributeAndModes(polyoffset.get(),
1080 StateAttribute::OVERRIDE|StateAttribute::ON);
1084 InstallAttributeBuilder<PolygonOffsetBuilder> installPolygonOffset("polygon-offset");
1086 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
1088 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1089 const SGReaderWriterOptions* options)
1091 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1094 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
1095 (realProp->getValue<bool>()
1096 ? StateAttribute::ON : StateAttribute::OFF));
1100 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
1101 installTwoSide("vertex-program-two-side");
1103 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
1105 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1106 const SGReaderWriterOptions* options)
1108 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
1111 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
1112 (realProp->getValue<bool>()
1113 ? StateAttribute::ON : StateAttribute::OFF));
1117 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
1118 installPointSize("vertex-program-point-size");
1120 EffectNameValue<Depth::Function> depthFunctionInit[] =
1122 {"never", Depth::NEVER},
1123 {"less", Depth::LESS},
1124 {"equal", Depth::EQUAL},
1125 {"lequal", Depth::LEQUAL},
1126 {"greater", Depth::GREATER},
1127 {"notequal", Depth::NOTEQUAL},
1128 {"gequal", Depth::GEQUAL},
1129 {"always", Depth::ALWAYS}
1131 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1133 struct DepthBuilder : public PassAttributeBuilder
1135 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1136 const SGReaderWriterOptions* options)
1138 if (!isAttributeActive(effect, prop))
1140 ref_ptr<Depth> depth = new Depth;
1141 const SGPropertyNode* pfunc
1142 = getEffectPropertyChild(effect, prop, "function");
1144 Depth::Function func = Depth::LESS;
1145 findAttr(depthFunction, pfunc, func);
1146 depth->setFunction(func);
1148 const SGPropertyNode* pnear
1149 = getEffectPropertyChild(effect, prop, "near");
1151 depth->setZNear(pnear->getValue<double>());
1152 const SGPropertyNode* pfar
1153 = getEffectPropertyChild(effect, prop, "far");
1155 depth->setZFar(pfar->getValue<double>());
1156 const SGPropertyNode* pmask
1157 = getEffectPropertyChild(effect, prop, "write-mask");
1159 depth->setWriteMask(pmask->getValue<bool>());
1160 const SGPropertyNode* penabled
1161 = getEffectPropertyChild(effect, prop, "enabled");
1162 bool enabled = ( penabled == 0 || penabled->getBoolValue() );
1163 pass->setAttributeAndModes(depth.get(), enabled ? osg::StateAttribute::ON : osg::StateAttribute::OFF);
1167 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1169 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1170 const SGReaderWriterOptions* options)
1172 Technique* tniq = new Technique;
1173 effect->techniques.push_back(tniq);
1174 const SGPropertyNode* predProp = prop->getChild("predicate");
1176 tniq->setAlwaysValid(true);
1179 TechniquePredParser parser;
1180 parser.setTechnique(tniq);
1181 expression::BindingLayout& layout = parser.getBindingLayout();
1182 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1183 SGExpressionb* validExp
1184 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1187 tniq->setValidExpression(validExp, layout);
1189 throw expression::ParseError("technique predicate is not a boolean expression");
1191 catch (expression::ParseError& except)
1193 SG_LOG(SG_INPUT, SG_ALERT,
1194 "parsing technique predicate " << except.getMessage());
1195 tniq->setAlwaysValid(false);
1198 PropertyList passProps = prop->getChildren("pass");
1199 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1202 buildPass(effect, tniq, itr->ptr(), options);
1206 // Specifically for .ac files...
1207 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1209 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1210 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1211 Vec4f ambVal, difVal, specVal, emisVal;
1212 float shininess = 0.0f;
1213 const Material* mat = getStateAttribute<Material>(ss);
1215 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1216 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1217 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1218 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1219 shininess = mat->getShininess(Material::FRONT_AND_BACK);
1220 makeChild(matNode, "active")->setValue(true);
1221 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1222 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1223 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1224 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1225 makeChild(matNode, "shininess")->setValue(shininess);
1226 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1228 makeChild(matNode, "active")->setValue(false);
1230 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1231 string shadeModelString("smooth");
1233 ShadeModel::Mode smMode = sm->getMode();
1234 if (smMode == ShadeModel::FLAT)
1235 shadeModelString = "flat";
1237 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1238 string cullFaceString("off");
1239 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1241 switch (cullFace->getMode()) {
1242 case CullFace::FRONT:
1243 cullFaceString = "front";
1245 case CullFace::BACK:
1246 cullFaceString = "back";
1248 case CullFace::FRONT_AND_BACK:
1249 cullFaceString = "front-back";
1255 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1256 // Macintosh ATI workaround
1257 bool vertexTwoSide = cullFaceString == "off";
1258 makeChild(paramRoot, "vertex-program-two-side")->setValue(vertexTwoSide);
1259 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1260 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1262 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1263 string destMode = findName(blendFuncModes, blendFunc->getDestination());
1264 makeChild(blendNode, "active")->setValue(true);
1265 makeChild(blendNode, "source")->setStringValue(sourceMode);
1266 makeChild(blendNode, "destination")->setStringValue(destMode);
1267 makeChild(blendNode, "mode")->setValue(true);
1269 makeChild(blendNode, "active")->setValue(false);
1271 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1272 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1273 makeTextureParameters(paramRoot, ss);
1277 // Walk the techniques property tree, building techniques and
1279 bool Effect::realizeTechniques(const SGReaderWriterOptions* options)
1283 PropertyList tniqList = root->getChildren("technique");
1284 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1287 buildTechnique(this, *itr, options);
1292 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1294 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1297 Effect* effect = eg->getEffect();
1300 SGPropertyNode* root = getPropertyRoot();
1301 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1302 end = effect->_extraData.end();
1305 InitializeWhenAdded* adder
1306 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1308 adder->initOnAdd(effect, root);
1312 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1313 const Effect::Key& rhs) const
1315 if (lhs.paths.size() != rhs.paths.size()
1316 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1318 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1319 return props::Compare()(lhs.unmerged, rhs.unmerged);
1321 return lhs.unmerged == rhs.unmerged;
1324 size_t hash_value(const Effect::Key& key)
1327 if (key.unmerged.valid())
1328 boost::hash_combine(seed, *key.unmerged);
1329 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1333 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1335 const Effect& effect = static_cast<const Effect&>(obj);
1337 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1338 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1339 fw.writeObject(*technique);
1346 osgDB::RegisterDotOsgWrapperProxy effectProxy
1350 "Object simgear::Effect",
1352 &Effect_writeLocalData
1356 // Property expressions for technique predicates
1357 template<typename T>
1358 class PropertyExpression : public SGExpression<T>
1361 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode), _listener(NULL) {}
1363 ~PropertyExpression()
1368 void eval(T& value, const expression::Binding*) const
1370 value = _pnode->getValue<T>();
1373 void setListener(SGPropertyChangeListener* l)
1378 SGPropertyNode_ptr _pnode;
1379 SGPropertyChangeListener* _listener;
1382 class EffectPropertyListener : public SGPropertyChangeListener
1385 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1387 void valueChanged(SGPropertyNode* node)
1390 _tniq->refreshValidity();
1393 virtual ~EffectPropertyListener() { }
1396 osg::observer_ptr<Technique> _tniq;
1399 template<typename T>
1400 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1401 expression::Parser* parser)
1403 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1405 PropertyExpression<T>* pexp = new PropertyExpression<T>(pnode);
1406 TechniquePredParser* predParser
1407 = dynamic_cast<TechniquePredParser*>(parser);
1409 EffectPropertyListener* l = new EffectPropertyListener(predParser
1411 pexp->setListener(l);
1412 pnode->addChangeListener(l);
1417 expression::ExpParserRegistrar propertyRegistrar("property",
1418 propertyExpressionParser<bool>);
1420 expression::ExpParserRegistrar propvalueRegistrar("float-property",
1421 propertyExpressionParser<float>);