]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/TextureBuilder.cxx
Work around apparent OSG 3.2.0 normal binding bug.
[simgear.git] / simgear / scene / material / TextureBuilder.cxx
1 // Copyright (C) 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 "TextureBuilder.hxx"
22 #include "mipmap.hxx"
23
24 #include "Pass.hxx"
25
26 #include <osg/TexEnv>
27 #include <osg/TexEnvCombine>
28 #include <osg/TexGen>
29 #include <osg/Texture1D>
30 #include <osg/Texture2D>
31 #include <osg/Texture3D>
32 #include <osg/TextureRectangle>
33 #include <osg/TextureCubeMap>
34 #include <osgDB/FileUtils>
35 #include <osgDB/ReadFile>
36
37 #include <boost/lexical_cast.hpp>
38 #include <boost/tuple/tuple.hpp>
39 #include <boost/tuple/tuple_comparison.hpp>
40
41 #include <simgear/scene/util/OsgMath.hxx>
42 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
43 #include <simgear/scene/util/SGSceneFeatures.hxx>
44 #include <simgear/scene/util/StateAttributeFactory.hxx>
45 #include <simgear/structure/OSGUtils.hxx>
46 #include <simgear/props/vectorPropTemplates.hxx>
47
48 namespace simgear
49 {
50 using namespace std;
51 using namespace osg;
52
53 using namespace effect;
54
55 TexEnvCombine* buildTexEnvCombine(Effect* effect,
56                                   const SGPropertyNode* envProp,
57                                   const SGReaderWriterOptions* options);
58 TexGen* buildTexGen(Effect* Effect, const SGPropertyNode* tgenProp);
59
60 // Hack to force inclusion of TextureBuilder.cxx in library
61 osg::Texture* TextureBuilder::buildFromType(Effect* effect, Pass* pass, const string& type,
62                                             const SGPropertyNode*props,
63                                             const SGReaderWriterOptions*
64                                             options)
65 {
66     return EffectBuilder<Texture>::buildFromType(effect, pass, type, props, options);
67 }
68
69 typedef boost::tuple<string, Texture::FilterMode, Texture::FilterMode,
70                      Texture::WrapMode, Texture::WrapMode, Texture::WrapMode,
71                      string, MipMapTuple> TexTuple;
72
73 EffectNameValue<TexEnv::Mode> texEnvModesInit[] =
74 {
75     {"add", TexEnv::ADD},
76     {"blend", TexEnv::BLEND},
77     {"decal", TexEnv::DECAL},
78     {"modulate", TexEnv::MODULATE},
79     {"replace", TexEnv::REPLACE}
80 };
81 EffectPropertyMap<TexEnv::Mode> texEnvModes(texEnvModesInit);
82
83 TexEnv* buildTexEnv(Effect* effect, const SGPropertyNode* prop)
84 {
85     const SGPropertyNode* modeProp = getEffectPropertyChild(effect, prop,
86                                                             "mode");
87     const SGPropertyNode* colorProp = getEffectPropertyChild(effect, prop,
88                                                              "color");
89     if (!modeProp)
90         return 0;
91     TexEnv::Mode mode = TexEnv::MODULATE;
92     findAttr(texEnvModes, modeProp, mode);
93     if (mode == TexEnv::MODULATE) {
94         return StateAttributeFactory::instance()->getStandardTexEnv();
95     }
96     TexEnv* env = new TexEnv(mode);
97     if (colorProp)
98         env->setColor(toOsg(colorProp->getValue<SGVec4d>()));
99     return env;
100 }
101
102
103 void TextureUnitBuilder::buildAttribute(Effect* effect, Pass* pass,
104                                         const SGPropertyNode* prop,
105                                         const SGReaderWriterOptions* options)
106 {
107     if (!isAttributeActive(effect, prop))
108         return;
109     // Decode the texture unit
110     int unit = 0;
111     const SGPropertyNode* pUnit = prop->getChild("unit");
112     if (pUnit) {
113         unit = pUnit->getValue<int>();
114     } else {
115         const SGPropertyNode* pName = prop->getChild("name");
116         if (pName)
117             try {
118                 unit = boost::lexical_cast<int>(pName->getStringValue());
119             } catch (boost::bad_lexical_cast& lex) {
120                 SG_LOG(SG_INPUT, SG_ALERT, "can't decode name as texture unit "
121                        << lex.what());
122             }
123     }
124     const SGPropertyNode* pType = getEffectPropertyChild(effect, prop, "type");
125     string type;
126     if (!pType)
127         type = "2d";
128     else
129         type = pType->getStringValue();
130     Texture* texture = 0;
131     try {
132         texture = TextureBuilder::buildFromType(effect, pass, type, prop,
133                                                 options);
134     }
135     catch (BuilderException& e) {
136         SG_LOG(SG_INPUT, SG_DEBUG, e.getFormattedMessage() << ", "
137             << "maybe the reader did not set the filename attribute, "
138             << "using white for type '" << type << "' on '" << pass->getName() << "', in " << prop->getPath() );
139         texture = StateAttributeFactory::instance()->getWhiteTexture();
140     }
141     pass->setTextureAttributeAndModes(unit, texture);
142     const SGPropertyNode* envProp = prop->getChild("environment");
143     if (envProp) {
144         TexEnv* env = buildTexEnv(effect, envProp);
145         if (env)
146             pass->setTextureAttributeAndModes(unit, env);
147     }
148     const SGPropertyNode* combineProp = prop->getChild("texenv-combine");
149     TexEnvCombine* combiner = 0;
150     if (combineProp && ((combiner = buildTexEnvCombine(effect, combineProp,
151                                                        options))))
152         pass->setTextureAttributeAndModes(unit, combiner);
153     const SGPropertyNode* tgenProp = prop->getChild("texgen");
154     TexGen* tgen = 0;
155     if (tgenProp && (tgen = buildTexGen(effect, tgenProp)))
156         pass->setTextureAttributeAndModes(unit, tgen);
157 }
158
159 // InstallAttributeBuilder call is in Effect.cxx to force this file to
160 // be linked in.
161
162 namespace
163 {
164 EffectNameValue<Texture::FilterMode> filterModesInit[] =
165 {
166     { "linear", Texture::LINEAR },
167     { "linear-mipmap-linear", Texture::LINEAR_MIPMAP_LINEAR},
168     { "linear-mipmap-nearest", Texture::LINEAR_MIPMAP_NEAREST},
169     { "nearest", Texture::NEAREST},
170     { "nearest-mipmap-linear", Texture::NEAREST_MIPMAP_LINEAR},
171     { "nearest-mipmap-nearest", Texture::NEAREST_MIPMAP_NEAREST}
172 };
173 EffectPropertyMap<Texture::FilterMode> filterModes(filterModesInit);
174
175 EffectNameValue<Texture::WrapMode> wrapModesInit[] =
176 {
177     {"clamp", Texture::CLAMP},
178     {"clamp-to-border", Texture::CLAMP_TO_BORDER},
179     {"clamp-to-edge", Texture::CLAMP_TO_EDGE},
180     {"mirror", Texture::MIRROR},
181     {"repeat", Texture::REPEAT}
182 };
183 EffectPropertyMap<Texture::WrapMode> wrapModes(wrapModesInit);
184
185 TexTuple makeTexTuple(Effect* effect, const SGPropertyNode* props,
186                       const SGReaderWriterOptions* options,
187                       const string& texType)
188 {
189     Texture::FilterMode minFilter = Texture::LINEAR_MIPMAP_LINEAR;
190     const SGPropertyNode* ep = 0;
191     if ((ep = getEffectPropertyChild(effect, props, "filter")))
192         findAttr(filterModes, ep, minFilter);
193     Texture::FilterMode magFilter = Texture::LINEAR;
194     if ((ep = getEffectPropertyChild(effect, props, "mag-filter")))
195         findAttr(filterModes, ep, magFilter);
196     const SGPropertyNode* pWrapS
197         = getEffectPropertyChild(effect, props, "wrap-s");
198     Texture::WrapMode sWrap = Texture::CLAMP;
199     if (pWrapS)
200         findAttr(wrapModes, pWrapS, sWrap);
201     const SGPropertyNode* pWrapT
202         = getEffectPropertyChild(effect, props, "wrap-t");
203     Texture::WrapMode tWrap = Texture::CLAMP;
204     if (pWrapT)
205         findAttr(wrapModes, pWrapT, tWrap);
206     const SGPropertyNode* pWrapR
207         = getEffectPropertyChild(effect, props, "wrap-r");
208     Texture::WrapMode rWrap = Texture::CLAMP;
209     if (pWrapR)
210         findAttr(wrapModes, pWrapR, rWrap);
211     const SGPropertyNode* pImage
212         = getEffectPropertyChild(effect, props, "image");
213     string imageName;
214     string absFileName;
215     if (pImage)
216     {
217         imageName = pImage->getStringValue();
218         absFileName = SGModelLib::findDataFile(imageName, options);
219         if (absFileName.empty())
220         {
221             SG_LOG(SG_INPUT, SG_ALERT, "Texture file not found: '"
222                    << imageName << "'");
223         }
224     }
225
226     const SGPropertyNode* pMipmapControl
227         = getEffectPropertyChild(effect, props, "mipmap-control");
228     MipMapTuple mipmapFunctions( AUTOMATIC, AUTOMATIC, AUTOMATIC, AUTOMATIC ); 
229     if ( pMipmapControl )
230         mipmapFunctions = makeMipMapTuple(effect, pMipmapControl, options);
231
232     return TexTuple(absFileName, minFilter, magFilter, sWrap, tWrap, rWrap,
233                     texType, mipmapFunctions);
234 }
235
236 bool setAttrs(const TexTuple& attrs, Texture* tex,
237               const SGReaderWriterOptions* options)
238 {
239     const string& imageName = attrs.get<0>();
240     if (imageName.empty()) 
241         return false;
242         
243     osgDB::ReaderWriter::ReadResult result;
244     result = osgDB::readImageFile(imageName, options);
245     osg::ref_ptr<osg::Image> image;
246     if (result.success())
247         image = result.getImage();
248     if (image.valid())
249     {
250         image = computeMipmap( image.get(), attrs.get<7>() );
251         tex->setImage(GL_FRONT_AND_BACK, image.get());
252         int s = image->s();
253         int t = image->t();
254         if (s <= t && 32 <= s) {
255             SGSceneFeatures::instance()->setTextureCompression(tex);
256         } else if (t < s && 32 <= t) {
257             SGSceneFeatures::instance()->setTextureCompression(tex);
258         }
259         tex->setMaxAnisotropy(SGSceneFeatures::instance()
260                               ->getTextureFilter());
261     } else {
262         SG_LOG(SG_INPUT, SG_ALERT, "failed to load effect texture file "
263                << imageName);
264         return false;
265     }
266
267     // texture->setDataVariance(osg::Object::STATIC);
268     tex->setFilter(Texture::MIN_FILTER, attrs.get<1>());
269     tex->setFilter(Texture::MAG_FILTER, attrs.get<2>());
270     tex->setWrap(Texture::WRAP_S, attrs.get<3>());
271     tex->setWrap(Texture::WRAP_T, attrs.get<4>());
272     tex->setWrap(Texture::WRAP_R, attrs.get<5>());
273     return true;
274 }
275
276 } // of anonymous namespace
277
278 template<typename T>
279 class TexBuilder : public TextureBuilder
280 {
281 public:
282     TexBuilder(const string& texType) : _type(texType) {}
283     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
284                    const SGReaderWriterOptions* options);
285 protected:
286     typedef map<TexTuple, observer_ptr<T> > TexMap;
287     TexMap texMap;
288     const string _type;
289 };
290
291 template<typename T>
292 Texture* TexBuilder<T>::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
293                               const SGReaderWriterOptions* options)
294 {
295     TexTuple attrs = makeTexTuple(effect, props, options, _type);
296     typename TexMap::iterator itr = texMap.find(attrs);
297
298     ref_ptr<T> tex;
299     if ((itr != texMap.end())&&
300         (itr->second.lock(tex)))
301     {
302         return tex.release();
303     }
304
305     tex = new T;
306     if (!setAttrs(attrs, tex, options))
307         return NULL;
308     
309     if (itr == texMap.end())
310         texMap.insert(make_pair(attrs, tex));
311     else
312         itr->second = tex; // update existing, but empty observer
313     return tex.release();
314 }
315
316
317 namespace
318 {
319 TextureBuilder::Registrar install1D("1d", new TexBuilder<Texture1D>("1d"));
320 TextureBuilder::Registrar install2D("2d", new TexBuilder<Texture2D>("2d"));
321 TextureBuilder::Registrar install3D("3d", new TexBuilder<Texture3D>("3d"));
322 }
323
324 class WhiteTextureBuilder : public TextureBuilder
325 {
326 public:
327     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
328                    const SGReaderWriterOptions* options);
329 };
330
331 Texture* WhiteTextureBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode*,
332                                     const SGReaderWriterOptions* options)
333 {
334     return StateAttributeFactory::instance()->getWhiteTexture();
335 }
336
337 namespace
338 {
339 TextureBuilder::Registrar installWhite("white", new WhiteTextureBuilder);
340 }
341
342 class TransparentTextureBuilder : public TextureBuilder
343 {
344 public:
345     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
346                    const SGReaderWriterOptions* options);
347 };
348
349 Texture* TransparentTextureBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode*,
350                                     const SGReaderWriterOptions* options)
351 {
352     return StateAttributeFactory::instance()->getTransparentTexture();
353 }
354
355 namespace
356 {
357 TextureBuilder::Registrar installTransparent("transparent",
358                                              new TransparentTextureBuilder);
359 }
360
361 class NoiseBuilder : public TextureBuilder
362 {
363 public:
364     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
365                    const SGReaderWriterOptions* options);
366 protected:
367     typedef map<int, ref_ptr<Texture3D> > NoiseMap;
368     NoiseMap _noises;
369 };
370
371 Texture* NoiseBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
372                              const SGReaderWriterOptions* options)
373 {
374     int texSize = 64;
375     const SGPropertyNode* sizeProp = getEffectPropertyChild(effect, props,
376                                                             "size");
377     if (sizeProp)
378         texSize = sizeProp->getValue<int>();
379
380     return StateAttributeFactory::instance()->getNoiseTexture(texSize);
381 }
382
383 namespace
384 {
385 TextureBuilder::Registrar installNoise("noise", new NoiseBuilder);
386 }
387
388
389
390 // Image names for all sides
391 typedef boost::tuple<string, string, string, string, string, string> CubeMapTuple;
392
393 CubeMapTuple makeCubeMapTuple(Effect* effect, const SGPropertyNode* props)
394 {
395     const SGPropertyNode* ep = 0;
396
397     string positive_x;
398     if ((ep = getEffectPropertyChild(effect, props, "positive-x")))
399         positive_x = ep->getStringValue();
400     string negative_x;
401     if ((ep = getEffectPropertyChild(effect, props, "negative-x")))
402         negative_x = ep->getStringValue();
403     string positive_y;
404     if ((ep = getEffectPropertyChild(effect, props, "positive-y")))
405         positive_y = ep->getStringValue();
406     string negative_y;
407     if ((ep = getEffectPropertyChild(effect, props, "negative-y")))
408         negative_y = ep->getStringValue();
409     string positive_z;
410     if ((ep = getEffectPropertyChild(effect, props, "positive-z")))
411         positive_z = ep->getStringValue();
412     string negative_z;
413     if ((ep = getEffectPropertyChild(effect, props, "negative-z")))
414         negative_z = ep->getStringValue();
415     return CubeMapTuple(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
416 }
417
418
419 class CubeMapBuilder : public TextureBuilder
420 {
421 public:
422     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
423                    const SGReaderWriterOptions* options);
424 protected:
425     typedef map<CubeMapTuple, ref_ptr<TextureCubeMap> > CubeMap;
426     typedef map<string, ref_ptr<TextureCubeMap> > CrossCubeMap;
427     CubeMap _cubemaps;
428     CrossCubeMap _crossmaps;
429 };
430
431 // I use this until osg::CopyImage is fixed
432 // This one assumes images are the same format and sizes are correct
433 void copySubImage(const osg::Image* srcImage, int src_s, int src_t, int width, int height, 
434                  osg::Image* destImage, int dest_s, int dest_t)
435 {
436     for(int row = 0; row<height; ++row)
437     {
438         const unsigned char* srcData = srcImage->data(src_s, src_t+row, 0);
439         unsigned char* destData = destImage->data(dest_s, dest_t+row, 0);
440         memcpy(destData, srcData, (width*destImage->getPixelSizeInBits())/8);
441     }
442 }
443
444
445 Texture* CubeMapBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* props,
446                                const SGReaderWriterOptions* options)
447 {
448     // First check that there is a <images> tag
449     const SGPropertyNode* texturesProp = getEffectPropertyChild(effect, props, "images");
450     const SGPropertyNode* crossProp = getEffectPropertyChild(effect, props, "image");
451     if (!texturesProp && !crossProp) {
452         throw BuilderException("no images defined for cube map");
453         return NULL; // This is redundant
454     }
455
456     // Using 6 separate images
457     if(texturesProp) {
458
459         SG_LOG(SG_INPUT, SG_DEBUG, "try 6 images ");
460
461         CubeMapTuple _tuple = makeCubeMapTuple(effect, texturesProp);
462
463         CubeMap::iterator itr = _cubemaps.find(_tuple);
464         if (itr != _cubemaps.end())
465             return itr->second.get();
466
467         TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
468
469         // TODO: Read these from effect file? Maybe these are sane for all cuebmaps?
470         cubeTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
471         cubeTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture::LINEAR);
472         cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
473         cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
474         cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
475
476         osgDB::ReaderWriter::ReadResult result;
477         result = osgDB::readImageFile(_tuple.get<0>(), options);
478         if(result.success()) {
479             osg::Image* image = result.getImage();
480             cubeTexture->setImage(TextureCubeMap::POSITIVE_X, image);
481         }
482         result = osgDB::readImageFile(_tuple.get<1>(), options);
483         if(result.success()) {
484             osg::Image* image = result.getImage();
485             cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, image);
486         }
487         result = osgDB::readImageFile(_tuple.get<2>(), options);
488         if(result.success()) {
489             osg::Image* image = result.getImage();
490             cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, image);
491         }
492         result = osgDB::readImageFile(_tuple.get<3>(), options);
493         if(result.success()) {
494             osg::Image* image = result.getImage();
495             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, image);
496         }
497         result = osgDB::readImageFile(_tuple.get<4>(), options);
498         if(result.success()) {
499             osg::Image* image = result.getImage();
500             cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, image);
501         }
502         result = osgDB::readImageFile(_tuple.get<5>(), options);
503         if(result.success()) {
504             osg::Image* image = result.getImage();
505             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, image);
506         }
507
508         _cubemaps[_tuple] = cubeTexture;
509
510         return cubeTexture;
511     }
512
513
514     // Using 1 cross image
515     else if(crossProp) {
516         SG_LOG(SG_INPUT, SG_DEBUG, "try cross map ");
517
518         std::string texname = crossProp->getStringValue();
519
520         // Try to find existing cube map
521         CrossCubeMap::iterator itr = _crossmaps.find(texname);
522         if (itr != _crossmaps.end())
523             return itr->second.get();
524
525         osgDB::ReaderWriter::ReadResult result;
526         result = osgDB::readImageFile(texname, options);
527         if(result.success()) {
528             osg::Image* image = result.getImage();
529             image->flipVertical();   // Seems like the image coordinates are somewhat funny, flip to get better ones
530
531             //cubeTexture->setResizeNonPowerOfTwoHint(false);
532
533             // Size of a single image, 4 rows and 3 columns
534             int width = image->s() / 3;
535             int height = image->t() / 4;
536             int depth = image->r();
537
538             TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
539
540             // Copy the 6 sub-images and push them
541             for(int n=0; n<6; n++) {
542
543                 SG_LOG(SG_INPUT, SG_DEBUG, "Copying the " << n << "th sub-images and pushing it" );
544
545                 osg::ref_ptr<osg::Image> subimg = new osg::Image();
546                 subimg->allocateImage(width, height, depth, image->getPixelFormat(), image->getDataType());  // Copy attributes
547
548                 // Choose correct image
549                 switch(n) {
550                 case 0:  // Front
551                     copySubImage(image, width, 0, width, height, subimg.get(), 0, 0);
552                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, subimg.get());
553                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
554                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
555                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
556                     break;
557                 case 1:  // Left
558                     copySubImage(image, 0, height, width, height, subimg.get(), 0, 0);
559                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, subimg.get());
560                     cubeTexture->setWrap(osg::Texture2D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
561                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
562                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
563                     break;
564                 case 2:  // Top
565                     copySubImage(image, width, height, width, height, subimg.get(), 0, 0);
566                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, subimg.get());
567                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
568                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
569                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
570                     break;
571                 case 3:  // Right
572                     copySubImage(image, width*2, height, width, height, subimg.get(), 0, 0);
573                     cubeTexture->setImage(TextureCubeMap::POSITIVE_X, subimg.get());
574                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
575                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
576                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
577                     break;
578                 case 4:  // Back
579                     copySubImage(image, width, height*2, width, height, subimg.get(), 0, 0);
580                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, subimg.get());
581                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
582                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
583                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
584                     break;
585                 case 5:  // Bottom
586                     copySubImage(image, width, height*3, width, height, subimg.get(), 0, 0);
587                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, subimg.get());
588                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
589                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
590                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
591                     break;
592                 };
593
594             }
595
596             _crossmaps[texname] = cubeTexture;
597
598             return cubeTexture;
599
600         } else {
601             throw BuilderException("Could not load cube cross");
602         }
603     }
604
605     return NULL;
606 }
607
608 namespace {
609 TextureBuilder::Registrar installCubeMap("cubemap", new CubeMapBuilder);
610 }
611
612 EffectNameValue<TexEnvCombine::CombineParam> combineParamInit[] =
613 {
614     {"replace", TexEnvCombine::REPLACE},
615     {"modulate", TexEnvCombine::MODULATE},
616     {"add", TexEnvCombine::ADD},
617     {"add-signed", TexEnvCombine::ADD_SIGNED},
618     {"interpolate", TexEnvCombine::INTERPOLATE},
619     {"subtract", TexEnvCombine::SUBTRACT},
620     {"dot3-rgb", TexEnvCombine::DOT3_RGB},
621     {"dot3-rgba", TexEnvCombine::DOT3_RGBA}
622 };
623
624 EffectPropertyMap<TexEnvCombine::CombineParam> combineParams(combineParamInit);
625
626 EffectNameValue<TexEnvCombine::SourceParam> sourceParamInit[] =
627 {
628     {"constant", TexEnvCombine::CONSTANT},
629     {"primary_color", TexEnvCombine::PRIMARY_COLOR},
630     {"previous", TexEnvCombine::PREVIOUS},
631     {"texture", TexEnvCombine::TEXTURE},
632     {"texture0", TexEnvCombine::TEXTURE0},
633     {"texture1", TexEnvCombine::TEXTURE1},
634     {"texture2", TexEnvCombine::TEXTURE2},
635     {"texture3", TexEnvCombine::TEXTURE3},
636     {"texture4", TexEnvCombine::TEXTURE4},
637     {"texture5", TexEnvCombine::TEXTURE5},
638     {"texture6", TexEnvCombine::TEXTURE6},
639     {"texture7", TexEnvCombine::TEXTURE7}
640 };
641
642 EffectPropertyMap<TexEnvCombine::SourceParam> sourceParams(sourceParamInit);
643
644 EffectNameValue<TexEnvCombine::OperandParam> opParamInit[] =
645 {
646     {"src-color", TexEnvCombine::SRC_COLOR},
647     {"one-minus-src-color", TexEnvCombine::ONE_MINUS_SRC_COLOR},
648     {"src-alpha", TexEnvCombine::SRC_ALPHA},
649     {"one-minus-src-alpha", TexEnvCombine::ONE_MINUS_SRC_ALPHA}
650 };
651
652 EffectPropertyMap<TexEnvCombine::OperandParam> operandParams(opParamInit);
653
654 TexEnvCombine* buildTexEnvCombine(Effect* effect, const SGPropertyNode* envProp,
655                                   const SGReaderWriterOptions* options)
656 {
657     if (!isAttributeActive(effect, envProp))
658         return 0;
659     TexEnvCombine* result = new TexEnvCombine;
660     const SGPropertyNode* p = 0;
661     if ((p = getEffectPropertyChild(effect, envProp, "combine-rgb"))) {
662         TexEnvCombine::CombineParam crgb = TexEnvCombine::MODULATE;
663         findAttr(combineParams, p, crgb);
664         result->setCombine_RGB(crgb);
665     }
666     if ((p = getEffectPropertyChild(effect, envProp, "combine-alpha"))) {
667         TexEnvCombine::CombineParam calpha = TexEnvCombine::MODULATE;
668         findAttr(combineParams, p, calpha);
669         result->setCombine_Alpha(calpha);
670     }
671     if ((p = getEffectPropertyChild(effect, envProp, "source0-rgb"))) {
672         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
673         findAttr(sourceParams, p, source);
674         result->setSource0_RGB(source);
675     }
676     if ((p = getEffectPropertyChild(effect, envProp, "source1-rgb"))) {
677         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
678         findAttr(sourceParams, p, source);
679         result->setSource1_RGB(source);
680     }
681     if ((p = getEffectPropertyChild(effect, envProp, "source2-rgb"))) {
682         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
683         findAttr(sourceParams, p, source);
684         result->setSource2_RGB(source);
685     }
686     if ((p = getEffectPropertyChild(effect, envProp, "source0-alpha"))) {
687         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
688         findAttr(sourceParams, p, source);
689         result->setSource0_Alpha(source);
690     }
691     if ((p = getEffectPropertyChild(effect, envProp, "source1-alpha"))) {
692         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
693         findAttr(sourceParams, p, source);
694         result->setSource1_Alpha(source);
695     }
696     if ((p = getEffectPropertyChild(effect, envProp, "source2-alpha"))) {
697         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
698         findAttr(sourceParams, p, source);
699         result->setSource2_Alpha(source);
700     }
701     if ((p = getEffectPropertyChild(effect, envProp, "operand0-rgb"))) {
702         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
703         findAttr(operandParams, p, op);
704         result->setOperand0_RGB(op);
705     }
706     if ((p = getEffectPropertyChild(effect, envProp, "operand1-rgb"))) {
707         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
708         findAttr(operandParams, p, op);
709         result->setOperand1_RGB(op);
710     }
711     if ((p = getEffectPropertyChild(effect, envProp, "operand2-rgb"))) {
712         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
713         findAttr(operandParams, p, op);
714         result->setOperand2_RGB(op);
715     }
716     if ((p = getEffectPropertyChild(effect, envProp, "operand0-alpha"))) {
717         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
718         findAttr(operandParams, p, op);
719         result->setOperand0_Alpha(op);
720     }
721     if ((p = getEffectPropertyChild(effect, envProp, "operand1-alpha"))) {
722         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
723         findAttr(operandParams, p, op);
724         result->setOperand1_Alpha(op);
725     }
726     if ((p = getEffectPropertyChild(effect, envProp, "operand2-alpha"))) {
727         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
728         findAttr(operandParams, p, op);
729         result->setOperand2_Alpha(op);
730     }
731     if ((p = getEffectPropertyChild(effect, envProp, "scale-rgb"))) {
732         result->setScale_RGB(p->getValue<float>());
733     }
734     if ((p = getEffectPropertyChild(effect, envProp, "scale-alpha"))) {
735         result->setScale_Alpha(p->getValue<float>());
736     }
737 #if 0
738     if ((p = getEffectPropertyChild(effect, envProp, "constant-color"))) {
739         SGVec4d color = p->getValue<SGVec4d>();
740         result->setConstantColor(toOsg(color));
741     } else if ((p = getEffectPropertyChild(effect, envProp,
742                                            "light-direction"))) {
743         SGVec3d direction = p->getValue<SGVec3d>();
744         result->setConstantColorAsLightDirection(toOsg(direction));
745     }
746 #endif
747     const SGPropertyNode* colorNode = envProp->getChild("constant-color");
748     if (colorNode)
749         initFromParameters(effect, colorNode, result,
750                            &TexEnvCombine::setConstantColor, colorFields,
751                            options);
752     return result;
753 }
754
755 EffectNameValue<TexGen::Mode> tgenModeInit[] =
756 {
757     { "object-linear", TexGen::OBJECT_LINEAR},
758     { "eye-linear", TexGen::EYE_LINEAR},
759     { "sphere-map", TexGen::SPHERE_MAP},
760     { "normal-map", TexGen::NORMAL_MAP},
761     { "reflection-map", TexGen::REFLECTION_MAP}
762 };
763
764 EffectPropertyMap<TexGen::Mode> tgenModes(tgenModeInit);
765
766 EffectNameValue<TexGen::Coord> tgenCoordInit[] =
767 {
768     {"s", TexGen::S},
769     {"t", TexGen::T},
770     {"r", TexGen::R},
771     {"q", TexGen::Q}
772 };
773
774 EffectPropertyMap<TexGen::Coord> tgenCoords(tgenCoordInit);
775
776 TexGen* buildTexGen(Effect* effect, const SGPropertyNode* tgenProp)
777 {
778     if (!isAttributeActive(effect, tgenProp))
779         return 0;
780     TexGen* result = new TexGen;
781     TexGen::Mode mode = TexGen::OBJECT_LINEAR;
782     findAttr(tgenModes, getEffectPropertyChild(effect, tgenProp, "mode"), mode);
783     result->setMode(mode);
784     const SGPropertyNode* planesNode = tgenProp->getChild("planes");
785     if (planesNode) {
786         for (int i = 0; i < planesNode->nChildren(); ++i) {
787             const SGPropertyNode* planeNode = planesNode->getChild(i);
788             TexGen::Coord coord;
789             findAttr(tgenCoords, planeNode->getName(), coord);
790             const SGPropertyNode* realNode
791                 = getEffectPropertyNode(effect, planeNode);
792             SGVec4d plane = realNode->getValue<SGVec4d>();
793             result->setPlane(coord, toOsg(plane));
794         }
795     }
796     return result;
797 }
798
799 bool makeTextureParameters(SGPropertyNode* paramRoot, const StateSet* ss)
800 {
801     SGPropertyNode* texUnit = makeChild(paramRoot, "texture");
802     const Texture* tex = getStateAttribute<Texture>(0, ss);
803     const Texture2D* texture = dynamic_cast<const Texture2D*>(tex);
804     makeChild(texUnit, "unit")->setValue(0);
805     if (!tex) {
806         // The default shader-based technique ignores active
807         makeChild(texUnit, "active")->setValue(false);
808         return false;
809     }
810     const Image* image = texture->getImage();
811     string imageName;
812     if (image) {
813         imageName = image->getFileName();
814     } else {
815         makeChild(texUnit, "active")->setValue(false);
816         makeChild(texUnit, "type")->setValue("white");
817         return false;
818     }
819     makeChild(texUnit, "active")->setValue(true);
820     makeChild(texUnit, "type")->setValue("2d");
821     string filter = findName(filterModes,
822                              texture->getFilter(Texture::MIN_FILTER));
823     string magFilter = findName(filterModes,
824                              texture->getFilter(Texture::MAG_FILTER));
825     string wrapS = findName(wrapModes, texture->getWrap(Texture::WRAP_S));
826     string wrapT = findName(wrapModes, texture->getWrap(Texture::WRAP_T));
827     string wrapR = findName(wrapModes, texture->getWrap(Texture::WRAP_R));
828     makeChild(texUnit, "image")->setStringValue(imageName);
829     makeChild(texUnit, "filter")->setStringValue(filter);
830     makeChild(texUnit, "mag-filter")->setStringValue(magFilter);
831     makeChild(texUnit, "wrap-s")->setStringValue(wrapS);
832     makeChild(texUnit, "wrap-t")->setStringValue(wrapT);
833     makeChild(texUnit, "wrap-r")->setStringValue(wrapR);
834     return true;
835 }
836
837 class GBufferBuilder : public TextureBuilder
838 {
839 public:
840     GBufferBuilder() {}
841     Texture* build(Effect* effect, Pass* pass, const SGPropertyNode*,
842                    const SGReaderWriterOptions* options);
843 private:
844     string buffer;
845 };
846
847 class BufferNameChangeListener : public SGPropertyChangeListener, public InitializeWhenAdded,
848       public Effect::Updater {
849 public:
850     BufferNameChangeListener(Pass* p, int u, const std::string& pn) : pass(p), unit(u)
851     {
852         propName = new std::string(pn);
853     }
854     ~BufferNameChangeListener()
855     {
856         delete propName;
857         propName = 0;
858     }
859     void valueChanged(SGPropertyNode* node)
860     {
861         const char* buffer = node->getStringValue();
862         pass->setBufferUnit(unit, buffer);
863     }
864     void initOnAddImpl(Effect* effect, SGPropertyNode* propRoot)
865     {
866         SGPropertyNode* listenProp = makeNode(propRoot, *propName);
867         delete propName;
868         propName = 0;
869         if (listenProp)
870             listenProp->addChangeListener(this, true);
871     }
872
873 private:
874     ref_ptr<Pass> pass;
875     int unit;
876     std::string* propName;
877 };
878
879 Texture* GBufferBuilder::build(Effect* effect, Pass* pass, const SGPropertyNode* prop,
880                                     const SGReaderWriterOptions* options)
881 {
882     int unit = 0;
883     const SGPropertyNode* pUnit = prop->getChild("unit");
884     if (pUnit) {
885         unit = pUnit->getValue<int>();
886     } else {
887         SG_LOG(SG_INPUT, SG_ALERT, "no texture unit");
888     }
889     const SGPropertyNode* nameProp = getEffectPropertyChild(effect, prop,
890                                                             "name");
891     if (!nameProp)
892         return 0;
893
894     if (nameProp->nChildren() == 0) {
895         buffer = nameProp->getStringValue();
896         pass->setBufferUnit( unit, buffer );
897     } else {
898         std::string propName = getGlobalProperty(nameProp, options);
899         BufferNameChangeListener* listener = new BufferNameChangeListener(pass, unit, propName);
900         effect->addUpdater(listener);
901     }
902
903     // Return white for now. Would be overridden in Technique::ProcessDrawable
904     return StateAttributeFactory::instance()->getWhiteTexture();
905 }
906
907 namespace
908 {
909     TextureBuilder::Registrar installBuffer("buffer", new GBufferBuilder);
910 }
911
912 }