]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
0ec20275611edb7a59e3ab09b3fe1c8d669252cd
[simgear.git] / simgear / scene / material / Effect.cxx
1 // Copyright (C) 2008 - 2009  Tim Moore timoore@redhat.com
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Library General Public
5 // License as published by the Free Software Foundation; either
6 // version 2 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Library General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
16
17 #ifdef HAVE_CONFIG_H
18 #  include <simgear_config.h>
19 #endif
20
21 #include "Effect.hxx"
22 #include "EffectBuilder.hxx"
23 #include "Technique.hxx"
24 #include "Pass.hxx"
25 #include "TextureBuilder.hxx"
26
27 #include <algorithm>
28 #include <functional>
29 #include <iterator>
30 #include <map>
31 #include <utility>
32
33 #include <boost/foreach.hpp>
34 #include <boost/tuple/tuple.hpp>
35 #include <boost/tuple/tuple_comparison.hpp>
36
37 #include <osg/AlphaFunc>
38 #include <osg/BlendFunc>
39 #include <osg/CullFace>
40 #include <osg/Drawable>
41 #include <osg/Material>
42 #include <osg/Math>
43 #include <osg/PolygonMode>
44 #include <osg/Program>
45 #include <osg/Referenced>
46 #include <osg/RenderInfo>
47 #include <osg/ShadeModel>
48 #include <osg/StateSet>
49 #include <osg/TexEnv>
50 #include <osg/Texture1D>
51 #include <osg/Texture2D>
52 #include <osg/Texture3D>
53 #include <osg/TextureRectangle>
54 #include <osg/Uniform>
55 #include <osg/Vec4d>
56 #include <osgUtil/CullVisitor>
57 #include <osgDB/FileUtils>
58 #include <osgDB/Input>
59 #include <osgDB/ParameterOutput>
60 #include <osgDB/ReadFile>
61 #include <osgDB/Registry>
62
63 #include <simgear/scene/tgdb/userdata.hxx>
64 #include <simgear/scene/util/SGSceneFeatures.hxx>
65 #include <simgear/scene/util/StateAttributeFactory.hxx>
66 #include <simgear/structure/OSGUtils.hxx>
67 #include <simgear/structure/SGExpression.hxx>
68
69
70
71 namespace simgear
72 {
73 using namespace std;
74 using namespace osg;
75 using namespace osgUtil;
76
77 using namespace effect;
78
79 Effect::Effect()
80 {
81 }
82
83 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
84     : root(rhs.root), parametersProp(rhs.parametersProp)
85 {
86     typedef vector<ref_ptr<Technique> > TechniqueList;
87     for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
88              end = rhs.techniques.end();
89          itr != end;
90          ++itr)
91         techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
92 }
93
94 // Assume that the last technique is always valid.
95 StateSet* Effect::getDefaultStateSet()
96 {
97     Technique* tniq = techniques.back().get();
98     if (!tniq)
99         return 0;
100     Pass* pass = tniq->passes.front().get();
101     return pass;
102 }
103
104 // There should always be a valid technique in an effect.
105
106 Technique* Effect::chooseTechnique(RenderInfo* info)
107 {
108     BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
109     {
110         if (technique->valid(info) == Technique::VALID)
111             return technique.get();
112     }
113     return 0;
114 }
115
116 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
117 {
118     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
119     {
120         technique->resizeGLObjectBuffers(maxSize);
121     }
122 }
123
124 void Effect::releaseGLObjects(osg::State* state) const
125 {
126     BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
127     {
128         technique->releaseGLObjects(state);
129     }
130 }
131
132 Effect::~Effect()
133 {
134 }
135
136 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
137                const osgDB::ReaderWriter::Options* options)
138 {
139     Pass* pass = new Pass;
140     tniq->passes.push_back(pass);
141     for (int i = 0; i < prop->nChildren(); ++i) {
142         const SGPropertyNode* attrProp = prop->getChild(i);
143         PassAttributeBuilder* builder
144             = PassAttributeBuilder::find(attrProp->getNameString());
145         if (builder)
146             builder->buildAttribute(effect, pass, attrProp, options);
147         else
148             SG_LOG(SG_INPUT, SG_ALERT,
149                    "skipping unknown pass attribute " << attrProp->getName());
150     }
151 }
152
153 osg::Vec4f getColor(const SGPropertyNode* prop)
154 {
155     if (prop->nChildren() == 0) {
156         if (prop->getType() == props::VEC4D) {
157             return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
158         } else if (prop->getType() == props::VEC3D) {
159             return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
160         } else {
161             SG_LOG(SG_INPUT, SG_ALERT,
162                    "invalid color property " << prop->getName() << " "
163                    << prop->getStringValue());
164             return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
165         }
166     } else {
167         osg::Vec4f result;
168         static const char* colors[] = {"r", "g", "b"};
169         for (int i = 0; i < 3; ++i) {
170             const SGPropertyNode* componentProp = prop->getChild(colors[i]);
171             result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
172         }
173         const SGPropertyNode* alphaProp = prop->getChild("a");
174         result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
175         return result;
176     }
177 }
178
179 struct LightingBuilder : public PassAttributeBuilder
180 {
181     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
182                         const osgDB::ReaderWriter::Options* options);
183 };
184
185 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
186                                      const SGPropertyNode* prop,
187                                      const osgDB::ReaderWriter::Options* options)
188 {
189     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
190     if (!realProp)
191         return;
192     pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
193                                 : StateAttribute::OFF));
194 }
195
196 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
197
198 struct ShadeModelBuilder : public PassAttributeBuilder
199 {
200     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
201                         const osgDB::ReaderWriter::Options* options)
202     {
203         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
204         if (!realProp)
205             return;
206         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
207         string propVal = realProp->getStringValue();
208         if (propVal == "flat")
209             pass->setAttribute(attrFact->getFlatShadeModel());
210         else if (propVal == "smooth")
211             pass->setAttribute(attrFact->getSmoothShadeModel());
212         else
213             SG_LOG(SG_INPUT, SG_ALERT,
214                    "invalid shade model property " << propVal);
215     }
216 };
217
218 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
219
220 struct CullFaceBuilder : PassAttributeBuilder
221 {
222     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
223                         const osgDB::ReaderWriter::Options* options)
224     {
225         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
226         if (!realProp) {
227             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
228             return;
229         }
230         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
231         string propVal = realProp->getStringValue();
232         if (propVal == "front")
233             pass->setAttributeAndModes(attrFact->getCullFaceFront());
234         else if (propVal == "back")
235             pass->setAttributeAndModes(attrFact->getCullFaceBack());
236         else if (propVal == "front-back")
237             pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
238         else if (propVal == "off")
239             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
240         else
241             SG_LOG(SG_INPUT, SG_ALERT,
242                    "invalid cull face property " << propVal);            
243     }    
244 };
245
246 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
247
248 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
249 {
250     { "default", StateSet::DEFAULT_BIN },
251     { "opaque", StateSet::OPAQUE_BIN },
252     { "transparent", StateSet::TRANSPARENT_BIN }
253 };
254
255 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
256
257 struct HintBuilder : public PassAttributeBuilder
258 {
259     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
260                         const osgDB::ReaderWriter::Options* options)
261     {
262         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
263         if (!realProp)
264             return;
265         StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
266         findAttr(renderingHints, realProp, renderingHint);
267         pass->setRenderingHint(renderingHint);
268     }    
269 };
270
271 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
272
273 struct RenderBinBuilder : public PassAttributeBuilder
274 {
275     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
276                         const osgDB::ReaderWriter::Options* options)
277     {
278         if (!isAttributeActive(effect, prop))
279             return;
280         const SGPropertyNode* binProp = prop->getChild("bin-number");
281         binProp = getEffectPropertyNode(effect, binProp);
282         const SGPropertyNode* nameProp = prop->getChild("bin-name");
283         nameProp = getEffectPropertyNode(effect, nameProp);
284         if (binProp && nameProp) {
285             pass->setRenderBinDetails(binProp->getIntValue(),
286                                       nameProp->getStringValue());
287         } else {
288             if (!binProp)
289                 SG_LOG(SG_INPUT, SG_ALERT,
290                        "No render bin number specified in render bin section");
291             if (!nameProp)
292                 SG_LOG(SG_INPUT, SG_ALERT,
293                        "No render bin name specified in render bin section");
294         }
295     }
296 };
297
298 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
299
300 struct MaterialBuilder : public PassAttributeBuilder
301 {
302     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
303                         const osgDB::ReaderWriter::Options* options);
304 };
305
306 EffectNameValue<Material::ColorMode> colorModeInit[] =
307 {
308     { "ambient", Material::AMBIENT },
309     { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
310     { "diffuse", Material::DIFFUSE },
311     { "emissive", Material::EMISSION },
312     { "specular", Material::SPECULAR },
313     { "off", Material::OFF }
314 };
315 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
316
317 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
318                                      const SGPropertyNode* prop,
319                                      const osgDB::ReaderWriter::Options* options)
320 {
321     if (!isAttributeActive(effect, prop))
322         return;
323     Material* mat = new Material;
324     const SGPropertyNode* color = 0;
325     if ((color = getEffectPropertyChild(effect, prop, "ambient")))
326         mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
327     if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
328         mat->setAmbient(Material::FRONT, getColor(color));
329     if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
330         mat->setAmbient(Material::BACK, getColor(color));
331     if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
332         mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
333     if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
334         mat->setDiffuse(Material::FRONT, getColor(color));
335     if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
336         mat->setDiffuse(Material::BACK, getColor(color));
337     if ((color = getEffectPropertyChild(effect, prop, "specular")))
338         mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
339     if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
340         mat->setSpecular(Material::FRONT, getColor(color));
341     if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
342         mat->setSpecular(Material::BACK, getColor(color));
343     if ((color = getEffectPropertyChild(effect, prop, "emissive")))
344         mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
345     if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
346         mat->setEmission(Material::FRONT, getColor(color));        
347     if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
348         mat->setEmission(Material::BACK, getColor(color));        
349     const SGPropertyNode* shininess = 0;
350     mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
351     if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
352         mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
353     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
354         mat->setShininess(Material::FRONT, shininess->getFloatValue());
355     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
356         mat->setShininess(Material::BACK, shininess->getFloatValue());
357     Material::ColorMode colorMode = Material::OFF;
358     findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
359              colorMode);
360     mat->setColorMode(colorMode);
361     pass->setAttribute(mat);
362 }
363
364 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
365
366 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
367 {
368     {"dst-alpha", BlendFunc::DST_ALPHA},
369     {"dst-color", BlendFunc::DST_COLOR},
370     {"one", BlendFunc::ONE},
371     {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
372     {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
373     {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
374     {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
375     {"src-alpha", BlendFunc::SRC_ALPHA},
376     {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
377     {"src-color", BlendFunc::SRC_COLOR},
378     {"constant-color", BlendFunc::CONSTANT_COLOR},
379     {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
380     {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
381     {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
382     {"zero", BlendFunc::ZERO}
383 };
384 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
385
386 struct BlendBuilder : public PassAttributeBuilder
387 {
388     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
389                         const osgDB::ReaderWriter::Options* options)
390     {
391         if (!isAttributeActive(effect, prop))
392             return;
393         // XXX Compatibility with early <blend> syntax; should go away
394         // before a release
395         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
396         if (!realProp)
397             return;
398         if (realProp->nChildren() == 0) {
399             pass->setMode(GL_BLEND, (realProp->getBoolValue()
400                                      ? StateAttribute::ON
401                                      : StateAttribute::OFF));
402             return;
403         }
404
405         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
406                                                              "mode");
407         // XXX When dynamic parameters are supported, this code should
408         // create the blend function even if the mode is off.
409         if (pmode && !pmode->getValue<bool>()) {
410             pass->setMode(GL_BLEND, StateAttribute::OFF);
411             return;
412         }
413         const SGPropertyNode* psource
414             = getEffectPropertyChild(effect, prop, "source");
415         const SGPropertyNode* pdestination
416             = getEffectPropertyChild(effect, prop, "destination");
417         const SGPropertyNode* psourceRGB
418             = getEffectPropertyChild(effect, prop, "source-rgb");
419         const SGPropertyNode* psourceAlpha
420             = getEffectPropertyChild(effect, prop, "source-alpha");
421         const SGPropertyNode* pdestRGB
422             = getEffectPropertyChild(effect, prop, "destination-rgb");
423         const SGPropertyNode* pdestAlpha
424             = getEffectPropertyChild(effect, prop, "destination-alpha");
425         BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
426         BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
427         if (psource)
428             findAttr(blendFuncModes, psource, sourceMode);
429         if (pdestination)
430             findAttr(blendFuncModes, pdestination, destMode);
431         if (psource && pdestination
432             && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
433             && sourceMode == BlendFunc::SRC_ALPHA
434             && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
435             pass->setAttributeAndModes(StateAttributeFactory::instance()
436                                        ->getStandardBlendFunc());
437             return;
438         }
439         BlendFunc* blendFunc = new BlendFunc;
440         if (psource)
441             blendFunc->setSource(sourceMode);
442         if (pdestination)
443             blendFunc->setDestination(destMode);
444         if (psourceRGB) {
445             BlendFunc::BlendFuncMode sourceRGBMode;
446             findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
447             blendFunc->setSourceRGB(sourceRGBMode);
448         }
449         if (pdestRGB) {
450             BlendFunc::BlendFuncMode destRGBMode;
451             findAttr(blendFuncModes, pdestRGB, destRGBMode);
452             blendFunc->setDestinationRGB(destRGBMode);
453         }
454         if (psourceAlpha) {
455             BlendFunc::BlendFuncMode sourceAlphaMode;
456             findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
457             blendFunc->setSourceAlpha(sourceAlphaMode);
458         }
459         if (pdestAlpha) {
460             BlendFunc::BlendFuncMode destAlphaMode;
461             findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
462             blendFunc->setDestinationAlpha(destAlphaMode);
463         }
464         pass->setAttributeAndModes(blendFunc);
465     }
466 };
467
468 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
469
470 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
471 {
472     {"never", AlphaFunc::NEVER},
473     {"less", AlphaFunc::LESS},
474     {"equal", AlphaFunc::EQUAL},
475     {"lequal", AlphaFunc::LEQUAL},
476     {"greater", AlphaFunc::GREATER},
477     {"notequal", AlphaFunc::NOTEQUAL},
478     {"gequal", AlphaFunc::GEQUAL},
479     {"always", AlphaFunc::ALWAYS}
480 };
481 EffectPropertyMap<AlphaFunc::ComparisonFunction>
482 alphaComparison(alphaComparisonInit);
483
484 struct AlphaTestBuilder : public PassAttributeBuilder
485 {
486     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
487                         const osgDB::ReaderWriter::Options* options)
488     {
489         if (!isAttributeActive(effect, prop))
490             return;
491         // XXX Compatibility with early <alpha-test> syntax; should go away
492         // before a release
493         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
494         if (!realProp)
495             return;
496         if (realProp->nChildren() == 0) {
497             pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
498                                      ? StateAttribute::ON
499                                      : StateAttribute::OFF));
500             return;
501         }
502
503         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
504                                                              "mode");
505         // XXX When dynamic parameters are supported, this code should
506         // create the blend function even if the mode is off.
507         if (pmode && !pmode->getValue<bool>()) {
508             pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
509             return;
510         }
511         const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
512                                                              "comparison");
513         const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
514                                                              "reference");
515         AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
516         float refValue = 1.0f;
517         if (pComp)
518             findAttr(alphaComparison, pComp, func);
519         if (pRef)
520             refValue = pRef->getValue<float>();
521         if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
522             pass->setAttributeAndModes(StateAttributeFactory::instance()
523                                        ->getStandardAlphaFunc());
524         } else {
525             AlphaFunc* alphaFunc = new AlphaFunc;
526             alphaFunc->setFunction(func);
527             alphaFunc->setReferenceValue(refValue);
528             pass->setAttributeAndModes(alphaFunc);
529         }
530     }
531 };
532
533 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
534
535 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
536
537 typedef map<string, ref_ptr<Program> > ProgramMap;
538 ProgramMap programMap;
539
540 typedef map<string, ref_ptr<Shader> > ShaderMap;
541 ShaderMap shaderMap;
542
543 void reload_shaders()
544 {
545     for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
546     {
547         Shader *shader = sitr->second.get();
548         string fileName = osgDB::findDataFile(sitr->first);
549         if (!fileName.empty()) {
550             shader->loadShaderSourceFromFile(fileName);
551         }
552     }
553 }
554
555 struct ShaderProgramBuilder : PassAttributeBuilder
556 {
557     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
558                         const osgDB::ReaderWriter::Options* options);
559 };
560
561 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
562                                           const SGPropertyNode* prop,
563                                           const osgDB::ReaderWriter::Options*
564                                           options)
565 {
566     if (!isAttributeActive(effect, prop))
567         return;
568     PropertyList pVertShaders = prop->getChildren("vertex-shader");
569     PropertyList pFragShaders = prop->getChildren("fragment-shader");
570     string programKey;
571     for (PropertyList::iterator itr = pVertShaders.begin(),
572              e = pVertShaders.end();
573          itr != e;
574          ++itr)
575     {
576         programKey += (*itr)->getStringValue();
577         programKey += ";";
578     }
579     for (PropertyList::iterator itr = pFragShaders.begin(),
580              e = pFragShaders.end();
581          itr != e;
582          ++itr)
583     {
584         programKey += (*itr)->getStringValue();
585         programKey += ";";
586     }
587     Program* program = 0;
588     ProgramMap::iterator pitr = programMap.find(programKey);
589     if (pitr != programMap.end()) {
590         program = pitr->second.get();
591     } else {
592         program = new Program;
593         program->setName(programKey);
594         // Add vertex shaders, then fragment shaders
595         PropertyList& pvec = pVertShaders;
596         Shader::Type stype = Shader::VERTEX;
597         for (int i = 0; i < 2; ++i) {
598             for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
599                  nameItr != e;
600                  ++nameItr) {
601                 string shaderName = (*nameItr)->getStringValue();
602                 ShaderMap::iterator sitr = shaderMap.find(shaderName);
603                 if (sitr != shaderMap.end()) {
604                     program->addShader(sitr->second.get());
605                 } else {
606                     string fileName = osgDB::findDataFile(shaderName, options);
607                     if (!fileName.empty()) {
608                         ref_ptr<Shader> shader = new Shader(stype);
609                         if (shader->loadShaderSourceFromFile(fileName)) {
610                             program->addShader(shader.get());
611                             shaderMap.insert(make_pair(shaderName, shader));
612                         }
613                     }
614                 }
615             }
616             pvec = pFragShaders;
617             stype = Shader::FRAGMENT;
618         }
619         programMap.insert(make_pair(programKey, program));
620     }
621     pass->setAttributeAndModes(program);
622 }
623
624 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
625
626 EffectNameValue<Uniform::Type> uniformTypesInit[] =
627 {
628     {"float", Uniform::FLOAT},
629     {"float-vec3", Uniform::FLOAT_VEC3},
630     {"float-vec4", Uniform::FLOAT_VEC4},
631     {"sampler-1d", Uniform::SAMPLER_1D},
632     {"sampler-2d", Uniform::SAMPLER_2D},
633     {"sampler-3d", Uniform::SAMPLER_3D}
634 };
635 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
636
637 struct UniformBuilder :public PassAttributeBuilder
638 {
639     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
640                         const osgDB::ReaderWriter::Options* options)
641     {
642         if (!isAttributeActive(effect, prop))
643             return;
644         const SGPropertyNode* nameProp = prop->getChild("name");
645         const SGPropertyNode* typeProp = prop->getChild("type");
646         const SGPropertyNode* valProp
647             = getEffectPropertyChild(effect, prop, "value");
648         string name;
649         Uniform::Type uniformType = Uniform::FLOAT;
650         if (nameProp) {
651             name = nameProp->getStringValue();
652         } else {
653             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
654             return;
655         }
656         if (!valProp) {
657             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
658                    << name);
659             return;
660         }
661         if (!typeProp) {
662             props::Type propType = valProp->getType();
663             switch (propType) {
664             case props::FLOAT:
665             case props::DOUBLE:
666                 break;          // default float type;
667             case props::VEC3D:
668                 uniformType = Uniform::FLOAT_VEC3;
669                 break;
670             case props::VEC4D:
671                 uniformType = Uniform::FLOAT_VEC4;
672                 break;
673             default:
674                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
675                        << name);
676                 return;
677             }
678         } else {
679             findAttr(uniformTypes, typeProp, uniformType);
680         }
681         ref_ptr<Uniform> uniform = new Uniform;
682         uniform->setName(name);
683         uniform->setType(uniformType);
684         switch (uniformType) {
685         case Uniform::FLOAT:
686             uniform->set(valProp->getValue<float>());
687             break;
688         case Uniform::FLOAT_VEC3:
689             uniform->set(toOsg(valProp->getValue<SGVec3d>()));
690             break;
691         case Uniform::FLOAT_VEC4:
692             uniform->set(toOsg(valProp->getValue<SGVec4d>()));
693             break;
694         case Uniform::SAMPLER_1D:
695         case Uniform::SAMPLER_2D:
696         case Uniform::SAMPLER_3D:
697             uniform->set(valProp->getValue<int>());
698             break;
699         default: // avoid compiler warning
700             break;
701         }
702         pass->addUniform(uniform.get());
703     }
704 };
705
706 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
707
708 // Not sure what to do with "name". At one point I wanted to use it to
709 // order the passes, but I do support render bin and stuff too...
710
711 struct NameBuilder : public PassAttributeBuilder
712 {
713     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
714                         const osgDB::ReaderWriter::Options* options)
715     {
716         // name can't use <use>
717         string name = prop->getStringValue();
718         if (!name.empty())
719             pass->setName(name);
720     }
721 };
722
723 InstallAttributeBuilder<NameBuilder> installName("name");
724
725 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
726 {
727     {"fill", PolygonMode::FILL},
728     {"line", PolygonMode::LINE},
729     {"point", PolygonMode::POINT}
730 };
731 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
732
733 struct PolygonModeBuilder : public PassAttributeBuilder
734 {
735     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
736                         const osgDB::ReaderWriter::Options* options)
737     {
738         if (!isAttributeActive(effect, prop))
739             return;
740         const SGPropertyNode* frontProp
741             = getEffectPropertyChild(effect, prop, "front");
742         const SGPropertyNode* backProp
743             = getEffectPropertyChild(effect, prop, "back");
744         ref_ptr<PolygonMode> pmode = new PolygonMode;
745         PolygonMode::Mode frontMode = PolygonMode::FILL;
746         PolygonMode::Mode backMode = PolygonMode::FILL;
747         if (frontProp) {
748             findAttr(polygonModeModes, frontProp, frontMode);
749             pmode->setMode(PolygonMode::FRONT, frontMode);
750         }
751         if (backProp) {
752             findAttr(polygonModeModes, backProp, backMode);
753             pmode->setMode(PolygonMode::BACK, backMode);
754         }
755         pass->setAttribute(pmode.get());
756     }
757 };
758
759 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
760 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
761                     const osgDB::ReaderWriter::Options* options)
762 {
763     Technique* tniq = new Technique;
764     effect->techniques.push_back(tniq);
765     const SGPropertyNode* predProp = prop->getChild("predicate");
766     if (!predProp) {
767         tniq->setAlwaysValid(true);
768     } else {
769         try {
770             TechniquePredParser parser;
771             parser.setTechnique(tniq);
772             expression::BindingLayout& layout = parser.getBindingLayout();
773             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
774             SGExpressionb* validExp
775                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
776                                                            ->getChild(0)));
777             if (validExp)
778                 tniq->setValidExpression(validExp, layout);
779             else
780                 throw expression::ParseError("technique predicate is not a boolean expression");
781         }
782         catch (expression::ParseError& except)
783         {
784             SG_LOG(SG_INPUT, SG_ALERT,
785                    "parsing technique predicate " << except.getMessage());
786             tniq->setAlwaysValid(false);
787         }
788     }
789     PropertyList passProps = prop->getChildren("pass");
790     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
791          itr != e;
792          ++itr) {
793         buildPass(effect, tniq, itr->ptr(), options);
794     }
795 }
796
797 // Specifically for .ac files...
798 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
799 {
800     SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
801     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
802     Vec4f ambVal, difVal, specVal, emisVal;
803     float shininess = 0.0f;
804     const Material* mat = getStateAttribute<Material>(ss);
805     if (mat) {
806         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
807         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
808         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
809         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
810         shininess = mat->getShininess(Material::FRONT_AND_BACK);
811         makeChild(matNode, "active")->setValue(true);
812         makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
813         makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
814         makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
815         makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
816         makeChild(matNode, "shininess")->setValue(shininess);
817         matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
818     } else {
819         makeChild(matNode, "active")->setValue(false);
820     }
821     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
822     string shadeModelString("smooth");
823     if (sm) {
824         ShadeModel::Mode smMode = sm->getMode();
825         if (smMode == ShadeModel::FLAT)
826             shadeModelString = "flat";
827     }
828     makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
829     string cullFaceString("off");
830     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
831     if (cullFace) {
832         switch (cullFace->getMode()) {
833         case CullFace::FRONT:
834             cullFaceString = "front";
835             break;
836         case CullFace::BACK:
837             cullFaceString = "back";
838             break;
839         case CullFace::FRONT_AND_BACK:
840             cullFaceString = "front-back";
841             break;
842         default:
843             break;
844         }
845     }
846     makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
847     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
848     SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
849     if (blendFunc) {
850         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
851         string destMode = findName(blendFuncModes, blendFunc->getDestination());
852         makeChild(blendNode, "active")->setValue(true);
853         makeChild(blendNode, "source")->setStringValue(sourceMode);
854         makeChild(blendNode, "destination")->setStringValue(destMode);
855         makeChild(blendNode, "mode")->setValue(true);
856     } else {
857         makeChild(blendNode, "active")->setValue(false);
858     }
859     makeTextureParameters(paramRoot, ss);
860     return true;
861 }
862
863 // Walk the techniques property tree, building techniques and
864 // passes.
865 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
866 {
867     PropertyList tniqList = root->getChildren("technique");
868     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
869          itr != e;
870          ++itr)
871         buildTechnique(this, *itr, options);
872     return true;
873 }
874
875 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
876 {
877     const Effect& effect = static_cast<const Effect&>(obj);
878
879     fw.indent() << "techniques " << effect.techniques.size() << "\n";
880     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
881         fw.writeObject(*technique);
882     }
883     return true;
884 }
885
886 namespace
887 {
888 osgDB::RegisterDotOsgWrapperProxy effectProxy
889 (
890     new Effect,
891     "simgear::Effect",
892     "Object simgear::Effect",
893     0,
894     &Effect_writeLocalData
895     );
896 }
897
898 // Property expressions for technique predicates
899 class PropertyExpression : public SGExpression<bool>
900 {
901 public:
902     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
903     
904     void eval(bool& value, const expression::Binding*) const
905     {
906         value = _pnode->getValue<bool>();
907     }
908 protected:
909     SGPropertyNode_ptr _pnode;
910 };
911
912 class EffectPropertyListener : public SGPropertyChangeListener
913 {
914 public:
915     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
916     
917     void valueChanged(SGPropertyNode* node)
918     {
919         _tniq->refreshValidity();
920     }
921 protected:
922     osg::ref_ptr<Technique> _tniq;
923 };
924
925 Expression* propertyExpressionParser(const SGPropertyNode* exp,
926                                      expression::Parser* parser)
927 {
928     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
929                                                           true);
930     PropertyExpression* pexp = new PropertyExpression(pnode);
931     TechniquePredParser* predParser
932         = dynamic_cast<TechniquePredParser*>(parser);
933     if (predParser)
934         pnode->addChangeListener(new EffectPropertyListener(predParser
935                                                             ->getTechnique()));
936     return pexp;
937 }
938
939 expression::ExpParserRegistrar propertyRegistrar("property",
940                                                  propertyExpressionParser);
941
942 }