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"
34 #include <boost/foreach.hpp>
35 #include <boost/tuple/tuple.hpp>
36 #include <boost/tuple/tuple_comparison.hpp>
38 #include <osg/AlphaFunc>
39 #include <osg/BlendFunc>
40 #include <osg/CullFace>
41 #include <osg/Drawable>
42 #include <osg/Material>
44 #include <osg/PolygonMode>
45 #include <osg/Program>
46 #include <osg/Referenced>
47 #include <osg/RenderInfo>
48 #include <osg/ShadeModel>
49 #include <osg/StateSet>
51 #include <osg/Texture1D>
52 #include <osg/Texture2D>
53 #include <osg/Texture3D>
54 #include <osg/TextureRectangle>
55 #include <osg/Uniform>
57 #include <osgUtil/CullVisitor>
58 #include <osgDB/FileUtils>
59 #include <osgDB/Input>
60 #include <osgDB/ParameterOutput>
61 #include <osgDB/ReadFile>
62 #include <osgDB/Registry>
64 #include <simgear/scene/tgdb/userdata.hxx>
65 #include <simgear/scene/util/SGSceneFeatures.hxx>
66 #include <simgear/scene/util/StateAttributeFactory.hxx>
67 #include <simgear/structure/OSGUtils.hxx>
68 #include <simgear/structure/SGExpression.hxx>
76 using namespace osgUtil;
78 using namespace effect;
84 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
85 : root(rhs.root), parametersProp(rhs.parametersProp)
87 typedef vector<ref_ptr<Technique> > TechniqueList;
88 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
89 end = rhs.techniques.end();
92 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
95 // Assume that the last technique is always valid.
96 StateSet* Effect::getDefaultStateSet()
98 Technique* tniq = techniques.back().get();
101 Pass* pass = tniq->passes.front().get();
105 // There should always be a valid technique in an effect.
107 Technique* Effect::chooseTechnique(RenderInfo* info)
109 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
111 if (technique->valid(info) == Technique::VALID)
112 return technique.get();
117 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
119 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
121 technique->resizeGLObjectBuffers(maxSize);
125 void Effect::releaseGLObjects(osg::State* state) const
127 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
129 technique->releaseGLObjects(state);
137 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
138 const osgDB::ReaderWriter::Options* options)
140 Pass* pass = new Pass;
141 tniq->passes.push_back(pass);
142 for (int i = 0; i < prop->nChildren(); ++i) {
143 const SGPropertyNode* attrProp = prop->getChild(i);
144 PassAttributeBuilder* builder
145 = PassAttributeBuilder::find(attrProp->getNameString());
147 builder->buildAttribute(effect, pass, attrProp, options);
149 SG_LOG(SG_INPUT, SG_ALERT,
150 "skipping unknown pass attribute " << attrProp->getName());
154 osg::Vec4f getColor(const SGPropertyNode* prop)
156 if (prop->nChildren() == 0) {
157 if (prop->getType() == props::VEC4D) {
158 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
159 } else if (prop->getType() == props::VEC3D) {
160 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
162 SG_LOG(SG_INPUT, SG_ALERT,
163 "invalid color property " << prop->getName() << " "
164 << prop->getStringValue());
165 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
169 static const char* colors[] = {"r", "g", "b"};
170 for (int i = 0; i < 3; ++i) {
171 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
172 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
174 const SGPropertyNode* alphaProp = prop->getChild("a");
175 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
180 struct LightingBuilder : public PassAttributeBuilder
182 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
183 const osgDB::ReaderWriter::Options* options);
186 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
187 const SGPropertyNode* prop,
188 const osgDB::ReaderWriter::Options* options)
190 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
193 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
194 : StateAttribute::OFF));
197 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
199 struct ShadeModelBuilder : public PassAttributeBuilder
201 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
202 const osgDB::ReaderWriter::Options* options)
204 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
207 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
208 string propVal = realProp->getStringValue();
209 if (propVal == "flat")
210 pass->setAttribute(attrFact->getFlatShadeModel());
211 else if (propVal == "smooth")
212 pass->setAttribute(attrFact->getSmoothShadeModel());
214 SG_LOG(SG_INPUT, SG_ALERT,
215 "invalid shade model property " << propVal);
219 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
221 struct CullFaceBuilder : PassAttributeBuilder
223 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
224 const osgDB::ReaderWriter::Options* options)
226 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
228 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
231 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
232 string propVal = realProp->getStringValue();
233 if (propVal == "front")
234 pass->setAttributeAndModes(attrFact->getCullFaceFront());
235 else if (propVal == "back")
236 pass->setAttributeAndModes(attrFact->getCullFaceBack());
237 else if (propVal == "front-back")
238 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
239 else if (propVal == "off")
240 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
242 SG_LOG(SG_INPUT, SG_ALERT,
243 "invalid cull face property " << propVal);
247 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
249 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
251 { "default", StateSet::DEFAULT_BIN },
252 { "opaque", StateSet::OPAQUE_BIN },
253 { "transparent", StateSet::TRANSPARENT_BIN }
256 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
258 struct HintBuilder : public PassAttributeBuilder
260 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
261 const osgDB::ReaderWriter::Options* options)
263 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
266 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
267 findAttr(renderingHints, realProp, renderingHint);
268 pass->setRenderingHint(renderingHint);
272 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
274 struct RenderBinBuilder : public PassAttributeBuilder
276 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
277 const osgDB::ReaderWriter::Options* options)
279 if (!isAttributeActive(effect, prop))
281 const SGPropertyNode* binProp = prop->getChild("bin-number");
282 binProp = getEffectPropertyNode(effect, binProp);
283 const SGPropertyNode* nameProp = prop->getChild("bin-name");
284 nameProp = getEffectPropertyNode(effect, nameProp);
285 if (binProp && nameProp) {
286 pass->setRenderBinDetails(binProp->getIntValue(),
287 nameProp->getStringValue());
290 SG_LOG(SG_INPUT, SG_ALERT,
291 "No render bin number specified in render bin section");
293 SG_LOG(SG_INPUT, SG_ALERT,
294 "No render bin name specified in render bin section");
299 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
301 struct MaterialBuilder : public PassAttributeBuilder
303 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
304 const osgDB::ReaderWriter::Options* options);
307 EffectNameValue<Material::ColorMode> colorModeInit[] =
309 { "ambient", Material::AMBIENT },
310 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
311 { "diffuse", Material::DIFFUSE },
312 { "emissive", Material::EMISSION },
313 { "specular", Material::SPECULAR },
314 { "off", Material::OFF }
316 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
318 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
319 const SGPropertyNode* prop,
320 const osgDB::ReaderWriter::Options* options)
322 if (!isAttributeActive(effect, prop))
324 Material* mat = new Material;
325 const SGPropertyNode* color = 0;
326 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
327 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
328 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
329 mat->setAmbient(Material::FRONT, getColor(color));
330 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
331 mat->setAmbient(Material::BACK, getColor(color));
332 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
333 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
334 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
335 mat->setDiffuse(Material::FRONT, getColor(color));
336 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
337 mat->setDiffuse(Material::BACK, getColor(color));
338 if ((color = getEffectPropertyChild(effect, prop, "specular")))
339 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
340 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
341 mat->setSpecular(Material::FRONT, getColor(color));
342 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
343 mat->setSpecular(Material::BACK, getColor(color));
344 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
345 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
346 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
347 mat->setEmission(Material::FRONT, getColor(color));
348 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
349 mat->setEmission(Material::BACK, getColor(color));
350 const SGPropertyNode* shininess = 0;
351 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
352 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
353 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
354 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
355 mat->setShininess(Material::FRONT, shininess->getFloatValue());
356 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
357 mat->setShininess(Material::BACK, shininess->getFloatValue());
358 Material::ColorMode colorMode = Material::OFF;
359 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
361 mat->setColorMode(colorMode);
362 pass->setAttribute(mat);
365 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
367 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
369 {"dst-alpha", BlendFunc::DST_ALPHA},
370 {"dst-color", BlendFunc::DST_COLOR},
371 {"one", BlendFunc::ONE},
372 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
373 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
374 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
375 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
376 {"src-alpha", BlendFunc::SRC_ALPHA},
377 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
378 {"src-color", BlendFunc::SRC_COLOR},
379 {"constant-color", BlendFunc::CONSTANT_COLOR},
380 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
381 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
382 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
383 {"zero", BlendFunc::ZERO}
385 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
387 struct BlendBuilder : public PassAttributeBuilder
389 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
390 const osgDB::ReaderWriter::Options* options)
392 if (!isAttributeActive(effect, prop))
394 // XXX Compatibility with early <blend> syntax; should go away
396 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
399 if (realProp->nChildren() == 0) {
400 pass->setMode(GL_BLEND, (realProp->getBoolValue()
402 : StateAttribute::OFF));
406 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
408 // XXX When dynamic parameters are supported, this code should
409 // create the blend function even if the mode is off.
410 if (pmode && !pmode->getValue<bool>()) {
411 pass->setMode(GL_BLEND, StateAttribute::OFF);
414 const SGPropertyNode* psource
415 = getEffectPropertyChild(effect, prop, "source");
416 const SGPropertyNode* pdestination
417 = getEffectPropertyChild(effect, prop, "destination");
418 const SGPropertyNode* psourceRGB
419 = getEffectPropertyChild(effect, prop, "source-rgb");
420 const SGPropertyNode* psourceAlpha
421 = getEffectPropertyChild(effect, prop, "source-alpha");
422 const SGPropertyNode* pdestRGB
423 = getEffectPropertyChild(effect, prop, "destination-rgb");
424 const SGPropertyNode* pdestAlpha
425 = getEffectPropertyChild(effect, prop, "destination-alpha");
426 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
427 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
429 findAttr(blendFuncModes, psource, sourceMode);
431 findAttr(blendFuncModes, pdestination, destMode);
432 if (psource && pdestination
433 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
434 && sourceMode == BlendFunc::SRC_ALPHA
435 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
436 pass->setAttributeAndModes(StateAttributeFactory::instance()
437 ->getStandardBlendFunc());
440 BlendFunc* blendFunc = new BlendFunc;
442 blendFunc->setSource(sourceMode);
444 blendFunc->setDestination(destMode);
446 BlendFunc::BlendFuncMode sourceRGBMode;
447 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
448 blendFunc->setSourceRGB(sourceRGBMode);
451 BlendFunc::BlendFuncMode destRGBMode;
452 findAttr(blendFuncModes, pdestRGB, destRGBMode);
453 blendFunc->setDestinationRGB(destRGBMode);
456 BlendFunc::BlendFuncMode sourceAlphaMode;
457 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
458 blendFunc->setSourceAlpha(sourceAlphaMode);
461 BlendFunc::BlendFuncMode destAlphaMode;
462 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
463 blendFunc->setDestinationAlpha(destAlphaMode);
465 pass->setAttributeAndModes(blendFunc);
469 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
471 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
473 {"never", AlphaFunc::NEVER},
474 {"less", AlphaFunc::LESS},
475 {"equal", AlphaFunc::EQUAL},
476 {"lequal", AlphaFunc::LEQUAL},
477 {"greater", AlphaFunc::GREATER},
478 {"notequal", AlphaFunc::NOTEQUAL},
479 {"gequal", AlphaFunc::GEQUAL},
480 {"always", AlphaFunc::ALWAYS}
482 EffectPropertyMap<AlphaFunc::ComparisonFunction>
483 alphaComparison(alphaComparisonInit);
485 struct AlphaTestBuilder : public PassAttributeBuilder
487 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
488 const osgDB::ReaderWriter::Options* options)
490 if (!isAttributeActive(effect, prop))
492 // XXX Compatibility with early <alpha-test> syntax; should go away
494 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
497 if (realProp->nChildren() == 0) {
498 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
500 : StateAttribute::OFF));
504 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
506 // XXX When dynamic parameters are supported, this code should
507 // create the blend function even if the mode is off.
508 if (pmode && !pmode->getValue<bool>()) {
509 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
512 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
514 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
516 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
517 float refValue = 1.0f;
519 findAttr(alphaComparison, pComp, func);
521 refValue = pRef->getValue<float>();
522 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
523 pass->setAttributeAndModes(StateAttributeFactory::instance()
524 ->getStandardAlphaFunc());
526 AlphaFunc* alphaFunc = new AlphaFunc;
527 alphaFunc->setFunction(func);
528 alphaFunc->setReferenceValue(refValue);
529 pass->setAttributeAndModes(alphaFunc);
534 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
536 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
538 typedef map<string, ref_ptr<Program> > ProgramMap;
539 ProgramMap programMap;
541 typedef map<string, ref_ptr<Shader> > ShaderMap;
544 void reload_shaders()
546 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
548 Shader *shader = sitr->second.get();
549 string fileName = osgDB::findDataFile(sitr->first);
550 if (!fileName.empty()) {
551 shader->loadShaderSourceFromFile(fileName);
556 struct ShaderProgramBuilder : PassAttributeBuilder
558 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
559 const osgDB::ReaderWriter::Options* options);
562 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
563 const SGPropertyNode* prop,
564 const osgDB::ReaderWriter::Options*
567 if (!isAttributeActive(effect, prop))
569 PropertyList pVertShaders = prop->getChildren("vertex-shader");
570 PropertyList pFragShaders = prop->getChildren("fragment-shader");
572 for (PropertyList::iterator itr = pVertShaders.begin(),
573 e = pVertShaders.end();
577 programKey += (*itr)->getStringValue();
580 for (PropertyList::iterator itr = pFragShaders.begin(),
581 e = pFragShaders.end();
585 programKey += (*itr)->getStringValue();
588 Program* program = 0;
589 ProgramMap::iterator pitr = programMap.find(programKey);
590 if (pitr != programMap.end()) {
591 program = pitr->second.get();
593 program = new Program;
594 program->setName(programKey);
595 // Add vertex shaders, then fragment shaders
596 PropertyList& pvec = pVertShaders;
597 Shader::Type stype = Shader::VERTEX;
598 for (int i = 0; i < 2; ++i) {
599 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
602 string shaderName = (*nameItr)->getStringValue();
603 ShaderMap::iterator sitr = shaderMap.find(shaderName);
604 if (sitr != shaderMap.end()) {
605 program->addShader(sitr->second.get());
607 string fileName = osgDB::findDataFile(shaderName, options);
608 if (!fileName.empty()) {
609 ref_ptr<Shader> shader = new Shader(stype);
610 if (shader->loadShaderSourceFromFile(fileName)) {
611 program->addShader(shader.get());
612 shaderMap.insert(make_pair(shaderName, shader));
618 stype = Shader::FRAGMENT;
620 programMap.insert(make_pair(programKey, program));
622 pass->setAttributeAndModes(program);
625 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
627 EffectNameValue<Uniform::Type> uniformTypesInit[] =
629 {"float", Uniform::FLOAT},
630 {"float-vec3", Uniform::FLOAT_VEC3},
631 {"float-vec4", Uniform::FLOAT_VEC4},
632 {"sampler-1d", Uniform::SAMPLER_1D},
633 {"sampler-2d", Uniform::SAMPLER_2D},
634 {"sampler-3d", Uniform::SAMPLER_3D}
636 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
638 struct UniformBuilder :public PassAttributeBuilder
640 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
641 const osgDB::ReaderWriter::Options* options)
643 if (!isAttributeActive(effect, prop))
645 const SGPropertyNode* nameProp = prop->getChild("name");
646 const SGPropertyNode* typeProp = prop->getChild("type");
647 const SGPropertyNode* valProp
648 = getEffectPropertyChild(effect, prop, "value");
650 Uniform::Type uniformType = Uniform::FLOAT;
652 name = nameProp->getStringValue();
654 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
658 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
663 props::Type propType = valProp->getType();
667 break; // default float type;
669 uniformType = Uniform::FLOAT_VEC3;
672 uniformType = Uniform::FLOAT_VEC4;
675 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
680 findAttr(uniformTypes, typeProp, uniformType);
682 ref_ptr<Uniform> uniform = new Uniform;
683 uniform->setName(name);
684 uniform->setType(uniformType);
685 switch (uniformType) {
687 uniform->set(valProp->getValue<float>());
689 case Uniform::FLOAT_VEC3:
690 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
692 case Uniform::FLOAT_VEC4:
693 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
695 case Uniform::SAMPLER_1D:
696 case Uniform::SAMPLER_2D:
697 case Uniform::SAMPLER_3D:
698 uniform->set(valProp->getValue<int>());
700 default: // avoid compiler warning
703 pass->addUniform(uniform.get());
707 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
709 // Not sure what to do with "name". At one point I wanted to use it to
710 // order the passes, but I do support render bin and stuff too...
712 struct NameBuilder : public PassAttributeBuilder
714 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
715 const osgDB::ReaderWriter::Options* options)
717 // name can't use <use>
718 string name = prop->getStringValue();
724 InstallAttributeBuilder<NameBuilder> installName("name");
726 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
728 {"fill", PolygonMode::FILL},
729 {"line", PolygonMode::LINE},
730 {"point", PolygonMode::POINT}
732 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
734 struct PolygonModeBuilder : public PassAttributeBuilder
736 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
737 const osgDB::ReaderWriter::Options* options)
739 if (!isAttributeActive(effect, prop))
741 const SGPropertyNode* frontProp
742 = getEffectPropertyChild(effect, prop, "front");
743 const SGPropertyNode* backProp
744 = getEffectPropertyChild(effect, prop, "back");
745 ref_ptr<PolygonMode> pmode = new PolygonMode;
746 PolygonMode::Mode frontMode = PolygonMode::FILL;
747 PolygonMode::Mode backMode = PolygonMode::FILL;
749 findAttr(polygonModeModes, frontProp, frontMode);
750 pmode->setMode(PolygonMode::FRONT, frontMode);
753 findAttr(polygonModeModes, backProp, backMode);
754 pmode->setMode(PolygonMode::BACK, backMode);
756 pass->setAttribute(pmode.get());
760 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
761 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
762 const osgDB::ReaderWriter::Options* options)
764 Technique* tniq = new Technique;
765 effect->techniques.push_back(tniq);
766 const SGPropertyNode* predProp = prop->getChild("predicate");
768 tniq->setAlwaysValid(true);
771 TechniquePredParser parser;
772 parser.setTechnique(tniq);
773 expression::BindingLayout& layout = parser.getBindingLayout();
774 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
775 SGExpressionb* validExp
776 = dynamic_cast<SGExpressionb*>(parser.read(predProp
779 tniq->setValidExpression(validExp, layout);
781 throw expression::ParseError("technique predicate is not a boolean expression");
783 catch (expression::ParseError& except)
785 SG_LOG(SG_INPUT, SG_ALERT,
786 "parsing technique predicate " << except.getMessage());
787 tniq->setAlwaysValid(false);
790 PropertyList passProps = prop->getChildren("pass");
791 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
794 buildPass(effect, tniq, itr->ptr(), options);
798 // Specifically for .ac files...
799 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
801 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
802 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
803 Vec4f ambVal, difVal, specVal, emisVal;
804 float shininess = 0.0f;
805 const Material* mat = getStateAttribute<Material>(ss);
807 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
808 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
809 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
810 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
811 shininess = mat->getShininess(Material::FRONT_AND_BACK);
812 makeChild(matNode, "active")->setValue(true);
813 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
814 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
815 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
816 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
817 makeChild(matNode, "shininess")->setValue(shininess);
818 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
820 makeChild(matNode, "active")->setValue(false);
822 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
823 string shadeModelString("smooth");
825 ShadeModel::Mode smMode = sm->getMode();
826 if (smMode == ShadeModel::FLAT)
827 shadeModelString = "flat";
829 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
830 string cullFaceString("off");
831 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
833 switch (cullFace->getMode()) {
834 case CullFace::FRONT:
835 cullFaceString = "front";
838 cullFaceString = "back";
840 case CullFace::FRONT_AND_BACK:
841 cullFaceString = "front-back";
847 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
848 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
849 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
851 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
852 string destMode = findName(blendFuncModes, blendFunc->getDestination());
853 makeChild(blendNode, "active")->setValue(true);
854 makeChild(blendNode, "source")->setStringValue(sourceMode);
855 makeChild(blendNode, "destination")->setStringValue(destMode);
856 makeChild(blendNode, "mode")->setValue(true);
858 makeChild(blendNode, "active")->setValue(false);
860 string renderingHint = findName(renderingHints, ss->getRenderingHint());
861 makeChild(paramRoot, "rendering-hint")->setStringValue(renderingHint);
862 makeTextureParameters(paramRoot, ss);
866 // Walk the techniques property tree, building techniques and
868 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
870 PropertyList tniqList = root->getChildren("technique");
871 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
874 buildTechnique(this, *itr, options);
878 void Effect::InitializeCallback::doUpdate(osg::Node* node, osg::NodeVisitor* nv)
880 EffectGeode* eg = dynamic_cast<EffectGeode*>(node);
883 Effect* effect = eg->getEffect();
886 SGPropertyNode* root = getPropertyRoot();
887 for (vector<SGSharedPtr<Updater> >::iterator itr = effect->_extraData.begin(),
888 end = effect->_extraData.end();
891 InitializeWhenAdded* adder
892 = dynamic_cast<InitializeWhenAdded*>(itr->ptr());
894 adder->initOnAdd(effect, root);
898 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
900 const Effect& effect = static_cast<const Effect&>(obj);
902 fw.indent() << "techniques " << effect.techniques.size() << "\n";
903 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
904 fw.writeObject(*technique);
911 osgDB::RegisterDotOsgWrapperProxy effectProxy
915 "Object simgear::Effect",
917 &Effect_writeLocalData
921 // Property expressions for technique predicates
922 class PropertyExpression : public SGExpression<bool>
925 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
927 void eval(bool& value, const expression::Binding*) const
929 value = _pnode->getValue<bool>();
932 SGPropertyNode_ptr _pnode;
935 class EffectPropertyListener : public SGPropertyChangeListener
938 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
940 void valueChanged(SGPropertyNode* node)
942 _tniq->refreshValidity();
945 osg::ref_ptr<Technique> _tniq;
948 Expression* propertyExpressionParser(const SGPropertyNode* exp,
949 expression::Parser* parser)
951 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
953 PropertyExpression* pexp = new PropertyExpression(pnode);
954 TechniquePredParser* predParser
955 = dynamic_cast<TechniquePredParser*>(parser);
957 pnode->addChangeListener(new EffectPropertyListener(predParser
962 expression::ExpParserRegistrar propertyRegistrar("property",
963 propertyExpressionParser);