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