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