1 // Copyright (C) 2008 - 2009 Tim Moore timoore@redhat.com
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.
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.
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.
18 # include <simgear_config.h>
22 #include "EffectBuilder.hxx"
23 #include "EffectGeode.hxx"
24 #include "Technique.hxx"
26 #include "TextureBuilder.hxx"
33 #include <boost/tr1/unordered_map.hpp>
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>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
43 #include <osg/CullFace>
45 #include <osg/Drawable>
46 #include <osg/Material>
48 #include <osg/PolygonMode>
49 #include <osg/Program>
50 #include <osg/Referenced>
51 #include <osg/RenderInfo>
52 #include <osg/ShadeModel>
53 #include <osg/StateSet>
55 #include <osg/Texture1D>
56 #include <osg/Texture2D>
57 #include <osg/Texture3D>
58 #include <osg/TextureRectangle>
59 #include <osg/Uniform>
61 #include <osgUtil/CullVisitor>
62 #include <osgDB/FileUtils>
63 #include <osgDB/Input>
64 #include <osgDB/ParameterOutput>
65 #include <osgDB/ReadFile>
66 #include <osgDB/Registry>
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>
80 using namespace osgUtil;
82 using namespace effect;
85 : _cache(0), _isRealized(false)
89 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
90 : root(rhs.root), parametersProp(rhs.parametersProp), _cache(0),
91 _isRealized(rhs._isRealized)
93 typedef vector<ref_ptr<Technique> > TechniqueList;
94 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
95 end = rhs.techniques.end();
98 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
101 // Assume that the last technique is always valid.
102 StateSet* Effect::getDefaultStateSet()
104 Technique* tniq = techniques.back().get();
107 Pass* pass = tniq->passes.front().get();
111 // There should always be a valid technique in an effect.
113 Technique* Effect::chooseTechnique(RenderInfo* info)
115 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
117 if (technique->valid(info) == Technique::VALID)
118 return technique.get();
123 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
125 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
127 technique->resizeGLObjectBuffers(maxSize);
131 void Effect::releaseGLObjects(osg::State* state) const
133 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
135 technique->releaseGLObjects(state);
144 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
145 const osgDB::ReaderWriter::Options* options)
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());
154 builder->buildAttribute(effect, pass, attrProp, options);
156 SG_LOG(SG_INPUT, SG_ALERT,
157 "skipping unknown pass attribute " << attrProp->getName());
161 osg::Vec4f getColor(const SGPropertyNode* prop)
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);
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);
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;
181 const SGPropertyNode* alphaProp = prop->getChild("a");
182 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
187 struct LightingBuilder : public PassAttributeBuilder
189 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
190 const osgDB::ReaderWriter::Options* options);
193 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
194 const SGPropertyNode* prop,
195 const osgDB::ReaderWriter::Options* options)
197 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
200 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
201 : StateAttribute::OFF));
204 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
206 struct ShadeModelBuilder : public PassAttributeBuilder
208 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
209 const osgDB::ReaderWriter::Options* options)
211 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
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());
221 SG_LOG(SG_INPUT, SG_ALERT,
222 "invalid shade model property " << propVal);
226 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
228 struct CullFaceBuilder : PassAttributeBuilder
230 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
231 const osgDB::ReaderWriter::Options* options)
233 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
235 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
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);
249 SG_LOG(SG_INPUT, SG_ALERT,
250 "invalid cull face property " << propVal);
254 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
256 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
258 { "default", StateSet::DEFAULT_BIN },
259 { "opaque", StateSet::OPAQUE_BIN },
260 { "transparent", StateSet::TRANSPARENT_BIN }
263 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
265 struct HintBuilder : public PassAttributeBuilder
267 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
268 const osgDB::ReaderWriter::Options* options)
270 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
273 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
274 findAttr(renderingHints, realProp, renderingHint);
275 pass->setRenderingHint(renderingHint);
279 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
281 struct RenderBinBuilder : public PassAttributeBuilder
283 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
284 const osgDB::ReaderWriter::Options* options)
286 if (!isAttributeActive(effect, prop))
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());
297 SG_LOG(SG_INPUT, SG_ALERT,
298 "No render bin number specified in render bin section");
300 SG_LOG(SG_INPUT, SG_ALERT,
301 "No render bin name specified in render bin section");
306 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
308 struct MaterialBuilder : public PassAttributeBuilder
310 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
311 const osgDB::ReaderWriter::Options* options);
314 EffectNameValue<Material::ColorMode> colorModeInit[] =
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 }
323 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
325 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
326 const SGPropertyNode* prop,
327 const osgDB::ReaderWriter::Options* options)
329 if (!isAttributeActive(effect, prop))
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"),
368 mat->setColorMode(colorMode);
369 pass->setAttribute(mat);
372 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
374 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
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}
392 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
394 struct BlendBuilder : public PassAttributeBuilder
396 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
397 const osgDB::ReaderWriter::Options* options)
399 if (!isAttributeActive(effect, prop))
401 // XXX Compatibility with early <blend> syntax; should go away
403 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
406 if (realProp->nChildren() == 0) {
407 pass->setMode(GL_BLEND, (realProp->getBoolValue()
409 : StateAttribute::OFF));
413 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
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);
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;
436 findAttr(blendFuncModes, psource, sourceMode);
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());
447 BlendFunc* blendFunc = new BlendFunc;
449 blendFunc->setSource(sourceMode);
451 blendFunc->setDestination(destMode);
453 BlendFunc::BlendFuncMode sourceRGBMode;
454 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
455 blendFunc->setSourceRGB(sourceRGBMode);
458 BlendFunc::BlendFuncMode destRGBMode;
459 findAttr(blendFuncModes, pdestRGB, destRGBMode);
460 blendFunc->setDestinationRGB(destRGBMode);
463 BlendFunc::BlendFuncMode sourceAlphaMode;
464 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
465 blendFunc->setSourceAlpha(sourceAlphaMode);
468 BlendFunc::BlendFuncMode destAlphaMode;
469 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
470 blendFunc->setDestinationAlpha(destAlphaMode);
472 pass->setAttributeAndModes(blendFunc);
476 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
478 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
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}
489 EffectPropertyMap<AlphaFunc::ComparisonFunction>
490 alphaComparison(alphaComparisonInit);
492 struct AlphaTestBuilder : public PassAttributeBuilder
494 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
495 const osgDB::ReaderWriter::Options* options)
497 if (!isAttributeActive(effect, prop))
499 // XXX Compatibility with early <alpha-test> syntax; should go away
501 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
504 if (realProp->nChildren() == 0) {
505 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
507 : StateAttribute::OFF));
511 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
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);
519 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
521 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
523 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
524 float refValue = 1.0f;
526 findAttr(alphaComparison, pComp, func);
528 refValue = pRef->getValue<float>();
529 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
530 pass->setAttributeAndModes(StateAttributeFactory::instance()
531 ->getStandardAlphaFunc());
533 AlphaFunc* alphaFunc = new AlphaFunc;
534 alphaFunc->setFunction(func);
535 alphaFunc->setReferenceValue(refValue);
536 pass->setAttributeAndModes(alphaFunc);
541 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
543 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
545 // Shader key, used both for shaders with relative and absolute names
546 typedef pair<string, Shader::Type> ShaderKey;
550 typedef pair<string, int> AttribKey;
551 osgDB::FilePathList paths;
552 vector<ShaderKey> shaders;
553 vector<AttribKey> attributes;
556 bool operator()(const ProgramKey& lhs, const ProgramKey& rhs) const
558 return (lhs.paths.size() == rhs.paths.size()
559 && equal(lhs.paths.begin(), lhs.paths.end(),
561 && lhs.shaders.size() == rhs.shaders.size()
562 && equal (lhs.shaders.begin(), lhs.shaders.end(),
564 && lhs.attributes.size() == rhs.attributes.size()
565 && equal(lhs.attributes.begin(), lhs.attributes.end(),
566 rhs.attributes.begin()));
571 size_t hash_value(const ProgramKey& key)
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());
580 // XXX Should these be protected by a mutex? Probably
582 typedef tr1::unordered_map<ProgramKey, ref_ptr<Program>,
583 boost::hash<ProgramKey>, ProgramKey::EqualTo>
585 ProgramMap programMap;
587 typedef tr1::unordered_map<ShaderKey, ref_ptr<Shader>, boost::hash<ShaderKey> >
591 void reload_shaders()
593 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
595 Shader *shader = sitr->second.get();
596 string fileName = osgDB::findDataFile(sitr->first.first);
597 if (!fileName.empty()) {
598 shader->loadShaderSourceFromFile(fileName);
603 struct ShaderProgramBuilder : PassAttributeBuilder
605 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
606 const osgDB::ReaderWriter::Options* options);
609 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
610 const SGPropertyNode* prop,
611 const osgDB::ReaderWriter::Options*
614 using namespace boost;
615 if (!isAttributeActive(effect, prop))
617 PropertyList pVertShaders = prop->getChildren("vertex-shader");
618 PropertyList pFragShaders = prop->getChildren("fragment-shader");
619 PropertyList pAttributes = prop->getChildren("attribute");
621 for (PropertyList::iterator itr = pVertShaders.begin(),
622 e = pVertShaders.end();
625 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
627 for (PropertyList::iterator itr = pFragShaders.begin(),
628 e = pFragShaders.end();
631 prgKey.shaders.push_back(ShaderKey((*itr)->getStringValue(),
633 for (PropertyList::iterator itr = pAttributes.begin(),
634 e = pAttributes.end();
637 const SGPropertyNode* pName = getEffectPropertyChild(effect, *itr,
639 const SGPropertyNode* pIndex = getEffectPropertyChild(effect, *itr,
641 if (!pName || ! pIndex)
642 throw BuilderException("malformed attribute property");
644 .push_back(ProgramKey::AttribKey(pName->getStringValue(),
645 pIndex->getValue<int>()));
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();
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();
662 string shaderName = (*nameItr)->getStringValue();
663 string fileName = osgDB::findDataFile(shaderName, options);
664 if (fileName.empty())
665 throw BuilderException(string("couldn't find shader ") +
667 ShaderKey skey(fileName, stype);
668 ShaderMap::iterator sitr = shaderMap.find(skey);
669 if (sitr != shaderMap.end()) {
670 program->addShader(sitr->second.get());
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));
680 stype = Shader::FRAGMENT;
682 BOOST_FOREACH(const ProgramKey::AttribKey& key, prgKey.attributes) {
683 program->addBindAttribLocation(key.first, key.second);
685 programMap.insert(ProgramMap::value_type(prgKey, program));
687 pass->setAttributeAndModes(program);
690 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
692 EffectNameValue<Uniform::Type> uniformTypesInit[] =
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}
701 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
703 struct UniformBuilder :public PassAttributeBuilder
705 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
706 const osgDB::ReaderWriter::Options* options)
708 if (!isAttributeActive(effect, prop))
710 const SGPropertyNode* nameProp = prop->getChild("name");
711 const SGPropertyNode* typeProp = prop->getChild("type");
712 const SGPropertyNode* valProp
713 = getEffectPropertyChild(effect, prop, "value");
715 Uniform::Type uniformType = Uniform::FLOAT;
717 name = nameProp->getStringValue();
719 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
723 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
728 props::Type propType = valProp->getType();
732 break; // default float type;
734 uniformType = Uniform::FLOAT_VEC3;
737 uniformType = Uniform::FLOAT_VEC4;
740 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
745 findAttr(uniformTypes, typeProp, uniformType);
747 ref_ptr<Uniform> uniform = new Uniform;
748 uniform->setName(name);
749 uniform->setType(uniformType);
750 switch (uniformType) {
752 uniform->set(valProp->getValue<float>());
754 case Uniform::FLOAT_VEC3:
755 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
757 case Uniform::FLOAT_VEC4:
758 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
760 case Uniform::SAMPLER_1D:
761 case Uniform::SAMPLER_2D:
762 case Uniform::SAMPLER_3D:
763 uniform->set(valProp->getValue<int>());
765 default: // avoid compiler warning
768 pass->addUniform(uniform.get());
772 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
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...
777 struct NameBuilder : public PassAttributeBuilder
779 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
780 const osgDB::ReaderWriter::Options* options)
782 // name can't use <use>
783 string name = prop->getStringValue();
789 InstallAttributeBuilder<NameBuilder> installName("name");
791 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
793 {"fill", PolygonMode::FILL},
794 {"line", PolygonMode::LINE},
795 {"point", PolygonMode::POINT}
797 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
799 struct PolygonModeBuilder : public PassAttributeBuilder
801 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
802 const osgDB::ReaderWriter::Options* options)
804 if (!isAttributeActive(effect, prop))
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;
814 findAttr(polygonModeModes, frontProp, frontMode);
815 pmode->setMode(PolygonMode::FRONT, frontMode);
818 findAttr(polygonModeModes, backProp, backMode);
819 pmode->setMode(PolygonMode::BACK, backMode);
821 pass->setAttribute(pmode.get());
825 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
827 struct VertexProgramTwoSideBuilder : public PassAttributeBuilder
829 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
830 const osgDB::ReaderWriter::Options* options)
832 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
835 pass->setMode(GL_VERTEX_PROGRAM_TWO_SIDE,
836 (realProp->getValue<bool>()
837 ? StateAttribute::ON : StateAttribute::OFF));
841 InstallAttributeBuilder<VertexProgramTwoSideBuilder>
842 installTwoSide("vertex-program-two-side");
844 struct VertexProgramPointSizeBuilder : public PassAttributeBuilder
846 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
847 const osgDB::ReaderWriter::Options* options)
849 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
852 pass->setMode(GL_VERTEX_PROGRAM_POINT_SIZE,
853 (realProp->getValue<bool>()
854 ? StateAttribute::ON : StateAttribute::OFF));
858 InstallAttributeBuilder<VertexProgramPointSizeBuilder>
859 installPointSize("vertex-program-point-size");
861 EffectNameValue<Depth::Function> depthFunctionInit[] =
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}
872 EffectPropertyMap<Depth::Function> depthFunction(depthFunctionInit);
874 struct DepthBuilder : public PassAttributeBuilder
876 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
877 const osgDB::ReaderWriter::Options* options)
879 if (!isAttributeActive(effect, prop))
881 ref_ptr<Depth> depth = new Depth;
882 const SGPropertyNode* pfunc
883 = getEffectPropertyChild(effect, prop, "function");
885 Depth::Function func = Depth::LESS;
886 findAttr(depthFunction, pfunc, func);
887 depth->setFunction(func);
889 const SGPropertyNode* pnear
890 = getEffectPropertyChild(effect, prop, "near");
892 depth->setZNear(pnear->getValue<double>());
893 const SGPropertyNode* pfar
894 = getEffectPropertyChild(effect, prop, "far");
896 depth->setZFar(pnear->getValue<double>());
897 const SGPropertyNode* pmask
898 = getEffectPropertyChild(effect, prop, "write-mask");
900 depth->setWriteMask(pmask->getValue<bool>());
901 pass->setAttribute(depth.get());
905 InstallAttributeBuilder<DepthBuilder> installDepth("depth");
907 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
908 const osgDB::ReaderWriter::Options* options)
910 Technique* tniq = new Technique;
911 effect->techniques.push_back(tniq);
912 const SGPropertyNode* predProp = prop->getChild("predicate");
914 tniq->setAlwaysValid(true);
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
925 tniq->setValidExpression(validExp, layout);
927 throw expression::ParseError("technique predicate is not a boolean expression");
929 catch (expression::ParseError& except)
931 SG_LOG(SG_INPUT, SG_ALERT,
932 "parsing technique predicate " << except.getMessage());
933 tniq->setAlwaysValid(false);
936 PropertyList passProps = prop->getChildren("pass");
937 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
940 buildPass(effect, tniq, itr->ptr(), options);
944 // Specifically for .ac files...
945 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
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);
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");
966 makeChild(matNode, "active")->setValue(false);
968 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
969 string shadeModelString("smooth");
971 ShadeModel::Mode smMode = sm->getMode();
972 if (smMode == ShadeModel::FLAT)
973 shadeModelString = "flat";
975 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
976 string cullFaceString("off");
977 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
979 switch (cullFace->getMode()) {
980 case CullFace::FRONT:
981 cullFaceString = "front";
984 cullFaceString = "back";
986 case CullFace::FRONT_AND_BACK:
987 cullFaceString = "front-back";
993 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
994 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
995 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
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);
1004 makeChild(blendNode, "active")->setValue(false);
1006 string renderingHint = findName(renderingHints, ss->getRenderingHint());
1007 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
1008 makeTextureParameters(paramRoot, ss);
1012 // Walk the techniques property tree, building techniques and
1014 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
1018 PropertyList tniqList = root->getChildren("technique");
1019 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
1022 buildTechnique(this, *itr, options);
1027 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
1029 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
1032 Effect* effect = eg->getEffect();
1035 SGPropertyNode* root = getPropertyRoot();
1036 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
1037 end = effect->_extraData.end();
1040 InitializeWhenAdded* adder
1041 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
1043 adder->initOnAdd(effect, root);
1047 bool Effect::Key::EqualTo::operator()(const Effect::Key& lhs,
1048 const Effect::Key& rhs) const
1050 if (lhs.paths.size() != rhs.paths.size()
1051 || !equal(lhs.paths.begin(), lhs.paths.end(), rhs.paths.begin()))
1053 if (lhs.unmerged.valid() && rhs.unmerged.valid())
1054 return props::Compare()(lhs.unmerged, rhs.unmerged);
1056 return lhs.unmerged == rhs.unmerged;
1059 size_t hash_value(const Effect::Key& key)
1062 if (key.unmerged.valid())
1063 boost::hash_combine(seed, *key.unmerged);
1064 boost::hash_range(seed, key.paths.begin(), key.paths.end());
1068 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
1070 const Effect& effect = static_cast<const Effect&>(obj);
1072 fw.indent() << "techniques " << effect.techniques.size() << "\n";
1073 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
1074 fw.writeObject(*technique);
1081 osgDB::RegisterDotOsgWrapperProxy effectProxy
1085 "Object simgear::Effect",
1087 &Effect_writeLocalData
1091 // Property expressions for technique predicates
1092 class PropertyExpression : public SGExpression<bool>
1095 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
1097 void eval(bool& value, const expression::Binding*) const
1099 value = _pnode->getValue<bool>();
1102 SGPropertyNode_ptr _pnode;
1105 class EffectPropertyListener : public SGPropertyChangeListener
1108 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
1110 void valueChanged(SGPropertyNode* node)
1112 _tniq->refreshValidity();
1115 osg::ref_ptr<Technique> _tniq;
1118 Expression* propertyExpressionParser(const SGPropertyNode* exp,
1119 expression::Parser* parser)
1121 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
1123 PropertyExpression* pexp = new PropertyExpression(pnode);
1124 TechniquePredParser* predParser
1125 = dynamic_cast<TechniquePredParser*>(parser);
1127 pnode->addChangeListener(new EffectPropertyListener(predParser
1132 expression::ExpParserRegistrar propertyRegistrar("property",
1133 propertyExpressionParser);