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