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 "Technique.hxx"
25 #include "TextureBuilder.hxx"
33 #include <boost/foreach.hpp>
34 #include <boost/tuple/tuple.hpp>
35 #include <boost/tuple/tuple_comparison.hpp>
37 #include <osg/AlphaFunc>
38 #include <osg/BlendFunc>
39 #include <osg/CullFace>
40 #include <osg/Drawable>
41 #include <osg/Material>
43 #include <osg/PolygonMode>
44 #include <osg/Program>
45 #include <osg/Referenced>
46 #include <osg/RenderInfo>
47 #include <osg/ShadeModel>
48 #include <osg/StateSet>
50 #include <osg/Texture1D>
51 #include <osg/Texture2D>
52 #include <osg/Texture3D>
53 #include <osg/TextureRectangle>
54 #include <osg/Uniform>
56 #include <osgUtil/CullVisitor>
57 #include <osgDB/FileUtils>
58 #include <osgDB/Input>
59 #include <osgDB/ParameterOutput>
60 #include <osgDB/ReadFile>
61 #include <osgDB/Registry>
63 #include <simgear/scene/tgdb/userdata.hxx>
64 #include <simgear/scene/util/SGSceneFeatures.hxx>
65 #include <simgear/scene/util/StateAttributeFactory.hxx>
66 #include <simgear/structure/OSGUtils.hxx>
67 #include <simgear/structure/SGExpression.hxx>
75 using namespace osgUtil;
77 using namespace effect;
83 Effect::Effect(const Effect& rhs, const CopyOp& copyop)
84 : root(rhs.root), parametersProp(rhs.parametersProp)
86 typedef vector<ref_ptr<Technique> > TechniqueList;
87 for (TechniqueList::const_iterator itr = rhs.techniques.begin(),
88 end = rhs.techniques.end();
91 techniques.push_back(static_cast<Technique*>(copyop(itr->get())));
94 // Assume that the last technique is always valid.
95 StateSet* Effect::getDefaultStateSet()
97 Technique* tniq = techniques.back().get();
100 Pass* pass = tniq->passes.front().get();
104 // There should always be a valid technique in an effect.
106 Technique* Effect::chooseTechnique(RenderInfo* info)
108 BOOST_FOREACH(ref_ptr<Technique>& technique, techniques)
110 if (technique->valid(info) == Technique::VALID)
111 return technique.get();
116 void Effect::resizeGLObjectBuffers(unsigned int maxSize)
118 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
120 technique->resizeGLObjectBuffers(maxSize);
124 void Effect::releaseGLObjects(osg::State* state) const
126 BOOST_FOREACH(const ref_ptr<Technique>& technique, techniques)
128 technique->releaseGLObjects(state);
136 void buildPass(Effect* effect, Technique* tniq, const SGPropertyNode* prop,
137 const osgDB::ReaderWriter::Options* options)
139 Pass* pass = new Pass;
140 tniq->passes.push_back(pass);
141 for (int i = 0; i < prop->nChildren(); ++i) {
142 const SGPropertyNode* attrProp = prop->getChild(i);
143 PassAttributeBuilder* builder
144 = PassAttributeBuilder::find(attrProp->getNameString());
146 builder->buildAttribute(effect, pass, attrProp, options);
148 SG_LOG(SG_INPUT, SG_ALERT,
149 "skipping unknown pass attribute " << attrProp->getName());
153 osg::Vec4f getColor(const SGPropertyNode* prop)
155 if (prop->nChildren() == 0) {
156 if (prop->getType() == props::VEC4D) {
157 return osg::Vec4f(toOsg(prop->getValue<SGVec4d>()));
158 } else if (prop->getType() == props::VEC3D) {
159 return osg::Vec4f(toOsg(prop->getValue<SGVec3d>()), 1.0f);
161 SG_LOG(SG_INPUT, SG_ALERT,
162 "invalid color property " << prop->getName() << " "
163 << prop->getStringValue());
164 return osg::Vec4f(0.0f, 0.0f, 0.0f, 1.0f);
168 static const char* colors[] = {"r", "g", "b"};
169 for (int i = 0; i < 3; ++i) {
170 const SGPropertyNode* componentProp = prop->getChild(colors[i]);
171 result[i] = componentProp ? componentProp->getValue<float>() : 0.0f;
173 const SGPropertyNode* alphaProp = prop->getChild("a");
174 result[3] = alphaProp ? alphaProp->getValue<float>() : 1.0f;
179 struct LightingBuilder : public PassAttributeBuilder
181 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
182 const osgDB::ReaderWriter::Options* options);
185 void LightingBuilder::buildAttribute(Effect* effect, Pass* pass,
186 const SGPropertyNode* prop,
187 const osgDB::ReaderWriter::Options* options)
189 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
192 pass->setMode(GL_LIGHTING, (realProp->getValue<bool>() ? StateAttribute::ON
193 : StateAttribute::OFF));
196 InstallAttributeBuilder<LightingBuilder> installLighting("lighting");
198 struct ShadeModelBuilder : public PassAttributeBuilder
200 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
201 const osgDB::ReaderWriter::Options* options)
203 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
206 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
207 string propVal = realProp->getStringValue();
208 if (propVal == "flat")
209 pass->setAttribute(attrFact->getFlatShadeModel());
210 else if (propVal == "smooth")
211 pass->setAttribute(attrFact->getSmoothShadeModel());
213 SG_LOG(SG_INPUT, SG_ALERT,
214 "invalid shade model property " << propVal);
218 InstallAttributeBuilder<ShadeModelBuilder> installShadeModel("shade-model");
220 struct CullFaceBuilder : PassAttributeBuilder
222 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
223 const osgDB::ReaderWriter::Options* options)
225 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
227 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
230 StateAttributeFactory *attrFact = StateAttributeFactory::instance();
231 string propVal = realProp->getStringValue();
232 if (propVal == "front")
233 pass->setAttributeAndModes(attrFact->getCullFaceFront());
234 else if (propVal == "back")
235 pass->setAttributeAndModes(attrFact->getCullFaceBack());
236 else if (propVal == "front-back")
237 pass->setAttributeAndModes(new CullFace(CullFace::FRONT_AND_BACK));
238 else if (propVal == "off")
239 pass->setMode(GL_CULL_FACE, StateAttribute::OFF);
241 SG_LOG(SG_INPUT, SG_ALERT,
242 "invalid cull face property " << propVal);
246 InstallAttributeBuilder<CullFaceBuilder> installCullFace("cull-face");
248 EffectNameValue<StateSet::RenderingHint> renderingHintInit[] =
250 { "default", StateSet::DEFAULT_BIN },
251 { "opaque", StateSet::OPAQUE_BIN },
252 { "transparent", StateSet::TRANSPARENT_BIN }
255 EffectPropertyMap<StateSet::RenderingHint> renderingHints(renderingHintInit);
257 struct HintBuilder : public PassAttributeBuilder
259 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
260 const osgDB::ReaderWriter::Options* options)
262 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
265 StateSet::RenderingHint renderingHint = StateSet::DEFAULT_BIN;
266 findAttr(renderingHints, realProp, renderingHint);
267 pass->setRenderingHint(renderingHint);
271 InstallAttributeBuilder<HintBuilder> installHint("rendering-hint");
273 struct RenderBinBuilder : public PassAttributeBuilder
275 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
276 const osgDB::ReaderWriter::Options* options)
278 if (!isAttributeActive(effect, prop))
280 const SGPropertyNode* binProp = prop->getChild("bin-number");
281 binProp = getEffectPropertyNode(effect, binProp);
282 const SGPropertyNode* nameProp = prop->getChild("bin-name");
283 nameProp = getEffectPropertyNode(effect, nameProp);
284 if (binProp && nameProp) {
285 pass->setRenderBinDetails(binProp->getIntValue(),
286 nameProp->getStringValue());
289 SG_LOG(SG_INPUT, SG_ALERT,
290 "No render bin number specified in render bin section");
292 SG_LOG(SG_INPUT, SG_ALERT,
293 "No render bin name specified in render bin section");
298 InstallAttributeBuilder<RenderBinBuilder> installRenderBin("render-bin");
300 struct MaterialBuilder : public PassAttributeBuilder
302 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
303 const osgDB::ReaderWriter::Options* options);
306 EffectNameValue<Material::ColorMode> colorModeInit[] =
308 { "ambient", Material::AMBIENT },
309 { "ambient-and-diffuse", Material::AMBIENT_AND_DIFFUSE },
310 { "diffuse", Material::DIFFUSE },
311 { "emissive", Material::EMISSION },
312 { "specular", Material::SPECULAR },
313 { "off", Material::OFF }
315 EffectPropertyMap<Material::ColorMode> colorModes(colorModeInit);
317 void MaterialBuilder::buildAttribute(Effect* effect, Pass* pass,
318 const SGPropertyNode* prop,
319 const osgDB::ReaderWriter::Options* options)
321 if (!isAttributeActive(effect, prop))
323 Material* mat = new Material;
324 const SGPropertyNode* color = 0;
325 if ((color = getEffectPropertyChild(effect, prop, "ambient")))
326 mat->setAmbient(Material::FRONT_AND_BACK, getColor(color));
327 if ((color = getEffectPropertyChild(effect, prop, "ambient-front")))
328 mat->setAmbient(Material::FRONT, getColor(color));
329 if ((color = getEffectPropertyChild(effect, prop, "ambient-back")))
330 mat->setAmbient(Material::BACK, getColor(color));
331 if ((color = getEffectPropertyChild(effect, prop, "diffuse")))
332 mat->setDiffuse(Material::FRONT_AND_BACK, getColor(color));
333 if ((color = getEffectPropertyChild(effect, prop, "diffuse-front")))
334 mat->setDiffuse(Material::FRONT, getColor(color));
335 if ((color = getEffectPropertyChild(effect, prop, "diffuse-back")))
336 mat->setDiffuse(Material::BACK, getColor(color));
337 if ((color = getEffectPropertyChild(effect, prop, "specular")))
338 mat->setSpecular(Material::FRONT_AND_BACK, getColor(color));
339 if ((color = getEffectPropertyChild(effect, prop, "specular-front")))
340 mat->setSpecular(Material::FRONT, getColor(color));
341 if ((color = getEffectPropertyChild(effect, prop, "specular-back")))
342 mat->setSpecular(Material::BACK, getColor(color));
343 if ((color = getEffectPropertyChild(effect, prop, "emissive")))
344 mat->setEmission(Material::FRONT_AND_BACK, getColor(color));
345 if ((color = getEffectPropertyChild(effect, prop, "emissive-front")))
346 mat->setEmission(Material::FRONT, getColor(color));
347 if ((color = getEffectPropertyChild(effect, prop, "emissive-back")))
348 mat->setEmission(Material::BACK, getColor(color));
349 const SGPropertyNode* shininess = 0;
350 mat->setShininess(Material::FRONT_AND_BACK, 0.0f);
351 if ((shininess = getEffectPropertyChild(effect, prop, "shininess")))
352 mat->setShininess(Material::FRONT_AND_BACK, shininess->getFloatValue());
353 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-front")))
354 mat->setShininess(Material::FRONT, shininess->getFloatValue());
355 if ((shininess = getEffectPropertyChild(effect, prop, "shininess-back")))
356 mat->setShininess(Material::BACK, shininess->getFloatValue());
357 Material::ColorMode colorMode = Material::OFF;
358 findAttr(colorModes, getEffectPropertyChild(effect, prop, "color-mode"),
360 mat->setColorMode(colorMode);
361 pass->setAttribute(mat);
364 InstallAttributeBuilder<MaterialBuilder> installMaterial("material");
366 EffectNameValue<BlendFunc::BlendFuncMode> blendFuncModesInit[] =
368 {"dst-alpha", BlendFunc::DST_ALPHA},
369 {"dst-color", BlendFunc::DST_COLOR},
370 {"one", BlendFunc::ONE},
371 {"one-minus-dst-alpha", BlendFunc::ONE_MINUS_DST_ALPHA},
372 {"one-minus-dst-color", BlendFunc::ONE_MINUS_DST_COLOR},
373 {"one-minus-src-alpha", BlendFunc::ONE_MINUS_SRC_ALPHA},
374 {"one-minus-src-color", BlendFunc::ONE_MINUS_SRC_COLOR},
375 {"src-alpha", BlendFunc::SRC_ALPHA},
376 {"src-alpha-saturate", BlendFunc::SRC_ALPHA_SATURATE},
377 {"src-color", BlendFunc::SRC_COLOR},
378 {"constant-color", BlendFunc::CONSTANT_COLOR},
379 {"one-minus-constant-color", BlendFunc::ONE_MINUS_CONSTANT_COLOR},
380 {"constant-alpha", BlendFunc::CONSTANT_ALPHA},
381 {"one-minus-constant-alpha", BlendFunc::ONE_MINUS_CONSTANT_ALPHA},
382 {"zero", BlendFunc::ZERO}
384 EffectPropertyMap<BlendFunc::BlendFuncMode> blendFuncModes(blendFuncModesInit);
386 struct BlendBuilder : public PassAttributeBuilder
388 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
389 const osgDB::ReaderWriter::Options* options)
391 if (!isAttributeActive(effect, prop))
393 // XXX Compatibility with early <blend> syntax; should go away
395 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
398 if (realProp->nChildren() == 0) {
399 pass->setMode(GL_BLEND, (realProp->getBoolValue()
401 : StateAttribute::OFF));
405 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
407 // XXX When dynamic parameters are supported, this code should
408 // create the blend function even if the mode is off.
409 if (pmode && !pmode->getValue<bool>()) {
410 pass->setMode(GL_BLEND, StateAttribute::OFF);
413 const SGPropertyNode* psource
414 = getEffectPropertyChild(effect, prop, "source");
415 const SGPropertyNode* pdestination
416 = getEffectPropertyChild(effect, prop, "destination");
417 const SGPropertyNode* psourceRGB
418 = getEffectPropertyChild(effect, prop, "source-rgb");
419 const SGPropertyNode* psourceAlpha
420 = getEffectPropertyChild(effect, prop, "source-alpha");
421 const SGPropertyNode* pdestRGB
422 = getEffectPropertyChild(effect, prop, "destination-rgb");
423 const SGPropertyNode* pdestAlpha
424 = getEffectPropertyChild(effect, prop, "destination-alpha");
425 BlendFunc::BlendFuncMode sourceMode = BlendFunc::ONE;
426 BlendFunc::BlendFuncMode destMode = BlendFunc::ZERO;
428 findAttr(blendFuncModes, psource, sourceMode);
430 findAttr(blendFuncModes, pdestination, destMode);
431 if (psource && pdestination
432 && !(psourceRGB || psourceAlpha || pdestRGB || pdestAlpha)
433 && sourceMode == BlendFunc::SRC_ALPHA
434 && destMode == BlendFunc::ONE_MINUS_SRC_ALPHA) {
435 pass->setAttributeAndModes(StateAttributeFactory::instance()
436 ->getStandardBlendFunc());
439 BlendFunc* blendFunc = new BlendFunc;
441 blendFunc->setSource(sourceMode);
443 blendFunc->setDestination(destMode);
445 BlendFunc::BlendFuncMode sourceRGBMode;
446 findAttr(blendFuncModes, psourceRGB, sourceRGBMode);
447 blendFunc->setSourceRGB(sourceRGBMode);
450 BlendFunc::BlendFuncMode destRGBMode;
451 findAttr(blendFuncModes, pdestRGB, destRGBMode);
452 blendFunc->setDestinationRGB(destRGBMode);
455 BlendFunc::BlendFuncMode sourceAlphaMode;
456 findAttr(blendFuncModes, psourceAlpha, sourceAlphaMode);
457 blendFunc->setSourceAlpha(sourceAlphaMode);
460 BlendFunc::BlendFuncMode destAlphaMode;
461 findAttr(blendFuncModes, pdestAlpha, destAlphaMode);
462 blendFunc->setDestinationAlpha(destAlphaMode);
464 pass->setAttributeAndModes(blendFunc);
468 InstallAttributeBuilder<BlendBuilder> installBlend("blend");
470 EffectNameValue<AlphaFunc::ComparisonFunction> alphaComparisonInit[] =
472 {"never", AlphaFunc::NEVER},
473 {"less", AlphaFunc::LESS},
474 {"equal", AlphaFunc::EQUAL},
475 {"lequal", AlphaFunc::LEQUAL},
476 {"greater", AlphaFunc::GREATER},
477 {"notequal", AlphaFunc::NOTEQUAL},
478 {"gequal", AlphaFunc::GEQUAL},
479 {"always", AlphaFunc::ALWAYS}
481 EffectPropertyMap<AlphaFunc::ComparisonFunction>
482 alphaComparison(alphaComparisonInit);
484 struct AlphaTestBuilder : public PassAttributeBuilder
486 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
487 const osgDB::ReaderWriter::Options* options)
489 if (!isAttributeActive(effect, prop))
491 // XXX Compatibility with early <alpha-test> syntax; should go away
493 const SGPropertyNode* realProp = getEffectPropertyNode(effect, prop);
496 if (realProp->nChildren() == 0) {
497 pass->setMode(GL_ALPHA_TEST, (realProp->getBoolValue()
499 : StateAttribute::OFF));
503 const SGPropertyNode* pmode = getEffectPropertyChild(effect, prop,
505 // XXX When dynamic parameters are supported, this code should
506 // create the blend function even if the mode is off.
507 if (pmode && !pmode->getValue<bool>()) {
508 pass->setMode(GL_ALPHA_TEST, StateAttribute::OFF);
511 const SGPropertyNode* pComp = getEffectPropertyChild(effect, prop,
513 const SGPropertyNode* pRef = getEffectPropertyChild(effect, prop,
515 AlphaFunc::ComparisonFunction func = AlphaFunc::ALWAYS;
516 float refValue = 1.0f;
518 findAttr(alphaComparison, pComp, func);
520 refValue = pRef->getValue<float>();
521 if (func == AlphaFunc::GREATER && osg::equivalent(refValue, 1.0f)) {
522 pass->setAttributeAndModes(StateAttributeFactory::instance()
523 ->getStandardAlphaFunc());
525 AlphaFunc* alphaFunc = new AlphaFunc;
526 alphaFunc->setFunction(func);
527 alphaFunc->setReferenceValue(refValue);
528 pass->setAttributeAndModes(alphaFunc);
533 InstallAttributeBuilder<AlphaTestBuilder> installAlphaTest("alpha-test");
535 InstallAttributeBuilder<TextureUnitBuilder> textureUnitBuilder("texture-unit");
537 typedef map<string, ref_ptr<Program> > ProgramMap;
538 ProgramMap programMap;
540 typedef map<string, ref_ptr<Shader> > ShaderMap;
543 void reload_shaders()
545 for(ShaderMap::iterator sitr = shaderMap.begin(); sitr != shaderMap.end(); ++sitr)
547 Shader *shader = sitr->second.get();
548 string fileName = osgDB::findDataFile(sitr->first);
549 if (!fileName.empty()) {
550 shader->loadShaderSourceFromFile(fileName);
555 struct ShaderProgramBuilder : PassAttributeBuilder
557 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
558 const osgDB::ReaderWriter::Options* options);
561 void ShaderProgramBuilder::buildAttribute(Effect* effect, Pass* pass,
562 const SGPropertyNode* prop,
563 const osgDB::ReaderWriter::Options*
566 if (!isAttributeActive(effect, prop))
568 PropertyList pVertShaders = prop->getChildren("vertex-shader");
569 PropertyList pFragShaders = prop->getChildren("fragment-shader");
571 for (PropertyList::iterator itr = pVertShaders.begin(),
572 e = pVertShaders.end();
576 programKey += (*itr)->getStringValue();
579 for (PropertyList::iterator itr = pFragShaders.begin(),
580 e = pFragShaders.end();
584 programKey += (*itr)->getStringValue();
587 Program* program = 0;
588 ProgramMap::iterator pitr = programMap.find(programKey);
589 if (pitr != programMap.end()) {
590 program = pitr->second.get();
592 program = new Program;
593 program->setName(programKey);
594 // Add vertex shaders, then fragment shaders
595 PropertyList& pvec = pVertShaders;
596 Shader::Type stype = Shader::VERTEX;
597 for (int i = 0; i < 2; ++i) {
598 for (PropertyList::iterator nameItr = pvec.begin(), e = pvec.end();
601 string shaderName = (*nameItr)->getStringValue();
602 ShaderMap::iterator sitr = shaderMap.find(shaderName);
603 if (sitr != shaderMap.end()) {
604 program->addShader(sitr->second.get());
606 string fileName = osgDB::findDataFile(shaderName, options);
607 if (!fileName.empty()) {
608 ref_ptr<Shader> shader = new Shader(stype);
609 if (shader->loadShaderSourceFromFile(fileName)) {
610 program->addShader(shader.get());
611 shaderMap.insert(make_pair(shaderName, shader));
617 stype = Shader::FRAGMENT;
619 programMap.insert(make_pair(programKey, program));
621 pass->setAttributeAndModes(program);
624 InstallAttributeBuilder<ShaderProgramBuilder> installShaderProgram("program");
626 EffectNameValue<Uniform::Type> uniformTypesInit[] =
628 {"float", Uniform::FLOAT},
629 {"float-vec3", Uniform::FLOAT_VEC3},
630 {"float-vec4", Uniform::FLOAT_VEC4},
631 {"sampler-1d", Uniform::SAMPLER_1D},
632 {"sampler-2d", Uniform::SAMPLER_2D},
633 {"sampler-3d", Uniform::SAMPLER_3D}
635 EffectPropertyMap<Uniform::Type> uniformTypes(uniformTypesInit);
637 struct UniformBuilder :public PassAttributeBuilder
639 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
640 const osgDB::ReaderWriter::Options* options)
642 if (!isAttributeActive(effect, prop))
644 const SGPropertyNode* nameProp = prop->getChild("name");
645 const SGPropertyNode* typeProp = prop->getChild("type");
646 const SGPropertyNode* valProp
647 = getEffectPropertyChild(effect, prop, "value");
649 Uniform::Type uniformType = Uniform::FLOAT;
651 name = nameProp->getStringValue();
653 SG_LOG(SG_INPUT, SG_ALERT, "No name for uniform property ");
657 SG_LOG(SG_INPUT, SG_ALERT, "No value for uniform property "
662 props::Type propType = valProp->getType();
666 break; // default float type;
668 uniformType = Uniform::FLOAT_VEC3;
671 uniformType = Uniform::FLOAT_VEC4;
674 SG_LOG(SG_INPUT, SG_ALERT, "Can't deduce type of uniform "
679 findAttr(uniformTypes, typeProp, uniformType);
681 ref_ptr<Uniform> uniform = new Uniform;
682 uniform->setName(name);
683 uniform->setType(uniformType);
684 switch (uniformType) {
686 uniform->set(valProp->getValue<float>());
688 case Uniform::FLOAT_VEC3:
689 uniform->set(toOsg(valProp->getValue<SGVec3d>()));
691 case Uniform::FLOAT_VEC4:
692 uniform->set(toOsg(valProp->getValue<SGVec4d>()));
694 case Uniform::SAMPLER_1D:
695 case Uniform::SAMPLER_2D:
696 case Uniform::SAMPLER_3D:
697 uniform->set(valProp->getValue<int>());
699 default: // avoid compiler warning
702 pass->addUniform(uniform.get());
706 InstallAttributeBuilder<UniformBuilder> installUniform("uniform");
708 // Not sure what to do with "name". At one point I wanted to use it to
709 // order the passes, but I do support render bin and stuff too...
711 struct NameBuilder : public PassAttributeBuilder
713 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
714 const osgDB::ReaderWriter::Options* options)
716 // name can't use <use>
717 string name = prop->getStringValue();
723 InstallAttributeBuilder<NameBuilder> installName("name");
725 EffectNameValue<PolygonMode::Mode> polygonModeModesInit[] =
727 {"fill", PolygonMode::FILL},
728 {"line", PolygonMode::LINE},
729 {"point", PolygonMode::POINT}
731 EffectPropertyMap<PolygonMode::Mode> polygonModeModes(polygonModeModesInit);
733 struct PolygonModeBuilder : public PassAttributeBuilder
735 void buildAttribute(Effect* effect, Pass* pass, const SGPropertyNode* prop,
736 const osgDB::ReaderWriter::Options* options)
738 if (!isAttributeActive(effect, prop))
740 const SGPropertyNode* frontProp
741 = getEffectPropertyChild(effect, prop, "front");
742 const SGPropertyNode* backProp
743 = getEffectPropertyChild(effect, prop, "back");
744 ref_ptr<PolygonMode> pmode = new PolygonMode;
745 PolygonMode::Mode frontMode = PolygonMode::FILL;
746 PolygonMode::Mode backMode = PolygonMode::FILL;
748 findAttr(polygonModeModes, frontProp, frontMode);
749 pmode->setMode(PolygonMode::FRONT, frontMode);
752 findAttr(polygonModeModes, backProp, backMode);
753 pmode->setMode(PolygonMode::BACK, backMode);
755 pass->setAttribute(pmode.get());
759 InstallAttributeBuilder<PolygonModeBuilder> installPolygonMode("polygon-mode");
760 void buildTechnique(Effect* effect, const SGPropertyNode* prop,
761 const osgDB::ReaderWriter::Options* options)
763 Technique* tniq = new Technique;
764 effect->techniques.push_back(tniq);
765 const SGPropertyNode* predProp = prop->getChild("predicate");
767 tniq->setAlwaysValid(true);
770 TechniquePredParser parser;
771 parser.setTechnique(tniq);
772 expression::BindingLayout& layout = parser.getBindingLayout();
773 /*int contextLoc = */layout.addBinding("__contextId", expression::INT);
774 SGExpressionb* validExp
775 = dynamic_cast<SGExpressionb*>(parser.read(predProp
778 tniq->setValidExpression(validExp, layout);
780 throw expression::ParseError("technique predicate is not a boolean expression");
782 catch (expression::ParseError& except)
784 SG_LOG(SG_INPUT, SG_ALERT,
785 "parsing technique predicate " << except.getMessage());
786 tniq->setAlwaysValid(false);
789 PropertyList passProps = prop->getChildren("pass");
790 for (PropertyList::iterator itr = passProps.begin(), e = passProps.end();
793 buildPass(effect, tniq, itr->ptr(), options);
797 // Specifically for .ac files...
798 bool makeParametersFromStateSet(SGPropertyNode* effectRoot, const StateSet* ss)
800 SGPropertyNode* paramRoot = makeChild(effectRoot, "parameters");
801 SGPropertyNode* matNode = paramRoot->getChild("material", 0, true);
802 Vec4f ambVal, difVal, specVal, emisVal;
803 float shininess = 0.0f;
804 const Material* mat = getStateAttribute<Material>(ss);
806 ambVal = mat->getAmbient(Material::FRONT_AND_BACK);
807 difVal = mat->getDiffuse(Material::FRONT_AND_BACK);
808 specVal = mat->getSpecular(Material::FRONT_AND_BACK);
809 emisVal = mat->getEmission(Material::FRONT_AND_BACK);
810 shininess = mat->getShininess(Material::FRONT_AND_BACK);
811 makeChild(matNode, "active")->setValue(true);
812 makeChild(matNode, "ambient")->setValue(toVec4d(toSG(ambVal)));
813 makeChild(matNode, "diffuse")->setValue(toVec4d(toSG(difVal)));
814 makeChild(matNode, "specular")->setValue(toVec4d(toSG(specVal)));
815 makeChild(matNode, "emissive")->setValue(toVec4d(toSG(emisVal)));
816 makeChild(matNode, "shininess")->setValue(shininess);
817 matNode->getChild("color-mode", 0, true)->setStringValue("diffuse");
819 makeChild(matNode, "active")->setValue(false);
821 const ShadeModel* sm = getStateAttribute<ShadeModel>(ss);
822 string shadeModelString("smooth");
824 ShadeModel::Mode smMode = sm->getMode();
825 if (smMode == ShadeModel::FLAT)
826 shadeModelString = "flat";
828 makeChild(paramRoot, "shade-model")->setStringValue(shadeModelString);
829 string cullFaceString("off");
830 const CullFace* cullFace = getStateAttribute<CullFace>(ss);
832 switch (cullFace->getMode()) {
833 case CullFace::FRONT:
834 cullFaceString = "front";
837 cullFaceString = "back";
839 case CullFace::FRONT_AND_BACK:
840 cullFaceString = "front-back";
846 makeChild(paramRoot, "cull-face")->setStringValue(cullFaceString);
847 const BlendFunc* blendFunc = getStateAttribute<BlendFunc>(ss);
848 SGPropertyNode* blendNode = makeChild(paramRoot, "blend");
850 string sourceMode = findName(blendFuncModes, blendFunc->getSource());
851 string destMode = findName(blendFuncModes, blendFunc->getDestination());
852 makeChild(blendNode, "active")->setValue(true);
853 makeChild(blendNode, "source")->setStringValue(sourceMode);
854 makeChild(blendNode, "destination")->setStringValue(destMode);
855 makeChild(blendNode, "mode")->setValue(true);
857 makeChild(blendNode, "active")->setValue(false);
859 makeTextureParameters(paramRoot, ss);
863 // Walk the techniques property tree, building techniques and
865 bool Effect::realizeTechniques(const osgDB::ReaderWriter::Options* options)
867 PropertyList tniqList = root->getChildren("technique");
868 for (PropertyList::iterator itr = tniqList.begin(), e = tniqList.end();
871 buildTechnique(this, *itr, options);
875 bool Effect_writeLocalData(const Object& obj, osgDB::Output& fw)
877 const Effect& effect = static_cast<const Effect&>(obj);
879 fw.indent() << "techniques " << effect.techniques.size() << "\n";
880 BOOST_FOREACH(const ref_ptr<Technique>& technique, effect.techniques) {
881 fw.writeObject(*technique);
888 osgDB::RegisterDotOsgWrapperProxy effectProxy
892 "Object simgear::Effect",
894 &Effect_writeLocalData
898 // Property expressions for technique predicates
899 class PropertyExpression : public SGExpression<bool>
902 PropertyExpression(SGPropertyNode* pnode) : _pnode(pnode) {}
904 void eval(bool& value, const expression::Binding*) const
906 value = _pnode->getValue<bool>();
909 SGPropertyNode_ptr _pnode;
912 class EffectPropertyListener : public SGPropertyChangeListener
915 EffectPropertyListener(Technique* tniq) : _tniq(tniq) {}
917 void valueChanged(SGPropertyNode* node)
919 _tniq->refreshValidity();
922 osg::ref_ptr<Technique> _tniq;
925 Expression* propertyExpressionParser(const SGPropertyNode* exp,
926 expression::Parser* parser)
928 SGPropertyNode_ptr pnode = getPropertyRoot()->getNode(exp->getStringValue(),
930 PropertyExpression* pexp = new PropertyExpression(pnode);
931 TechniquePredParser* predParser
932 = dynamic_cast<TechniquePredParser*>(parser);
934 pnode->addChangeListener(new EffectPropertyListener(predParser
939 expression::ExpParserRegistrar propertyRegistrar("property",
940 propertyExpressionParser);