]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
400e350a5d0b7fb5d123ca309b05e36c00e29ff1
[simgear.git] / simgear / scene / material / Effect.cxx
1 // Copyright (C) 2008 - 2009  Tim Moore timoore@redhat.com
2 //
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.
7 //
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.
12 //
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.
16
17 #ifdef HAVE_CONFIG_H
18 #  include <simgear_config.h>
19 #endif
20
21 #include "Effect.hxx"
22 #include "EffectBuilder.hxx"
23 #include "EffectGeode.hxx"
24 #include "Technique.hxx"
25 #include "Pass.hxx"
26 #include "TextureBuilder.hxx"
27
28 #include <algorithm>
29 #include <functional>
30 #include <iterator>
31 #include <map>
32 #include <utility>
33 #include <boost/tr1/unordered_map.hpp>
34
35 #include <boost/bind.hpp>
36 #include <boost/foreach.hpp>
37 #include <boost/functional/hash.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #include <boost/tuple/tuple_comparison.hpp>
40
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/CullFace>
44 #include <osg/Depth>
45 #include <osg/Drawable>
46 #include <osg/Material>
47 #include <osg/Math>
48 #include <osg/PolygonMode>
49 #include <osg/Program>
50 #include <osg/Referenced>
51 #include <osg/RenderInfo>
52 #include <osg/ShadeModel>
53 #include <osg/StateSet>
54 #include <osg/Stencil>
55 #include <osg/TexEnv>
56 #include <osg/Texture1D>
57 #include <osg/Texture2D>
58 #include <osg/Texture3D>
59 #include <osg/TextureRectangle>
60 #include <osg/Uniform>
61 #include <osg/Vec4d>
62 #include <osgUtil/CullVisitor>
63 #include <osgDB/FileUtils>
64 #include <osgDB/Input>
65 #include <osgDB/ParameterOutput>
66 #include <osgDB/ReadFile>
67 #include <osgDB/Registry>
68
69 #include <simgear/scene/model/SGReaderWriterXMLOptions.hxx>
70 #include <simgear/scene/tgdb/userdata.hxx>
71 #include <simgear/scene/util/SGSceneFeatures.hxx>
72 #include <simgear/scene/util/StateAttributeFactory.hxx>
73 #include <simgear/structure/OSGUtils.hxx>
74 #include <simgear/structure/SGExpression.hxx>
75
76
77
78 namespace simgear
79 {
80 using namespace std;
81 using namespace osg;
82 using namespace osgUtil;
83
84 using namespace effect;
85
86 Effect::Effect()
87     : _cache(0), _isRealized(false)
88 {
89 }
90
91 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
92     : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
93       _isRealized(rhs._isRealized)
94 {
95     typedef vector<ref_ptr<Technique> > TechniqueList;
96     for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
97              end = rhs.techniques.end();
98          itr != end;
99          ++itr)
100         techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
101 }
102
103 // Assume that the last technique is always valid.
104 StateSet* Effect::getDefaultStateSet()
105 {
106     Technique* tniq = techniques.back().get();
107     if (!tniq)
108         return 0;
109     Pass* pass = tniq->passes.front().get();
110     return pass;
111 }
112
113 // There should always be a valid technique in an effect.
114
115 Technique* Effect::chooseTechnique(RenderInfo* info)
116 {
117     BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
118     {
119         if (technique->valid(info) == Technique::VALID)
120             return technique.get();
121     }
122     return 0;
123 }
124
125 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
126 {
127     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
128     {
129         technique->resizeGLObjectBuffers(maxSize);
130     }
131 }
132
133 void Effect::releaseGLObjects(osg::State* state) const
134 {
135     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
136     {
137         technique->releaseGLObjects(state);
138     }
139 }
140
141 Effect::~Effect()
142 {
143     delete _cache;
144 }
145
146 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
147                const SGReaderWriterXMLOptions* options)
148 {
149     Pass* pass = new Pass;
150     tniq->passes.push_back(pass);
151     for (int i = 0; i < prop->nChildren(); ++i) {
152         const SGPropertyNode* attrProp = prop->getChild(i);
153         PassAttributeBuilder* builder
154             = PassAttributeBuilder::find(attrProp->getNameString());
155         if (builder)
156             builder->buildAttribute(effect, pass, attrProp, options);
157         else
158             SG_LOG(SG_INPUT, SG_ALERT,
159                    "skipping unknown pass attribute " << attrProp->getName());
160     }
161 }
162
163 // Default names for vector property components
164 const char* vec3Names[] = {"x", "y", "z"};
165 const char* vec4Names[] = {"x", "y", "z", "w"};
166
167 osg::Vec4f getColor(const SGPropertyNode* prop)
168 {
169     if (prop->nChildren() == 0) {
170         if (prop->getType() == props::VEC4D) {
171             return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
172         } else if (prop->getType() == props::VEC3D) {
173             return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
174         } else {
175             SG_LOG(SG_INPUT, SG_ALERT,
176                    "invalid color property " << prop->getName() << " "
177                    << prop->getStringValue());
178             return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
179         }
180     } else {
181         osg::Vec4f result;
182         static const char* colors[] = {"r", "g", "b"};
183         for (int i = 0; i < 3; ++i) {
184             const SGPropertyNode* componentProp = prop->getChild(colors[i]);
185             result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
186         }
187         const SGPropertyNode* alphaProp = prop->getChild("a");
188         result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
189         return result;
190     }
191 }
192
193 struct LightingBuilder : public PassAttributeBuilder
194 {
195     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
196                         const SGReaderWriterXMLOptions* options);
197 };
198
199 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
200                                      const SGPropertyNode* prop,
201                                      const SGReaderWriterXMLOptions* options)
202 {
203     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
204     if (!realProp)
205         return;
206     pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
207                                 : StateAttribute::OFF));
208 }
209
210 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
211
212 struct ShadeModelBuilder : public PassAttributeBuilder
213 {
214     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
215                         const SGReaderWriterXMLOptions* options)
216     {
217         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
218         if (!realProp)
219             return;
220         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
221         string propVal = realProp->getStringValue();
222         if (propVal == "flat")
223             pass->setAttribute(attrFact->getFlatShadeModel());
224         else if (propVal == "smooth")
225             pass->setAttribute(attrFact->getSmoothShadeModel());
226         else
227             SG_LOG(SG_INPUT, SG_ALERT,
228                    "invalid shade model property " << propVal);
229     }
230 };
231
232 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
233
234 struct CullFaceBuilder : PassAttributeBuilder
235 {
236     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
237                         const SGReaderWriterXMLOptions* options)
238     {
239         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
240         if (!realProp) {
241             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
242             return;
243         }
244         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
245         string propVal = realProp->getStringValue();
246         if (propVal == "front")
247             pass->setAttributeAndModes(attrFact->getCullFaceFront());
248         else if (propVal == "back")
249             pass->setAttributeAndModes(attrFact->getCullFaceBack());
250         else if (propVal == "front-back")
251             pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
252         else if (propVal == "off")
253             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
254         else
255             SG_LOG(SG_INPUT, SG_ALERT,
256                    "invalid cull face property " << propVal);            
257     }    
258 };
259
260 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
261
262 struct ColorMaskBuilder : PassAttributeBuilder
263 {
264     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
265                         const SGReaderWriterXMLOptions* options)
266     {
267         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
268         if (!realProp)
269             return;
270
271         ColorMask *mask = new ColorMask;
272         Vec4 m = getColor(realProp);
273         mask->setMask(m.r(), m.g(), m.b(), m.a());
274         pass->setAttributeAndModes(mask);
275     }    
276 };
277
278 InstallAttributeBuilder<ColorMaskBuilder> installColorMask("color-mask");
279
280 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
281 {
282     { "default", StateSet::DEFAULT_BIN },
283     { "opaque", StateSet::OPAQUE_BIN },
284     { "transparent", StateSet::TRANSPARENT_BIN }
285 };
286
287 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
288
289 struct HintBuilder : public PassAttributeBuilder
290 {
291     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
292                         const SGReaderWriterXMLOptions* options)
293     {
294         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
295         if (!realProp)
296             return;
297         StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
298         findAttr(renderingHints, realProp, renderingHint);
299         pass->setRenderingHint(renderingHint);
300     }    
301 };
302
303 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
304
305 struct RenderBinBuilder : public PassAttributeBuilder
306 {
307     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
308                         const SGReaderWriterXMLOptions* options)
309     {
310         if (!isAttributeActive(effect, prop))
311             return;
312         const SGPropertyNode* binProp = prop->getChild("bin-number");
313         binProp = getEffectPropertyNode(effect, binProp);
314         const SGPropertyNode* nameProp = prop->getChild("bin-name");
315         nameProp = getEffectPropertyNode(effect, nameProp);
316         if (binProp && nameProp) {
317             pass->setRenderBinDetails(binProp->getIntValue(),
318                                       nameProp->getStringValue());
319         } else {
320             if (!binProp)
321                 SG_LOG(SG_INPUT, SG_ALERT,
322                        "No render bin number specified in render bin section");
323             if (!nameProp)
324                 SG_LOG(SG_INPUT, SG_ALERT,
325                        "No render bin name specified in render bin section");
326         }
327     }
328 };
329
330 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
331
332 struct MaterialBuilder : public PassAttributeBuilder
333 {
334     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
335                         const SGReaderWriterXMLOptions* options);
336 };
337
338 EffectNameValue<Material::ColorMode> colorModeInit[] =
339 {
340     { "ambient", Material::AMBIENT },
341     { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
342     { "diffuse", Material::DIFFUSE },
343     { "emissive", Material::EMISSION },
344     { "specular", Material::SPECULAR },
345     { "off", Material::OFF }
346 };
347 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
348
349 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
350                                      const SGPropertyNode* prop,
351                                      const SGReaderWriterXMLOptions* options)
352 {
353     if (!isAttributeActive(effect, prop))
354         return;
355     Material* mat = new Material;
356     const SGPropertyNode* color = 0;
357     if ((color = getEffectPropertyChild(effect, prop, "ambient")))
358         mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
359     if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
360         mat->setAmbient(Material::FRONT, getColor(color));
361     if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
362         mat->setAmbient(Material::BACK, getColor(color));
363     if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
364         mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
365     if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
366         mat->setDiffuse(Material::FRONT, getColor(color));
367     if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
368         mat->setDiffuse(Material::BACK, getColor(color));
369     if ((color = getEffectPropertyChild(effect, prop, "specular")))
370         mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
371     if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
372         mat->setSpecular(Material::FRONT, getColor(color));
373     if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
374         mat->setSpecular(Material::BACK, getColor(color));
375     if ((color = getEffectPropertyChild(effect, prop, "emissive")))
376         mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
377     if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
378         mat->setEmission(Material::FRONT, getColor(color));        
379     if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
380         mat->setEmission(Material::BACK, getColor(color));        
381     const SGPropertyNode* shininess = 0;
382     mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
383     if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
384         mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
385     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
386         mat->setShininess(Material::FRONT, shininess->getFloatValue());
387     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
388         mat->setShininess(Material::BACK, shininess->getFloatValue());
389     Material::ColorMode colorMode = Material::OFF;
390     findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
391              colorMode);
392     mat->setColorMode(colorMode);
393     pass->setAttribute(mat);
394 }
395
396 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
397
398 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
399 {
400     {"dst-alpha", BlendFunc::DST_ALPHA},
401     {"dst-color", BlendFunc::DST_COLOR},
402     {"one", BlendFunc::ONE},
403     {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
404     {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
405     {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
406     {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
407     {"src-alpha", BlendFunc::SRC_ALPHA},
408     {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
409     {"src-color", BlendFunc::SRC_COLOR},
410     {"constant-color", BlendFunc::CONSTANT_COLOR},
411     {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
412     {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
413     {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
414     {"zero", BlendFunc::ZERO}
415 };
416 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
417
418 struct BlendBuilder : public PassAttributeBuilder
419 {
420     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
421                         const SGReaderWriterXMLOptions* options)
422     {
423         if (!isAttributeActive(effect, prop))
424             return;
425         // XXX Compatibility with early <blend> syntax; should go away
426         // before a release
427         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
428         if (!realProp)
429             return;
430         if (realProp->nChildren() == 0) {
431             pass->setMode(GL_BLEND, (realProp->getBoolValue()
432                                      ? StateAttribute::ON
433                                      : StateAttribute::OFF));
434             return;
435         }
436
437         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
438                                                              "mode");
439         // XXX When dynamic parameters are supported, this code should
440         // create the blend function even if the mode is off.
441         if (pmode && !pmode->getValue<bool>()) {
442             pass->setMode(GL_BLEND, StateAttribute::OFF);
443             return;
444         }
445         const SGPropertyNode* psource
446             = getEffectPropertyChild(effect, prop, "source");
447         const SGPropertyNode* pdestination
448             = getEffectPropertyChild(effect, prop, "destination");
449         const SGPropertyNode* psourceRGB
450             = getEffectPropertyChild(effect, prop, "source-rgb");
451         const SGPropertyNode* psourceAlpha
452             = getEffectPropertyChild(effect, prop, "source-alpha");
453         const SGPropertyNode* pdestRGB
454             = getEffectPropertyChild(effect, prop, "destination-rgb");
455         const SGPropertyNode* pdestAlpha
456             = getEffectPropertyChild(effect, prop, "destination-alpha");
457         BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
458         BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
459         if (psource)
460             findAttr(blendFuncModes, psource, sourceMode);
461         if (pdestination)
462             findAttr(blendFuncModes, pdestination, destMode);
463         if (psource && pdestination
464             && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
465             && sourceMode == BlendFunc::SRC_ALPHA
466             && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
467             pass->setAttributeAndModes(StateAttributeFactory::instance()
468                                        ->getStandardBlendFunc());
469             return;
470         }
471         BlendFunc* blendFunc = new BlendFunc;
472         if (psource)
473             blendFunc->setSource(sourceMode);
474         if (pdestination)
475             blendFunc->setDestination(destMode);
476         if (psourceRGB) {
477             BlendFunc::BlendFuncMode sourceRGBMode;
478             findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
479             blendFunc->setSourceRGB(sourceRGBMode);
480         }
481         if (pdestRGB) {
482             BlendFunc::BlendFuncMode destRGBMode;
483             findAttr(blendFuncModes, pdestRGB, destRGBMode);
484             blendFunc->setDestinationRGB(destRGBMode);
485         }
486         if (psourceAlpha) {
487             BlendFunc::BlendFuncMode sourceAlphaMode;
488             findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
489             blendFunc->setSourceAlpha(sourceAlphaMode);
490         }
491         if (pdestAlpha) {
492             BlendFunc::BlendFuncMode destAlphaMode;
493             findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
494             blendFunc->setDestinationAlpha(destAlphaMode);
495         }
496         pass->setAttributeAndModes(blendFunc);
497     }
498 };
499
500 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
501
502
503 EffectNameValue<Stencil::Function> stencilFunctionInit[] =
504 {
505     {"never", Stencil::NEVER },
506     {"less", Stencil::LESS},
507     {"equal", Stencil::EQUAL},
508     {"less-or-equal", Stencil::LEQUAL},
509     {"greater", Stencil::GREATER},
510     {"not-equal", Stencil::NOTEQUAL},
511     {"greater-or-equal", Stencil::GEQUAL},
512     {"always", Stencil::ALWAYS}
513 };
514
515 EffectPropertyMap<Stencil::Function> stencilFunction(stencilFunctionInit);
516
517 EffectNameValue<Stencil::Operation> stencilOperationInit[] =
518 {
519     {"keep", Stencil::KEEP},
520     {"zero", Stencil::ZERO},
521     {"replace", Stencil::REPLACE},
522     {"increase", Stencil::INCR},
523     {"decrease", Stencil::DECR},
524     {"invert", Stencil::INVERT},
525     {"increase-wrap", Stencil::INCR_WRAP},
526     {"decrease-wrap", Stencil::DECR_WRAP}
527 };
528
529 EffectPropertyMap<Stencil::Operation> stencilOperation(stencilOperationInit);
530
531 struct StencilBuilder : public PassAttributeBuilder
532 {
533     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
534                         const SGReaderWriterXMLOptions* options)
535     {
536         if (!isAttributeActive(effect, prop))
537             return;
538
539         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
540                                                              "mode");
541         if (pmode && !pmode->getValue<bool>()) {
542             pass->setMode(GL_STENCIL, StateAttribute::OFF);
543             return;
544         }
545         const SGPropertyNode* pfunction
546             = getEffectPropertyChild(effect, prop, "function");
547         const SGPropertyNode* pvalue
548             = getEffectPropertyChild(effect, prop, "value");
549         const SGPropertyNode* pmask
550             = getEffectPropertyChild(effect, prop, "mask");
551         const SGPropertyNode* psfail
552             = getEffectPropertyChild(effect, prop, "stencil-fail");
553         const SGPropertyNode* pzfail
554             = getEffectPropertyChild(effect, prop, "z-fail");
555         const SGPropertyNode* ppass
556             = getEffectPropertyChild(effect, prop, "pass");
557
558         Stencil::Function func = Stencil::ALWAYS;  // Always pass
559         int ref = 0;
560         unsigned int mask = ~0u;  // All bits on
561         Stencil::Operation sfailop = Stencil::KEEP;  // Keep the old values as default
562         Stencil::Operation zfailop = Stencil::KEEP;
563         Stencil::Operation passop = Stencil::KEEP;
564
565         ref_ptr<Stencil> stencilFunc = new Stencil;
566
567         if (pfunction)
568             findAttr(stencilFunction, pfunction, func);
569         if (pvalue)
570             ref = pvalue->getIntValue();
571         if (pmask) 
572             mask = pmask->getIntValue();
573
574         if (psfail)
575             findAttr(stencilOperation, psfail, sfailop);
576         if (pzfail)
577             findAttr(stencilOperation, pzfail, zfailop);
578         if (ppass)
579             findAttr(stencilOperation, ppass, passop);
580
581         // Set the stencil operation
582         stencilFunc->setFunction(func, ref, mask);
583
584         // Set the operation, s-fail, s-pass/z-fail, s-pass/z-pass
585         stencilFunc->setOperation(sfailop, zfailop, passop);
586
587         // Add the operation to pass
588         pass->setAttributeAndModes(stencilFunc.get());
589     }
590 };
591
592 InstallAttributeBuilder<StencilBuilder> installStencil("stencil");
593
594
595 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
596 {
597     {"never", AlphaFunc::NEVER},
598     {"less", AlphaFunc::LESS},
599     {"equal", AlphaFunc::EQUAL},
600     {"lequal", AlphaFunc::LEQUAL},
601     {"greater", AlphaFunc::GREATER},
602     {"notequal", AlphaFunc::NOTEQUAL},
603     {"gequal", AlphaFunc::GEQUAL},
604     {"always", AlphaFunc::ALWAYS}
605 };
606 EffectPropertyMap<AlphaFunc::ComparisonFunction>
607 alphaComparison(alphaComparisonInit);
608
609 struct AlphaTestBuilder : public PassAttributeBuilder
610 {
611     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
612                         const SGReaderWriterXMLOptions* options)
613     {
614         if (!isAttributeActive(effect, prop))
615             return;
616         // XXX Compatibility with early <alpha-test> syntax; should go away
617         // before a release
618         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
619         if (!realProp)
620             return;
621         if (realProp->nChildren() == 0) {
622             pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
623                                      ? StateAttribute::ON
624                                      : StateAttribute::OFF));
625             return;
626         }
627
628         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
629                                                              "mode");
630         // XXX When dynamic parameters are supported, this code should
631         // create the blend function even if the mode is off.
632         if (pmode && !pmode->getValue<bool>()) {
633             pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
634             return;
635         }
636         const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
637                                                              "comparison");
638         const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
639                                                              "reference");
640         AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
641         float refValue = 1.0f;
642         if (pComp)
643             findAttr(alphaComparison, pComp, func);
644         if (pRef)
645             refValue = pRef->getValue<float>();
646         if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
647             pass->setAttributeAndModes(StateAttributeFactory::instance()
648                                        ->getStandardAlphaFunc());
649         } else {
650             AlphaFunc* alphaFunc = new AlphaFunc;
651             alphaFunc->setFunction(func);
652             alphaFunc->setReferenceValue(refValue);
653             pass->setAttributeAndModes(alphaFunc);
654         }
655     }
656 };
657
658 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
659
660 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
661
662 // Shader key, used both for shaders with relative and absolute names
663 typedef pair<string, Shader::Type> ShaderKey;
664
665 struct ProgramKey
666 {
667     typedef pair<string, int> AttribKey;
668     osgDB::FilePathList paths;
669     vector<ShaderKey> shaders;
670     vector<AttribKey> attributes;
671     struct EqualTo
672     {
673         bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
674         {
675             return (lhs.paths.size() == rhs.paths.size()
676                     && equal(lhs.paths.begin(), lhs.paths.end(),
677                              rhs.paths.begin())
678                     && lhs.shaders.size() == rhs.shaders.size()
679                     && equal (lhs.shaders.begin(), lhs.shaders.end(),
680                               rhs.shaders.begin())
681                     && lhs.attributes.size() == rhs.attributes.size()
682                     && equal(lhs.attributes.begin(), lhs.attributes.end(),
683                              rhs.attributes.begin()));
684         }
685     };
686 };
687
688 size_t hash_value(const ProgramKey& key)
689 {
690     size_t seed = 0;
691     boost::hash_range(seed, key.paths.begin(), key.paths.end());
692     boost::hash_range(seed, key.shaders.begin(), key.shaders.end());
693     boost::hash_range(seed, key.attributes.begin(), key.attributes.end());
694     return seed;
695 }
696
697 // XXX Should these be protected by a mutex? Probably
698
699 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
700                            boost::hash<ProgramKey>, ProgramKey::EqualTo>
701 ProgramMap;
702 ProgramMap programMap;
703
704 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
705 ShaderMap;
706 ShaderMap shaderMap;
707
708 void reload_shaders()
709 {
710     for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
711     {
712         Shader *shader = sitr->second.get();
713         string fileName = osgDB::findDataFile(sitr->first.first);
714         if (!fileName.empty()) {
715             shader->loadShaderSourceFromFile(fileName);
716         }
717     }
718 }
719
720 struct ShaderProgramBuilder : PassAttributeBuilder
721 {
722     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
723                         const SGReaderWriterXMLOptions* options);
724 };
725
726 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
727                                           const SGPropertyNode* prop,
728                                           const SGReaderWriterXMLOptions*
729                                           options)
730 {
731     using namespace boost;
732     if (!isAttributeActive(effect, prop))
733         return;
734     PropertyList pVertShaders = prop->getChildren("vertex-shader");
735     PropertyList pFragShaders = prop->getChildren("fragment-shader");
736     PropertyList pAttributes = prop->getChildren("attribute");
737     ProgramKey prgKey;
738     for (PropertyList::iterator itr = pVertShaders.begin(),
739              e = pVertShaders.end();
740          itr != e;
741          ++itr)
742         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
743                                            Shader::VERTEX));
744     for (PropertyList::iterator itr = pFragShaders.begin(),
745              e = pFragShaders.end();
746          itr != e;
747          ++itr)
748         prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
749                                            Shader::FRAGMENT));
750     for (PropertyList::iterator itr = pAttributes.begin(),
751              e = pAttributes.end();
752          itr != e;
753          ++itr) {
754         const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
755                                                              "name");
756         const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
757                                                               "index");
758         if (!pName || ! pIndex)
759             throw BuilderException("malformed attribute property");
760         prgKey.attributes
761             .push_back(ProgramKey::AttribKey(pName->getStringValue(),
762                                              pIndex->getValue<int>()));
763     }
764     if (options)
765         prgKey.paths = options->getDatabasePathList();
766     Program* program = 0;
767     ProgramMap::iterator pitr = programMap.find(prgKey);
768     if (pitr != programMap.end()) {
769         program = pitr->second.get();
770     } else {
771         program = new Program;
772         // Add vertex shaders, then fragment shaders
773         PropertyList& pvec = pVertShaders;
774         Shader::Type stype = Shader::VERTEX;
775         for (int i = 0; i < 2; ++i) {
776             for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
777                  nameItr != e;
778                  ++nameItr) {
779                 string shaderName = (*nameItr)->getStringValue();
780                 string fileName = osgDB::findDataFile(shaderName, options);
781                 if (fileName.empty())
782                     throw BuilderException(string("couldn't find shader ") +
783                                            shaderName);
784                 ShaderKey skey(fileName, stype);
785                 ShaderMap::iterator sitr = shaderMap.find(skey);
786                 if (sitr != shaderMap.end()) {
787                     program->addShader(sitr->second.get());
788                 } else {
789                     ref_ptr<Shader> shader = new Shader(stype);
790                     if (shader->loadShaderSourceFromFile(fileName)) {
791                         program->addShader(shader.get());
792                         shaderMap.insert(ShaderMap::value_type(skey, shader));
793                     }
794                 }
795             }
796             pvec = pFragShaders;
797             stype = Shader::FRAGMENT;
798         }
799         BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
800             program->addBindAttribLocation(key.first, key.second);
801         }
802        programMap.insert(ProgramMap::value_type(prgKey, program));
803     }
804     pass->setAttributeAndModes(program);
805 }
806
807 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
808
809 EffectNameValue<Uniform::Type> uniformTypesInit[] =
810 {
811     {"float", Uniform::FLOAT},
812     {"float-vec3", Uniform::FLOAT_VEC3},
813     {"float-vec4", Uniform::FLOAT_VEC4},
814     {"sampler-1d", Uniform::SAMPLER_1D},
815     {"sampler-1d-shadow", Uniform::SAMPLER_1D_SHADOW},
816     {"sampler-2d", Uniform::SAMPLER_2D},
817     {"sampler-2d-shadow", Uniform::SAMPLER_2D_SHADOW},
818     {"sampler-3d", Uniform::SAMPLER_3D},
819     {"sampler-cube", Uniform::SAMPLER_CUBE}
820 };
821 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
822
823 struct UniformBuilder :public PassAttributeBuilder
824 {
825     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
826                         const SGReaderWriterXMLOptions* options)
827     {
828         if (!isAttributeActive(effect, prop))
829             return;
830         const SGPropertyNode* nameProp = prop->getChild("name");
831         const SGPropertyNode* typeProp = prop->getChild("type");
832         const SGPropertyNode* valProp
833             = getEffectPropertyChild(effect, prop, "value");
834         string name;
835         Uniform::Type uniformType = Uniform::FLOAT;
836         if (nameProp) {
837             name = nameProp->getStringValue();
838         } else {
839             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
840             return;
841         }
842         if (!valProp) {
843             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
844                    << name);
845             return;
846         }
847         if (!typeProp) {
848             props::Type propType = valProp->getType();
849             switch (propType) {
850             case props::FLOAT:
851             case props::DOUBLE:
852                 break;          // default float type;
853             case props::VEC3D:
854                 uniformType = Uniform::FLOAT_VEC3;
855                 break;
856             case props::VEC4D:
857                 uniformType = Uniform::FLOAT_VEC4;
858                 break;
859             default:
860                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
861                        << name);
862                 return;
863             }
864         } else {
865             findAttr(uniformTypes, typeProp, uniformType);
866         }
867         ref_ptr<Uniform> uniform = new Uniform;
868         uniform->setName(name);
869         uniform->setType(uniformType);
870         switch (uniformType) {
871         case Uniform::FLOAT:
872             initFromParameters(effect, valProp, uniform.get(),
873                                static_cast<bool (Uniform::*)(float)>(&Uniform::set),
874                                options);
875             break;
876         case Uniform::FLOAT_VEC3:
877             initFromParameters(effect, valProp, uniform.get(),
878                                static_cast<bool (Uniform::*)(const Vec3&)>(&Uniform::set),
879                                vec3Names, options);
880             break;
881         case Uniform::FLOAT_VEC4:
882             initFromParameters(effect, valProp, uniform.get(),
883                                static_cast<bool (Uniform::*)(const Vec4&)>(&Uniform::set),
884                                vec4Names, options);
885             break;
886         case Uniform::SAMPLER_1D:
887         case Uniform::SAMPLER_2D:
888         case Uniform::SAMPLER_3D:
889         case Uniform::SAMPLER_1D_SHADOW:
890         case Uniform::SAMPLER_2D_SHADOW:
891         case Uniform::SAMPLER_CUBE:
892             initFromParameters(effect, valProp, uniform.get(),
893                                static_cast<bool (Uniform::*)(int)>(&Uniform::set),
894                                options);
895             break;
896         default: // avoid compiler warning
897             break;
898         }
899         pass->addUniform(uniform.get());
900     }
901 };
902
903 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
904
905 // Not sure what to do with "name". At one point I wanted to use it to
906 // order the passes, but I do support render bin and stuff too...
907
908 struct NameBuilder : public PassAttributeBuilder
909 {
910     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
911                         const SGReaderWriterXMLOptions* options)
912     {
913         // name can't use <use>
914         string name = prop->getStringValue();
915         if (!name.empty())
916             pass->setName(name);
917     }
918 };
919
920 InstallAttributeBuilder<NameBuilder> installName("name");
921
922 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
923 {
924     {"fill", PolygonMode::FILL},
925     {"line", PolygonMode::LINE},
926     {"point", PolygonMode::POINT}
927 };
928 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
929
930 struct PolygonModeBuilder : public PassAttributeBuilder
931 {
932     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
933                         const SGReaderWriterXMLOptions* options)
934     {
935         if (!isAttributeActive(effect, prop))
936             return;
937         const SGPropertyNode* frontProp
938             = getEffectPropertyChild(effect, prop, "front");
939         const SGPropertyNode* backProp
940             = getEffectPropertyChild(effect, prop, "back");
941         ref_ptr<PolygonMode> pmode = new PolygonMode;
942         PolygonMode::Mode frontMode = PolygonMode::FILL;
943         PolygonMode::Mode backMode = PolygonMode::FILL;
944         if (frontProp) {
945             findAttr(polygonModeModes, frontProp, frontMode);
946             pmode->setMode(PolygonMode::FRONT, frontMode);
947         }
948         if (backProp) {
949             findAttr(polygonModeModes, backProp, backMode);
950             pmode->setMode(PolygonMode::BACK, backMode);
951         }
952         pass->setAttribute(pmode.get());
953     }
954 };
955
956 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
957
958 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
959 {
960     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
961                         const SGReaderWriterXMLOptions* options)
962     {
963         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
964         if (!realProp)
965             return;
966         pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
967                       (realProp->getValue<bool>()
968                        ? StateAttribute::ON : StateAttribute::OFF));
969     }
970 };
971
972 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
973 installTwoSide("vertex-program-two-side");
974
975 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
976 {
977     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
978                         const SGReaderWriterXMLOptions* options)
979     {
980         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
981         if (!realProp)
982             return;
983         pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
984                       (realProp->getValue<bool>()
985                        ? StateAttribute::ON : StateAttribute::OFF));
986     }
987 };
988
989 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
990 installPointSize("vertex-program-point-size");
991
992 EffectNameValue<Depth::Function> depthFunctionInit[] =
993 {
994     {"never", Depth::NEVER},
995     {"less", Depth::LESS},
996     {"equal", Depth::EQUAL},
997     {"lequal", Depth::LEQUAL},
998     {"greater", Depth::GREATER},
999     {"notequal", Depth::NOTEQUAL},
1000     {"gequal", Depth::GEQUAL},
1001     {"always", Depth::ALWAYS}
1002 };
1003 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
1004
1005 struct DepthBuilder : public PassAttributeBuilder
1006 {
1007     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
1008                         const SGReaderWriterXMLOptions* options)
1009     {
1010         if (!isAttributeActive(effect, prop))
1011             return;
1012         ref_ptr<Depth> depth = new Depth;
1013         const SGPropertyNode* pfunc
1014             = getEffectPropertyChild(effect, prop, "function");
1015         if (pfunc) {
1016             Depth::Function func = Depth::LESS;
1017             findAttr(depthFunction, pfunc, func);
1018             depth->setFunction(func);
1019         }
1020         const SGPropertyNode* pnear
1021             = getEffectPropertyChild(effect, prop, "near");
1022         if (pnear)
1023             depth->setZNear(pnear->getValue<double>());
1024         const SGPropertyNode* pfar
1025             = getEffectPropertyChild(effect, prop, "far");
1026         if (pfar)
1027             depth->setZFar(pnear->getValue<double>());
1028         const SGPropertyNode* pmask
1029             = getEffectPropertyChild(effect, prop, "write-mask");
1030         if (pmask)
1031             depth->setWriteMask(pmask->getValue<bool>());
1032         pass->setAttribute(depth.get());
1033     }
1034 };
1035
1036 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
1037
1038 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
1039                     const SGReaderWriterXMLOptions* options)
1040 {
1041     Technique* tniq = new Technique;
1042     effect->techniques.push_back(tniq);
1043     const SGPropertyNode* predProp = prop->getChild("predicate");
1044     if (!predProp) {
1045         tniq->setAlwaysValid(true);
1046     } else {
1047         try {
1048             TechniquePredParser parser;
1049             parser.setTechnique(tniq);
1050             expression::BindingLayout& layout = parser.getBindingLayout();
1051             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
1052             SGExpressionb* validExp
1053                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
1054                                                            ->getChild(0)));
1055             if (validExp)
1056                 tniq->setValidExpression(validExp, layout);
1057             else
1058                 throw expression::ParseError("technique predicate is not a boolean expression");
1059         }
1060         catch (expression::ParseError& except)
1061         {
1062             SG_LOG(SG_INPUT, SG_ALERT,
1063                    "parsing technique predicate " << except.getMessage());
1064             tniq->setAlwaysValid(false);
1065         }
1066     }
1067     PropertyList passProps = prop->getChildren("pass");
1068     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
1069          itr != e;
1070          ++itr) {
1071         buildPass(effect, tniq, itr->ptr(), options);
1072     }
1073 }
1074
1075 // Specifically for .ac files...
1076 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
1077 {
1078     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
1079     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
1080     Vec4f ambVal, difVal, specVal, emisVal;
1081     float shininess = 0.0f;
1082     const Material* mat = getStateAttribute<Material>(ss);
1083     if (mat) {
1084         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
1085         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
1086         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
1087         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
1088         shininess = mat->getShininess(Material::FRONT_AND_BACK);
1089         makeChild(matNode, "active")->setValue(true);
1090         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
1091         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
1092         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
1093         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
1094         makeChild(matNode, "shininess")->setValue(shininess);
1095         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
1096     } else {
1097         makeChild(matNode, "active")->setValue(false);
1098     }
1099     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
1100     string shadeModelString("smooth");
1101     if (sm) {
1102         ShadeModel::Mode smMode = sm->getMode();
1103         if (smMode == ShadeModel::FLAT)
1104             shadeModelString = "flat";
1105     }
1106     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
1107     string cullFaceString("off");
1108     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
1109     if (cullFace) {
1110         switch (cullFace->getMode()) {
1111         case CullFace::FRONT:
1112             cullFaceString = "front";
1113             break;
1114         case CullFace::BACK:
1115             cullFaceString = "back";
1116             break;
1117         case CullFace::FRONT_AND_BACK:
1118             cullFaceString = "front-back";
1119             break;
1120         default:
1121             break;
1122         }
1123     }
1124     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
1125     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
1126     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
1127     if (blendFunc) {
1128         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
1129         string destMode = findName(blendFuncModes, blendFunc->getDestination());
1130         makeChild(blendNode, "active")->setValue(true);
1131         makeChild(blendNode, "source")->setStringValue(sourceMode);
1132         makeChild(blendNode, "destination")->setStringValue(destMode);
1133         makeChild(blendNode, "mode")->setValue(true);
1134     } else {
1135         makeChild(blendNode, "active")->setValue(false);
1136     }
1137     string renderingHint = findName(renderingHints, ss->getRenderingHint());
1138     makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1139     makeTextureParameters(paramRoot, ss);
1140     return true;
1141 }
1142
1143 // Walk the techniques property tree, building techniques and
1144 // passes.
1145 bool Effect::realizeTechniques(const SGReaderWriterXMLOptions* options)
1146 {
1147     if (_isRealized)
1148         return true;
1149     PropertyList tniqList = root->getChildren("technique");
1150     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1151          itr != e;
1152          ++itr)
1153         buildTechnique(this, *itr, options);
1154     _isRealized = true;
1155     return true;
1156 }
1157
1158 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1159 {
1160     EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1161     if (!eg)
1162         return;
1163     Effect* effect = eg->getEffect();
1164     if (!effect)
1165         return;
1166     SGPropertyNode* root = getPropertyRoot();
1167     for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1168              end = effect->_extraData.end();
1169          itr != end;
1170          ++itr) {
1171         InitializeWhenAdded* adder
1172             = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1173         if (adder)
1174             adder->initOnAdd(effect, root);
1175     }
1176 }
1177
1178 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1179                                       const Effect::Key& rhs) const
1180 {
1181     if (lhs.paths.size() != rhs.paths.size()
1182         || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1183         return false;
1184     if (lhs.unmerged.valid() && rhs.unmerged.valid())
1185         return props::Compare()(lhs.unmerged, rhs.unmerged);
1186     else
1187         return lhs.unmerged == rhs.unmerged;
1188 }
1189
1190 size_t hash_value(const Effect::Key& key)
1191 {
1192     size_t seed = 0;
1193     if (key.unmerged.valid())
1194         boost::hash_combine(seed, *key.unmerged);
1195     boost::hash_range(seed, key.paths.begin(), key.paths.end());
1196     return seed;
1197 }
1198
1199 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1200 {
1201     const Effect& effect = static_cast<const Effect&>(obj);
1202
1203     fw.indent() << "techniques " << effect.techniques.size() << "\n";
1204     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1205         fw.writeObject(*technique);
1206     }
1207     return true;
1208 }
1209
1210 namespace
1211 {
1212 osgDB::RegisterDotOsgWrapperProxy effectProxy
1213 (
1214     new Effect,
1215     "simgear::Effect",
1216     "Object simgear::Effect",
1217     0,
1218     &Effect_writeLocalData
1219     );
1220 }
1221
1222 // Property expressions for technique predicates
1223 class PropertyExpression : public SGExpression<bool>
1224 {
1225 public:
1226     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1227     
1228     void eval(bool& value, const expression::Binding*) const
1229     {
1230         value = _pnode->getValue<bool>();
1231     }
1232 protected:
1233     SGPropertyNode_ptr _pnode;
1234 };
1235
1236 class EffectPropertyListener : public SGPropertyChangeListener
1237 {
1238 public:
1239     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1240     
1241     void valueChanged(SGPropertyNode* node)
1242     {
1243         _tniq->refreshValidity();
1244     }
1245 protected:
1246     osg::ref_ptr<Technique> _tniq;
1247 };
1248
1249 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1250                                      expression::Parser* parser)
1251 {
1252     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1253                                                           true);
1254     PropertyExpression* pexp = new PropertyExpression(pnode);
1255     TechniquePredParser* predParser
1256         = dynamic_cast<TechniquePredParser*>(parser);
1257     if (predParser)
1258         pnode->addChangeListener(new EffectPropertyListener(predParser
1259                                                             ->getTechnique()));
1260     return pexp;
1261 }
1262
1263 expression::ExpParserRegistrar propertyRegistrar("property",
1264                                                  propertyExpressionParser);
1265
1266 }