]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/Effect.cxx
2e68223431718685d65d750251ae143ca70ba511
[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/bind.hpp>
34 #include <boost/foreach.hpp>
35 #include <boost/lexical_cast.hpp>
36 #include <boost/tuple/tuple.hpp>
37 #include <boost/tuple/tuple_comparison.hpp>
38
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
41 #include <osg/CullFace>
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 {
83 }
84
85 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
86     : root(rhs.root), parametersProp(rhs.parametersProp)
87 {
88     using namespace boost;
89     transform(rhs.techniques.begin(), rhs.techniques.end(),
90               back_inserter(techniques),
91               bind(simgear::clone_ref<Technique>, _1, copyop));
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 class PassAttributeBuilder : public Referenced
137 {
138 public:
139     virtual void buildAttribute(Effect* effect, Pass* pass,
140                                 const SGPropertyNode* prop,
141                                 const osgDB::ReaderWriter::Options* options)
142     = 0;
143 };
144
145 typedef map<const string, ref_ptr<PassAttributeBuilder> > PassAttrMap;
146 PassAttrMap passAttrMap;
147
148 template<typename T>
149 struct InstallAttributeBuilder
150 {
151     InstallAttributeBuilder(const string& name)
152     {
153         passAttrMap.insert(make_pair(name, new T));
154     }
155 };
156
157 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
158                const osgDB::ReaderWriter::Options* options)
159 {
160     Pass* pass = new Pass;
161     tniq->passes.push_back(pass);
162     for (int i = 0; i < prop->nChildren(); ++i) {
163         const SGPropertyNode* attrProp = prop->getChild(i);
164         PassAttrMap::iterator itr = passAttrMap.find(attrProp->getName());
165         if (itr != passAttrMap.end())
166             itr->second->buildAttribute(effect, pass, attrProp, options);
167         else
168             SG_LOG(SG_INPUT, SG_ALERT,
169                    "skipping unknown pass attribute " << attrProp->getName());
170     }
171 }
172
173 osg::Vec4f getColor(const SGPropertyNode* prop)
174 {
175     if (prop->nChildren() == 0) {
176         if (prop->getType() == props::VEC4D) {
177             return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
178         } else if (prop->getType() == props::VEC3D) {
179             return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
180         } else {
181             SG_LOG(SG_INPUT, SG_ALERT,
182                    "invalid color property " << prop->getName() << " "
183                    << prop->getStringValue());
184             return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
185         }
186     } else {
187         osg::Vec4f result;
188         static const char* colors[] = {"r", "g", "b"};
189         for (int i = 0; i < 3; ++i) {
190             const SGPropertyNode* componentProp = prop->getChild(colors[i]);
191             result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
192         }
193         const SGPropertyNode* alphaProp = prop->getChild("a");
194         result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
195         return result;
196     }
197 }
198
199 struct LightingBuilder : public PassAttributeBuilder
200 {
201     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
202                         const osgDB::ReaderWriter::Options* options);
203 };
204
205 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
206                                      const SGPropertyNode* prop,
207                                      const osgDB::ReaderWriter::Options* options)
208 {
209     const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
210     if (!realProp)
211         return;
212     pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
213                                 : StateAttribute::OFF));
214 }
215
216 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
217
218 struct ShadeModelBuilder : public PassAttributeBuilder
219 {
220     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
221                         const osgDB::ReaderWriter::Options* options)
222     {
223         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
224         if (!realProp)
225             return;
226         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
227         string propVal = realProp->getStringValue();
228         if (propVal == "flat")
229             pass->setAttribute(attrFact->getFlatShadeModel());
230         else if (propVal == "smooth")
231             pass->setAttribute(attrFact->getSmoothShadeModel());
232         else
233             SG_LOG(SG_INPUT, SG_ALERT,
234                    "invalid shade model property " << propVal);
235     }
236 };
237
238 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
239
240 struct CullFaceBuilder : PassAttributeBuilder
241 {
242     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
243                         const osgDB::ReaderWriter::Options* options)
244     {
245         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
246         if (!realProp) {
247             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
248             return;
249         }
250         StateAttributeFactory *attrFact = StateAttributeFactory::instance();
251         string propVal = realProp->getStringValue();
252         if (propVal == "front")
253             pass->setAttributeAndModes(attrFact->getCullFaceFront());
254         else if (propVal == "back")
255             pass->setAttributeAndModes(attrFact->getCullFaceBack());
256         else if (propVal == "front-back")
257             pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
258         else if (propVal == "off")
259             pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
260         else
261             SG_LOG(SG_INPUT, SG_ALERT,
262                    "invalid cull face property " << propVal);            
263     }    
264 };
265
266 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
267
268 struct HintBuilder : public PassAttributeBuilder
269 {
270     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
271                         const osgDB::ReaderWriter::Options* options)
272     {
273         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
274         if (!realProp)
275             return;
276         string propVal = realProp->getStringValue();
277         if (propVal == "opaque")
278             pass->setRenderingHint(StateSet::OPAQUE_BIN);
279         else if (propVal == "transparent")
280             pass->setRenderingHint(StateSet::TRANSPARENT_BIN);
281     }    
282 };
283
284 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
285
286 struct RenderBinBuilder : public PassAttributeBuilder
287 {
288     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
289                         const osgDB::ReaderWriter::Options* options)
290     {
291         const SGPropertyNode* binProp = prop->getChild("bin-number");
292         binProp = getEffectPropertyNode(effect, binProp);
293         const SGPropertyNode* nameProp = prop->getChild("bin-name");
294         nameProp = getEffectPropertyNode(effect, nameProp);
295         if (binProp && nameProp) {
296             pass->setRenderBinDetails(binProp->getIntValue(),
297                                       nameProp->getStringValue());
298         } else {
299             if (!binProp)
300                 SG_LOG(SG_INPUT, SG_ALERT,
301                        "No render bin number specified in render bin section");
302             if (!nameProp)
303                 SG_LOG(SG_INPUT, SG_ALERT,
304                        "No render bin name specified in render bin section");
305         }
306     }
307 };
308
309 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
310
311 struct MaterialBuilder : public PassAttributeBuilder
312 {
313     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
314                         const osgDB::ReaderWriter::Options* options);
315 };
316
317 EffectNameValue<Material::ColorMode> colorModeInit[] =
318 {
319     { "ambient", Material::AMBIENT },
320     { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
321     { "diffuse", Material::DIFFUSE },
322     { "emissive", Material::EMISSION },
323     { "specular", Material::SPECULAR },
324     { "off", Material::OFF }
325 };
326 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
327
328 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
329                                      const SGPropertyNode* prop,
330                                      const osgDB::ReaderWriter::Options* options)
331 {
332     Material* mat = new Material;
333     const SGPropertyNode* color = 0;
334     if ((color = getEffectPropertyChild(effect, prop, "ambient")))
335         mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
336     if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
337         mat->setAmbient(Material::FRONT, getColor(color));
338     if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
339         mat->setAmbient(Material::BACK, getColor(color));
340     if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
341         mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
342     if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
343         mat->setDiffuse(Material::FRONT, getColor(color));
344     if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
345         mat->setDiffuse(Material::BACK, getColor(color));
346     if ((color = getEffectPropertyChild(effect, prop, "specular")))
347         mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
348     if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
349         mat->setSpecular(Material::FRONT, getColor(color));
350     if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
351         mat->setSpecular(Material::BACK, getColor(color));
352     if ((color = getEffectPropertyChild(effect, prop, "emissive")))
353         mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
354     if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
355         mat->setEmission(Material::FRONT, getColor(color));        
356     if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
357         mat->setEmission(Material::BACK, getColor(color));        
358     const SGPropertyNode* shininess = 0;
359     mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
360     if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
361         mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
362     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
363         mat->setShininess(Material::FRONT, shininess->getFloatValue());
364     if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
365         mat->setShininess(Material::BACK, shininess->getFloatValue());
366     Material::ColorMode colorMode = Material::OFF;
367     findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
368              colorMode);
369     mat->setColorMode(colorMode);
370     pass->setAttribute(mat);
371 }
372
373 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
374
375 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
376 {
377     {"dst-alpha", BlendFunc::DST_ALPHA},
378     {"dst-color", BlendFunc::DST_COLOR},
379     {"one", BlendFunc::ONE},
380     {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
381     {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
382     {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
383     {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
384     {"src-alpha", BlendFunc::SRC_ALPHA},
385     {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
386     {"src-color", BlendFunc::SRC_COLOR},
387     {"constant-color", BlendFunc::CONSTANT_COLOR},
388     {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
389     {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
390     {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
391     {"zero", BlendFunc::ZERO}
392 };
393 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
394
395 struct BlendBuilder : public PassAttributeBuilder
396 {
397     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
398                         const osgDB::ReaderWriter::Options* options)
399     {
400         // XXX Compatibility with early <blend> syntax; should go away
401         // before a release
402         const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
403         if (!realProp)
404             return;
405         if (realProp->nChildren() == 0) {
406             pass->setMode(GL_BLEND, (realProp->getBoolValue()
407                                      ? StateAttribute::ON
408                                      : StateAttribute::OFF));
409             return;
410         }
411
412         const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
413                                                              "mode");
414         // XXX When dynamic parameters are supported, this code should
415         // create the blend function even if the mode is off.
416         if (pmode && !pmode->getValue<bool>()) {
417             pass->setMode(GL_BLEND, StateAttribute::OFF);
418             return;
419         }
420         const SGPropertyNode* psource = getEffectPropertyChild(effect, prop,
421                                                               "source");
422         const SGPropertyNode* pdestination
423             = getEffectPropertyChild(effect, prop, "destination");
424         const SGPropertyNode* psourceRGB
425             = getEffectPropertyChild(effect, prop, "source-rgb");
426         const SGPropertyNode* psourceAlpha
427             = getEffectPropertyChild(effect, prop, "source-alpha");
428         const SGPropertyNode* pdestRGB
429             = getEffectPropertyChild(effect, prop, "destination-rgb");
430         const SGPropertyNode* pdestAlpha
431             = getEffectPropertyChild(effect, prop, "destination-alpha");
432         BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
433         BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
434         if (psource)
435             findAttr(blendFuncModes, psource, sourceMode);
436         if (pdestination)
437             findAttr(blendFuncModes, pdestination, destMode);
438         if (psource && pdestination
439             && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
440             && sourceMode == BlendFunc::SRC_ALPHA
441             && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
442             pass->setAttributeAndModes(StateAttributeFactory::instance()
443                                        ->getStandardBlendFunc());
444             return;
445         }
446         BlendFunc* blendFunc = new BlendFunc;
447         if (psource)
448             blendFunc->setSource(sourceMode);
449         if (pdestination)
450             blendFunc->setDestination(destMode);
451         if (psourceRGB) {
452             BlendFunc::BlendFuncMode sourceRGBMode;
453             findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
454             blendFunc->setSourceRGB(sourceRGBMode);
455         }
456         if (pdestRGB) {
457             BlendFunc::BlendFuncMode destRGBMode;
458             findAttr(blendFuncModes, pdestRGB, destRGBMode);
459             blendFunc->setDestinationRGB(destRGBMode);
460         }
461         if (psourceAlpha) {
462             BlendFunc::BlendFuncMode sourceAlphaMode;
463             findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
464             blendFunc->setSourceAlpha(sourceAlphaMode);
465         }
466         if (pdestAlpha) {
467             BlendFunc::BlendFuncMode destAlphaMode;
468             findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
469             blendFunc->setDestinationAlpha(destAlphaMode);
470         }
471         pass->setAttributeAndModes(blendFunc);
472     }
473 };
474
475 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
476
477 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
478 {
479     {"never", AlphaFunc::NEVER},
480     {"less", AlphaFunc::LESS},
481     {"equal", AlphaFunc::EQUAL},
482     {"lequal", AlphaFunc::LEQUAL},
483     {"greater", AlphaFunc::GREATER},
484     {"notequal", AlphaFunc::NOTEQUAL},
485     {"gequal", AlphaFunc::GEQUAL},
486     {"always", AlphaFunc::ALWAYS}
487 };
488 EffectPropertyMap<AlphaFunc::ComparisonFunction>
489 alphaComparison(alphaComparisonInit);
490
491 struct AlphaTestBuilder : public PassAttributeBuilder
492 {
493     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
494                         const osgDB::ReaderWriter::Options* options)
495     {
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 EffectNameValue<TexEnv::Mode> texEnvModesInit[] =
541 {
542     {"add", TexEnv::ADD},
543     {"blend", TexEnv::BLEND},
544     {"decal", TexEnv::DECAL},
545     {"modulate", TexEnv::MODULATE},
546     {"replace", TexEnv::REPLACE}
547 };
548 EffectPropertyMap<TexEnv::Mode> texEnvModes(texEnvModesInit);
549
550 TexEnv* buildTexEnv(Effect* effect, const SGPropertyNode* prop)
551 {
552     const SGPropertyNode* modeProp = getEffectPropertyChild(effect, prop,
553                                                             "mode");
554     const SGPropertyNode* colorProp = getEffectPropertyChild(effect, prop,
555                                                              "color");
556     if (!modeProp)
557         return 0;
558     TexEnv::Mode mode = TexEnv::MODULATE;
559     findAttr(texEnvModes, modeProp, mode);
560     if (mode == TexEnv::MODULATE) {
561         return StateAttributeFactory::instance()->getStandardTexEnv();
562     }
563     TexEnv* env = new TexEnv(mode);
564     if (colorProp)
565         env->setColor(toOsg(colorProp->getValue<SGVec4d>()));
566     return env;
567  }
568
569
570 struct TextureUnitBuilder : PassAttributeBuilder
571 {
572     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
573                         const osgDB::ReaderWriter::Options* options);
574 };
575
576 void TextureUnitBuilder::buildAttribute(Effect* effect, Pass* pass,
577                                         const SGPropertyNode* prop,
578                                         const osgDB::ReaderWriter::Options* options)
579 {
580
581     // Decode the texture unit
582     int unit = 0;
583     const SGPropertyNode* pUnit = prop->getChild("unit");
584     if (pUnit) {
585         unit = pUnit->getValue<int>();
586     } else {
587         const SGPropertyNode* pName = prop->getChild("name");
588         if (pName)
589             try {
590                 unit = boost::lexical_cast<int>(pName->getStringValue());
591             } catch (boost::bad_lexical_cast& lex) {
592                 SG_LOG(SG_INPUT, SG_ALERT, "can't decode name as texture unit "
593                        << lex.what());
594             }
595     }
596     const SGPropertyNode* pType = prop->getChild("type");
597     string type;
598     if (!pType)
599         type = "2d";
600     else
601         type = pType->getStringValue();
602     Texture* texture = 0;
603     try {
604         texture = TextureBuilder::buildFromType(effect, type, prop,
605                                                 options);
606     }
607     catch (BuilderException& e) {
608         SG_LOG(SG_INPUT, SG_ALERT, "No image file for texture, using white ");
609         texture = StateAttributeFactory::instance()->getWhiteTexture();
610     }
611     pass->setTextureAttributeAndModes(unit, texture);
612     const SGPropertyNode* envProp = prop->getChild("environment");
613     if (envProp) {
614         TexEnv* env = buildTexEnv(effect, envProp);
615         if (env)
616             pass->setTextureAttributeAndModes(unit, env);
617     }
618 }
619
620
621
622 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
623
624 typedef map<string, ref_ptr<Program> > ProgramMap;
625 ProgramMap programMap;
626
627 typedef map<string, ref_ptr<Shader> > ShaderMap;
628 ShaderMap shaderMap;
629
630 void reload_shaders()
631 {
632     for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
633     {
634         Shader *shader = sitr->second.get();
635         string fileName = osgDB::findDataFile(sitr->first);
636         if (!fileName.empty()) {
637             shader->loadShaderSourceFromFile(fileName);
638         }
639     }
640 }
641
642 struct ShaderProgramBuilder : PassAttributeBuilder
643 {
644     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
645                         const osgDB::ReaderWriter::Options* options);
646 };
647
648 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
649                                           const SGPropertyNode* prop,
650                                           const osgDB::ReaderWriter::Options*
651                                           options)
652 {
653     PropertyList pVertShaders = prop->getChildren("vertex-shader");
654     PropertyList pFragShaders = prop->getChildren("fragment-shader");
655     string programKey;
656     for (PropertyList::iterator itr = pVertShaders.begin(),
657              e = pVertShaders.end();
658          itr != e;
659          ++itr)
660     {
661         programKey += (*itr)->getStringValue();
662         programKey += ";";
663     }
664     for (PropertyList::iterator itr = pFragShaders.begin(),
665              e = pFragShaders.end();
666          itr != e;
667          ++itr)
668     {
669         programKey += (*itr)->getStringValue();
670         programKey += ";";
671     }
672     Program* program = 0;
673     ProgramMap::iterator pitr = programMap.find(programKey);
674     if (pitr != programMap.end()) {
675         program = pitr->second.get();
676     } else {
677         program = new Program;
678         program->setName(programKey);
679         // Add vertex shaders, then fragment shaders
680         PropertyList& pvec = pVertShaders;
681         Shader::Type stype = Shader::VERTEX;
682         for (int i = 0; i < 2; ++i) {
683             for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
684                  nameItr != e;
685                  ++nameItr) {
686                 string shaderName = (*nameItr)->getStringValue();
687                 ShaderMap::iterator sitr = shaderMap.find(shaderName);
688                 if (sitr != shaderMap.end()) {
689                     program->addShader(sitr->second.get());
690                 } else {
691                     string fileName = osgDB::findDataFile(shaderName, options);
692                     if (!fileName.empty()) {
693                         ref_ptr<Shader> shader = new Shader(stype);
694                         if (shader->loadShaderSourceFromFile(fileName)) {
695                             program->addShader(shader.get());
696                             shaderMap.insert(make_pair(shaderName, shader));
697                         }
698                     }
699                 }
700             }
701             pvec = pFragShaders;
702             stype = Shader::FRAGMENT;
703         }
704         programMap.insert(make_pair(programKey, program));
705     }
706     pass->setAttributeAndModes(program);
707 }
708
709 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
710
711 EffectNameValue<Uniform::Type> uniformTypesInit[] =
712 {
713     {"float", Uniform::FLOAT},
714     {"float-vec3", Uniform::FLOAT_VEC3},
715     {"float-vec4", Uniform::FLOAT_VEC4},
716     {"sampler-1d", Uniform::SAMPLER_1D},
717     {"sampler-2d", Uniform::SAMPLER_2D},
718     {"sampler-3d", Uniform::SAMPLER_3D}
719 };
720 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
721
722 struct UniformBuilder :public PassAttributeBuilder
723 {
724     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
725                         const osgDB::ReaderWriter::Options* options)
726     {
727         const SGPropertyNode* nameProp = prop->getChild("name");
728         const SGPropertyNode* typeProp = prop->getChild("type");
729         const SGPropertyNode* valProp
730             = getEffectPropertyChild(effect, prop, "value");
731         string name;
732         Uniform::Type uniformType = Uniform::FLOAT;
733         if (nameProp) {
734             name = nameProp->getStringValue();
735         } else {
736             SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
737             return;
738         }
739         if (!valProp) {
740             SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
741                    << name);
742             return;
743         }
744         if (!typeProp) {
745             props::Type propType = valProp->getType();
746             switch (propType) {
747             case props::FLOAT:
748             case props::DOUBLE:
749                 break;          // default float type;
750             case props::VEC3D:
751                 uniformType = Uniform::FLOAT_VEC3;
752                 break;
753             case props::VEC4D:
754                 uniformType = Uniform::FLOAT_VEC4;
755                 break;
756             default:
757                 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
758                        << name);
759                 return;
760             }
761         } else {
762             findAttr(uniformTypes, typeProp, uniformType);
763         }
764         ref_ptr<Uniform> uniform = new Uniform;
765         uniform->setName(name);
766         uniform->setType(uniformType);
767         switch (uniformType) {
768         case Uniform::FLOAT:
769             uniform->set(valProp->getValue<float>());
770             break;
771         case Uniform::FLOAT_VEC3:
772             uniform->set(toOsg(valProp->getValue<SGVec3d>()));
773             break;
774         case Uniform::FLOAT_VEC4:
775             uniform->set(toOsg(valProp->getValue<SGVec4d>()));
776             break;
777         case Uniform::SAMPLER_1D:
778         case Uniform::SAMPLER_2D:
779         case Uniform::SAMPLER_3D:
780             uniform->set(valProp->getValue<int>());
781             break;
782         default: // avoid compiler warning
783             break;
784         }
785         pass->addUniform(uniform.get());
786     }
787 };
788
789 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
790
791 // Not sure what to do with "name". At one point I wanted to use it to
792 // order the passes, but I do support render bin and stuff too...
793
794 struct NameBuilder : public PassAttributeBuilder
795 {
796     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
797                         const osgDB::ReaderWriter::Options* options)
798     {
799         // name can't use <use>
800         string name = prop->getStringValue();
801         if (!name.empty())
802             pass->setName(name);
803     }
804 };
805
806 InstallAttributeBuilder<NameBuilder> installName("name");
807
808 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
809 {
810     {"fill", PolygonMode::FILL},
811     {"line", PolygonMode::LINE},
812     {"point", PolygonMode::POINT}
813 };
814 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
815
816 struct PolygonModeBuilder : public PassAttributeBuilder
817 {
818     void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
819                         const osgDB::ReaderWriter::Options* options)
820     {
821         const SGPropertyNode* frontProp
822             = getEffectPropertyChild(effect, prop, "front");
823         const SGPropertyNode* backProp
824             = getEffectPropertyChild(effect, prop, "back");
825         ref_ptr<PolygonMode> pmode = new PolygonMode;
826         PolygonMode::Mode frontMode = PolygonMode::FILL;
827         PolygonMode::Mode backMode = PolygonMode::FILL;
828         if (frontProp) {
829             findAttr(polygonModeModes, frontProp, frontMode);
830             pmode->setMode(PolygonMode::FRONT, frontMode);
831         }
832         if (backProp) {
833             findAttr(polygonModeModes, backProp, backMode);
834             pmode->setMode(PolygonMode::BACK, backMode);
835         }
836         pass->setAttribute(pmode.get());
837     }
838 };
839
840 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
841 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
842                     const osgDB::ReaderWriter::Options* options)
843 {
844     Technique* tniq = new Technique;
845     effect->techniques.push_back(tniq);
846     const SGPropertyNode* predProp = prop->getChild("predicate");
847     if (!predProp) {
848         tniq->setAlwaysValid(true);
849     } else {
850         try {
851             TechniquePredParser parser;
852             parser.setTechnique(tniq);
853             expression::BindingLayout& layout = parser.getBindingLayout();
854             /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
855             SGExpressionb* validExp
856                 = dynamic_cast<SGExpressionb*>(parser.read(predProp
857                                                            ->getChild(0)));
858             if (validExp)
859                 tniq->setValidExpression(validExp, layout);
860             else
861                 throw expression::ParseError("technique predicate is not a boolean expression");
862         }
863         catch (expression::ParseError& except)
864         {
865             SG_LOG(SG_INPUT, SG_ALERT,
866                    "parsing technique predicate " << except.getMessage());
867             tniq->setAlwaysValid(false);
868         }
869     }
870     PropertyList passProps = prop->getChildren("pass");
871     for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
872          itr != e;
873          ++itr) {
874         buildPass(effect, tniq, itr->ptr(), options);
875     }
876 }
877
878 // Specifically for .ac files...
879 bool makeParametersFromStateSet(SGPropertyNode* paramRoot, const StateSet* ss)
880 {
881     SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
882     Vec4f ambVal, difVal, specVal, emisVal;
883     float shininess = 0.0f;
884     const Material* mat = getStateAttribute<Material>(ss);
885     if (mat) {
886         ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
887         difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
888         specVal = mat->getSpecular(Material::FRONT_AND_BACK);
889         emisVal = mat->getEmission(Material::FRONT_AND_BACK);
890         shininess = mat->getShininess(Material::FRONT_AND_BACK);
891     }
892     matNode->getChild("ambient", 0, true)->setValue(toVec4d(toSG(ambVal)));
893     matNode->getChild("diffuse", 0, true)->setValue(toVec4d(toSG(difVal)));
894     matNode->getChild("specular", 0, true)->setValue(toVec4d(toSG(specVal)));
895     matNode->getChild("emissive", 0, true)->setValue(toVec4d(toSG(emisVal)));
896     matNode->getChild("shininess", 0, true)->setValue(shininess);
897     matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
898     const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
899     string shadeModelString("smooth");
900     if (sm) {
901         ShadeModel::Mode smMode = sm->getMode();
902         if (smMode == ShadeModel::FLAT)
903             shadeModelString = "flat";
904     }
905     paramRoot->getChild("shade-model", 0, true)
906         ->setStringValue(shadeModelString);
907     string cullFaceString("off");
908     const CullFace* cullFace = getStateAttribute<CullFace>(ss);
909     if (cullFace) {
910         switch (cullFace->getMode()) {
911         case CullFace::FRONT:
912             cullFaceString = "front";
913             break;
914         case CullFace::BACK:
915             cullFaceString = "back";
916             break;
917         case CullFace::FRONT_AND_BACK:
918             cullFaceString = "front-back";
919             break;
920         default:
921             break;
922         }
923     }
924     paramRoot->getChild("cull-face", 0, true)->setStringValue(cullFaceString);
925     const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
926     if (blendFunc) {
927         string sourceMode = findName(blendFuncModes, blendFunc->getSource());
928         string destMode = findName(blendFuncModes, blendFunc->getDestination());
929         SGPropertyNode* blendNode = paramRoot->getChild("blend", 0, true);
930         blendNode->getChild("source", 0, true)->setStringValue(sourceMode);
931         blendNode->getChild("destination", 0, true)->setStringValue(destMode);
932         blendNode->getChild("mode", 0, true)->setValue(true);
933     }
934     makeTextureParameters(paramRoot, ss);
935     return true;
936 }
937
938 // Walk the techniques property tree, building techniques and
939 // passes.
940 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
941 {
942     PropertyList tniqList = root->getChildren("technique");
943     for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
944          itr != e;
945          ++itr)
946         buildTechnique(this, *itr, options);
947     return true;
948 }
949
950 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
951 {
952     const Effect& effect = static_cast<const Effect&>(obj);
953
954     fw.indent() << "techniques " << effect.techniques.size() << "\n";
955     BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
956         fw.writeObject(*technique);
957     }
958     return true;
959 }
960
961 namespace
962 {
963 osgDB::RegisterDotOsgWrapperProxy effectProxy
964 (
965     new Effect,
966     "simgear::Effect",
967     "Object simgear::Effect",
968     0,
969     &Effect_writeLocalData
970     );
971 }
972
973 // Property expressions for technique predicates
974 class PropertyExpression : public SGExpression<bool>
975 {
976 public:
977     PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
978     
979     void eval(bool& value, const expression::Binding*) const
980     {
981         value = _pnode->getValue<bool>();
982     }
983 protected:
984     SGPropertyNode_ptr _pnode;
985 };
986
987 class EffectPropertyListener : public SGPropertyChangeListener
988 {
989 public:
990     EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
991     
992     void valueChanged(SGPropertyNode* node)
993     {
994         _tniq->refreshValidity();
995     }
996 protected:
997     osg::ref_ptr<Technique> _tniq;
998 };
999
1000 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1001                                      expression::Parser* parser)
1002 {
1003     SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1004                                                           true);
1005     PropertyExpression* pexp = new PropertyExpression(pnode);
1006     TechniquePredParser* predParser
1007         = dynamic_cast<TechniquePredParser*>(parser);
1008     if (predParser)
1009         pnode->addChangeListener(new EffectPropertyListener(predParser
1010                                                             ->getTechnique()));
1011     return pexp;
1012 }
1013
1014 expression::ExpParserRegistrar propertyRegistrar("property",
1015                                                  propertyExpressionParser);
1016
1017 }