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