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