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