]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/TextureBuilder.cxx
Terrasync: make whitespace in pathnames work under windows
[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
36 #include <boost/lexical_cast.hpp>
37 #include <boost/tuple/tuple.hpp>
38 #include <boost/tuple/tuple_comparison.hpp>
39
40 #include <simgear/scene/model/SGReaderWriterXMLOptions.hxx>
41 #include <simgear/scene/util/SGSceneFeatures.hxx>
42 #include <simgear/scene/util/StateAttributeFactory.hxx>
43 #include <simgear/math/SGMath.hxx>
44 #include <simgear/structure/OSGUtils.hxx>
45
46 #include "Noise.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 SGReaderWriterXMLOptions* 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, const string& type,
62                                             const SGPropertyNode*props,
63                                             const SGReaderWriterXMLOptions*
64                                             options)
65 {
66     return EffectBuilder<Texture>::buildFromType(effect, 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 SGReaderWriterXMLOptions* 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, type, prop,
133                                                 options);
134     }
135     catch (BuilderException& e) {
136         SG_LOG(SG_INPUT, SG_ALERT, 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 SGReaderWriterXMLOptions* 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     if (pImage)
215         imageName = pImage->getStringValue();
216     string absFileName = SGModelLib::findDataFile(imageName, options);
217
218     const SGPropertyNode* pMipmapControl
219         = getEffectPropertyChild(effect, props, "mipmap-control");
220     MipMapTuple mipmapFunctions( AUTOMATIC, AUTOMATIC, AUTOMATIC, AUTOMATIC ); 
221     if ( pMipmapControl )
222         mipmapFunctions = makeMipMapTuple(effect, pMipmapControl, options);
223
224     return TexTuple(absFileName, minFilter, magFilter, sWrap, tWrap, rWrap,
225                     texType, mipmapFunctions);
226 }
227
228 void setAttrs(const TexTuple& attrs, Texture* tex,
229               const SGReaderWriterXMLOptions* options)
230 {
231     const string& imageName = attrs.get<0>();
232     if (imageName.empty()) {
233         throw BuilderException("no image file");
234     } else {
235         osgDB::ReaderWriter::ReadResult result
236             = osgDB::Registry::instance()->readImage(imageName, options);
237         if (result.success()) {
238             osg::ref_ptr<osg::Image> image = result.getImage();
239             image = computeMipmap( image.get(), attrs.get<7>() );
240             tex->setImage(GL_FRONT_AND_BACK, image.get());
241             int s = image->s();
242             int t = image->t();
243             if (s <= t && 32 <= s) {
244                 SGSceneFeatures::instance()->setTextureCompression(tex);
245             } else if (t < s && 32 <= t) {
246                 SGSceneFeatures::instance()->setTextureCompression(tex);
247             }
248             tex->setMaxAnisotropy(SGSceneFeatures::instance()
249                                   ->getTextureFilter());
250         } else {
251             SG_LOG(SG_INPUT, SG_ALERT, "failed to load effect texture file "
252                    << imageName);
253         }
254     }
255     // texture->setDataVariance(osg::Object::STATIC);
256     tex->setFilter(Texture::MIN_FILTER, attrs.get<1>());
257     tex->setFilter(Texture::MAG_FILTER, attrs.get<2>());
258     tex->setWrap(Texture::WRAP_S, attrs.get<3>());
259     tex->setWrap(Texture::WRAP_T, attrs.get<4>());
260     tex->setWrap(Texture::WRAP_R, attrs.get<5>());
261 }
262 }
263
264 template<typename T>
265 class TexBuilder : public TextureBuilder
266 {
267 public:
268     TexBuilder(const string& texType) : _type(texType) {}
269     Texture* build(Effect* effect, const SGPropertyNode*,
270                    const SGReaderWriterXMLOptions* options);
271 protected:
272     typedef map<TexTuple, ref_ptr<T> > TexMap;
273     TexMap texMap;
274     const string _type;
275 };
276
277 template<typename T>
278 Texture* TexBuilder<T>::build(Effect* effect, const SGPropertyNode* props,
279                               const SGReaderWriterXMLOptions* options)
280 {
281     TexTuple attrs = makeTexTuple(effect, props, options, _type);
282     typename TexMap::iterator itr = texMap.find(attrs);
283     if (itr != texMap.end())
284         return itr->second.get();
285     T* tex = new T;
286     setAttrs(attrs, tex, options);
287     texMap.insert(make_pair(attrs, tex));
288     return tex;
289 }
290
291
292 namespace
293 {
294 TextureBuilder::Registrar install1D("1d", new TexBuilder<Texture1D>("1d"));
295 TextureBuilder::Registrar install2D("2d", new TexBuilder<Texture2D>("2d"));
296 TextureBuilder::Registrar install3D("3d", new TexBuilder<Texture3D>("3d"));
297 }
298
299 class WhiteTextureBuilder : public TextureBuilder
300 {
301 public:
302     Texture* build(Effect* effect, const SGPropertyNode*,
303                    const SGReaderWriterXMLOptions* options);
304 };
305
306 Texture* WhiteTextureBuilder::build(Effect* effect, const SGPropertyNode*,
307                                     const SGReaderWriterXMLOptions* options)
308 {
309     return StateAttributeFactory::instance()->getWhiteTexture();
310 }
311
312 namespace
313 {
314 TextureBuilder::Registrar installWhite("white", new WhiteTextureBuilder);
315 }
316
317 class TransparentTextureBuilder : public TextureBuilder
318 {
319 public:
320     Texture* build(Effect* effect, const SGPropertyNode*,
321                    const SGReaderWriterXMLOptions* options);
322 };
323
324 Texture* TransparentTextureBuilder::build(Effect* effect, const SGPropertyNode*,
325                                     const SGReaderWriterXMLOptions* options)
326 {
327     return StateAttributeFactory::instance()->getTransparentTexture();
328 }
329
330 namespace
331 {
332 TextureBuilder::Registrar installTransparent("transparent",
333                                              new TransparentTextureBuilder);
334 }
335
336 osg::Image* make3DNoiseImage(int texSize)
337 {
338     osg::Image* image = new osg::Image;
339     image->setImage(texSize, texSize, texSize,
340                     4, GL_RGBA, GL_UNSIGNED_BYTE,
341                     new unsigned char[4 * texSize * texSize * texSize],
342                     osg::Image::USE_NEW_DELETE);
343
344     const int startFrequency = 4;
345     const int numOctaves = 4;
346
347     int f, i, j, k, inc;
348     double ni[3];
349     double inci, incj, inck;
350     int frequency = startFrequency;
351     GLubyte *ptr;
352     double amp = 0.5;
353
354     osg::notify(osg::WARN) << "creating 3D noise texture... ";
355
356     for (f = 0, inc = 0; f < numOctaves; ++f, frequency *= 2, ++inc, amp *= 0.5)
357     {
358         SetNoiseFrequency(frequency);
359         ptr = image->data();
360         ni[0] = ni[1] = ni[2] = 0;
361
362         inci = 1.0 / (texSize / frequency);
363         for (i = 0; i < texSize; ++i, ni[0] += inci)
364         {
365             incj = 1.0 / (texSize / frequency);
366             for (j = 0; j < texSize; ++j, ni[1] += incj)
367             {
368                 inck = 1.0 / (texSize / frequency);
369                 for (k = 0; k < texSize; ++k, ni[2] += inck, ptr += 4)
370                 {
371                     *(ptr+inc) = (GLubyte) (((noise3(ni) + 1.0) * amp) * 128.0);
372                 }
373             }
374         }
375     }
376
377     osg::notify(osg::WARN) << "DONE" << std::endl;
378     return image;
379 }
380
381 class NoiseBuilder : public TextureBuilder
382 {
383 public:
384     Texture* build(Effect* effect, const SGPropertyNode*,
385                    const SGReaderWriterXMLOptions* options);
386 protected:
387     typedef map<int, ref_ptr<Texture3D> > NoiseMap;
388     NoiseMap _noises;
389 };
390
391 Texture* NoiseBuilder::build(Effect* effect, const SGPropertyNode* props,
392                              const SGReaderWriterXMLOptions* options)
393 {
394     int texSize = 64;
395     const SGPropertyNode* sizeProp = getEffectPropertyChild(effect, props,
396                                                             "size");
397     if (sizeProp)
398         texSize = sizeProp->getValue<int>();
399     NoiseMap::iterator itr = _noises.find(texSize);
400     if (itr != _noises.end())
401         return itr->second.get();
402     Texture3D* noiseTexture = new osg::Texture3D;
403     noiseTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture3D::LINEAR);
404     noiseTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture3D::LINEAR);
405     noiseTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture3D::REPEAT);
406     noiseTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture3D::REPEAT);
407     noiseTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture3D::REPEAT);
408     noiseTexture->setImage( make3DNoiseImage(texSize) );
409     _noises.insert(make_pair(texSize, noiseTexture));
410     return noiseTexture;
411 }
412
413 namespace
414 {
415 TextureBuilder::Registrar installNoise("noise", new NoiseBuilder);
416 }
417
418
419
420 // Image names for all sides
421 typedef boost::tuple<string, string, string, string, string, string> CubeMapTuple;
422
423 CubeMapTuple makeCubeMapTuple(Effect* effect, const SGPropertyNode* props)
424 {
425     const SGPropertyNode* ep = 0;
426
427     string positive_x;
428     if ((ep = getEffectPropertyChild(effect, props, "positive-x")))
429         positive_x = ep->getStringValue();
430     string negative_x;
431     if ((ep = getEffectPropertyChild(effect, props, "negative-x")))
432         negative_x = ep->getStringValue();
433     string positive_y;
434     if ((ep = getEffectPropertyChild(effect, props, "positive-y")))
435         positive_y = ep->getStringValue();
436     string negative_y;
437     if ((ep = getEffectPropertyChild(effect, props, "negative-y")))
438         negative_y = ep->getStringValue();
439     string positive_z;
440     if ((ep = getEffectPropertyChild(effect, props, "positive-z")))
441         positive_z = ep->getStringValue();
442     string negative_z;
443     if ((ep = getEffectPropertyChild(effect, props, "negative-z")))
444         negative_z = ep->getStringValue();
445     return CubeMapTuple(positive_x, negative_x, positive_y, negative_y, positive_z, negative_z);
446 }
447
448
449 class CubeMapBuilder : public TextureBuilder
450 {
451 public:
452     Texture* build(Effect* effect, const SGPropertyNode*,
453                    const SGReaderWriterXMLOptions* options);
454 protected:
455     typedef map<CubeMapTuple, ref_ptr<TextureCubeMap> > CubeMap;
456     typedef map<string, ref_ptr<TextureCubeMap> > CrossCubeMap;
457     CubeMap _cubemaps;
458     CrossCubeMap _crossmaps;
459 };
460
461 // I use this until osg::CopyImage is fixed
462 // This one assumes images are the same format and sizes are correct
463 void copySubImage(const osg::Image* srcImage, int src_s, int src_t, int width, int height, 
464                  osg::Image* destImage, int dest_s, int dest_t)
465 {
466     for(int row = 0; row<height; ++row)
467     {
468         const unsigned char* srcData = srcImage->data(src_s, src_t+row, 0);
469         unsigned char* destData = destImage->data(dest_s, dest_t+row, 0);
470         memcpy(destData, srcData, (width*destImage->getPixelSizeInBits())/8);
471     }
472 }
473
474
475 Texture* CubeMapBuilder::build(Effect* effect, const SGPropertyNode* props,
476                                const SGReaderWriterXMLOptions* options)
477 {
478     // First check that there is a <images> tag
479     const SGPropertyNode* texturesProp = getEffectPropertyChild(effect, props, "images");
480     const SGPropertyNode* crossProp = getEffectPropertyChild(effect, props, "image");
481     if (!texturesProp && !crossProp) {
482         throw BuilderException("no images defined for cube map");
483         return NULL; // This is redundant
484     }
485
486     // Using 6 separate images
487     if(texturesProp) {
488
489         SG_LOG(SG_INPUT, SG_DEBUG, "try 6 images ");
490
491         CubeMapTuple _tuple = makeCubeMapTuple(effect, texturesProp);
492
493         CubeMap::iterator itr = _cubemaps.find(_tuple);
494         if (itr != _cubemaps.end())
495             return itr->second.get();
496
497         TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
498
499         // TODO: Read these from effect file? Maybe these are sane for all cuebmaps?
500         cubeTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture::LINEAR_MIPMAP_LINEAR);
501         cubeTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture::LINEAR);
502         cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
503         cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
504         cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
505
506         osgDB::ReaderWriter::ReadResult result =
507             osgDB::Registry::instance()->readImage(_tuple.get<0>(), options);
508         if(result.success()) {
509             osg::Image* image = result.getImage();
510             cubeTexture->setImage(TextureCubeMap::POSITIVE_X, image);
511         }
512         result = osgDB::Registry::instance()->readImage(_tuple.get<1>(), options);
513         if(result.success()) {
514             osg::Image* image = result.getImage();
515             cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, image);
516         }
517         result = osgDB::Registry::instance()->readImage(_tuple.get<2>(), options);
518         if(result.success()) {
519             osg::Image* image = result.getImage();
520             cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, image);
521         }
522         result = osgDB::Registry::instance()->readImage(_tuple.get<3>(), options);
523         if(result.success()) {
524             osg::Image* image = result.getImage();
525             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, image);
526         }
527         result = osgDB::Registry::instance()->readImage(_tuple.get<4>(), options);
528         if(result.success()) {
529             osg::Image* image = result.getImage();
530             cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, image);
531         }
532         result = osgDB::Registry::instance()->readImage(_tuple.get<5>(), options);
533         if(result.success()) {
534             osg::Image* image = result.getImage();
535             cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, image);
536         }
537
538         _cubemaps[_tuple] = cubeTexture;
539
540         return cubeTexture;
541     }
542
543
544     // Using 1 cross image
545     else if(crossProp) {
546         SG_LOG(SG_INPUT, SG_DEBUG, "try cross map ");
547
548         std::string texname = crossProp->getStringValue();
549
550         // Try to find existing cube map
551         CrossCubeMap::iterator itr = _crossmaps.find(texname);
552         if (itr != _crossmaps.end())
553             return itr->second.get();
554
555         osgDB::ReaderWriter::ReadResult result =
556             osgDB::Registry::instance()->readImage(texname, options);
557         if(result.success()) {
558             osg::Image* image = result.getImage();
559             image->flipVertical();   // Seems like the image coordinates are somewhat funny, flip to get better ones
560
561             //cubeTexture->setResizeNonPowerOfTwoHint(false);
562
563             // Size of a single image, 4 rows and 3 columns
564             int width = image->s() / 3;
565             int height = image->t() / 4;
566             int depth = image->r();
567
568             TextureCubeMap* cubeTexture = new osg::TextureCubeMap;
569
570             // Copy the 6 sub-images and push them
571             for(int n=0; n<6; n++) {
572
573                 SG_LOG(SG_INPUT, SG_DEBUG, "Copying the " << n << "th sub-images and pushing it" );
574
575                 osg::ref_ptr<osg::Image> subimg = new osg::Image();
576                 subimg->allocateImage(width, height, depth, image->getPixelFormat(), image->getDataType());  // Copy attributes
577
578                 // Choose correct image
579                 switch(n) {
580                 case 0:  // Front
581                     copySubImage(image, width, 0, width, height, subimg.get(), 0, 0);
582                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Y, subimg.get());
583                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
584                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
585                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
586                     break;
587                 case 1:  // Left
588                     copySubImage(image, 0, height, width, height, subimg.get(), 0, 0);
589                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_X, subimg.get());
590                     cubeTexture->setWrap(osg::Texture2D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
591                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
592                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
593                     break;
594                 case 2:  // Top
595                     copySubImage(image, width, height, width, height, subimg.get(), 0, 0);
596                     cubeTexture->setImage(TextureCubeMap::POSITIVE_Z, subimg.get());
597                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
598                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
599                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
600                     break;
601                 case 3:  // Right
602                     copySubImage(image, width*2, height, width, height, subimg.get(), 0, 0);
603                     cubeTexture->setImage(TextureCubeMap::POSITIVE_X, subimg.get());
604                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
605                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
606                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
607                     break;
608                 case 4:  // Back
609                     copySubImage(image, width, height*2, width, height, subimg.get(), 0, 0);
610                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Y, subimg.get());
611                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
612                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
613                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
614                     break;
615                 case 5:  // Bottom
616                     copySubImage(image, width, height*3, width, height, subimg.get(), 0, 0);
617                     cubeTexture->setImage(TextureCubeMap::NEGATIVE_Z, subimg.get());
618                     cubeTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
619                     cubeTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
620                     cubeTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture::CLAMP_TO_EDGE);
621                     break;
622                 };
623
624             }
625
626             _crossmaps[texname] = cubeTexture;
627
628             return cubeTexture;
629
630         } else {
631             throw BuilderException("Could not load cube cross");
632         }
633     }
634
635     return NULL;
636 }
637
638 namespace {
639 TextureBuilder::Registrar installCubeMap("cubemap", new CubeMapBuilder);
640 }
641
642 EffectNameValue<TexEnvCombine::CombineParam> combineParamInit[] =
643 {
644     {"replace", TexEnvCombine::REPLACE},
645     {"modulate", TexEnvCombine::MODULATE},
646     {"add", TexEnvCombine::ADD},
647     {"add-signed", TexEnvCombine::ADD_SIGNED},
648     {"interpolate", TexEnvCombine::INTERPOLATE},
649     {"subtract", TexEnvCombine::SUBTRACT},
650     {"dot3-rgb", TexEnvCombine::DOT3_RGB},
651     {"dot3-rgba", TexEnvCombine::DOT3_RGBA}
652 };
653
654 EffectPropertyMap<TexEnvCombine::CombineParam> combineParams(combineParamInit);
655
656 EffectNameValue<TexEnvCombine::SourceParam> sourceParamInit[] =
657 {
658     {"constant", TexEnvCombine::CONSTANT},
659     {"primary_color", TexEnvCombine::PRIMARY_COLOR},
660     {"previous", TexEnvCombine::PREVIOUS},
661     {"texture", TexEnvCombine::TEXTURE},
662     {"texture0", TexEnvCombine::TEXTURE0},
663     {"texture1", TexEnvCombine::TEXTURE1},
664     {"texture2", TexEnvCombine::TEXTURE2},
665     {"texture3", TexEnvCombine::TEXTURE3},
666     {"texture4", TexEnvCombine::TEXTURE4},
667     {"texture5", TexEnvCombine::TEXTURE5},
668     {"texture6", TexEnvCombine::TEXTURE6},
669     {"texture7", TexEnvCombine::TEXTURE7}
670 };
671
672 EffectPropertyMap<TexEnvCombine::SourceParam> sourceParams(sourceParamInit);
673
674 EffectNameValue<TexEnvCombine::OperandParam> opParamInit[] =
675 {
676     {"src-color", TexEnvCombine::SRC_COLOR},
677     {"one-minus-src-color", TexEnvCombine::ONE_MINUS_SRC_COLOR},
678     {"src-alpha", TexEnvCombine::SRC_ALPHA},
679     {"one-minus-src-alpha", TexEnvCombine::ONE_MINUS_SRC_ALPHA}
680 };
681
682 EffectPropertyMap<TexEnvCombine::OperandParam> operandParams(opParamInit);
683
684 TexEnvCombine* buildTexEnvCombine(Effect* effect, const SGPropertyNode* envProp,
685                                   const SGReaderWriterXMLOptions* options)
686 {
687     if (!isAttributeActive(effect, envProp))
688         return 0;
689     TexEnvCombine* result = new TexEnvCombine;
690     const SGPropertyNode* p = 0;
691     if ((p = getEffectPropertyChild(effect, envProp, "combine-rgb"))) {
692         TexEnvCombine::CombineParam crgb = TexEnvCombine::MODULATE;
693         findAttr(combineParams, p, crgb);
694         result->setCombine_RGB(crgb);
695     }
696     if ((p = getEffectPropertyChild(effect, envProp, "combine-alpha"))) {
697         TexEnvCombine::CombineParam calpha = TexEnvCombine::MODULATE;
698         findAttr(combineParams, p, calpha);
699         result->setCombine_Alpha(calpha);
700     }
701     if ((p = getEffectPropertyChild(effect, envProp, "source0-rgb"))) {
702         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
703         findAttr(sourceParams, p, source);
704         result->setSource0_RGB(source);
705     }
706     if ((p = getEffectPropertyChild(effect, envProp, "source1-rgb"))) {
707         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
708         findAttr(sourceParams, p, source);
709         result->setSource1_RGB(source);
710     }
711     if ((p = getEffectPropertyChild(effect, envProp, "source2-rgb"))) {
712         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
713         findAttr(sourceParams, p, source);
714         result->setSource2_RGB(source);
715     }
716     if ((p = getEffectPropertyChild(effect, envProp, "source0-alpha"))) {
717         TexEnvCombine::SourceParam source = TexEnvCombine::TEXTURE;
718         findAttr(sourceParams, p, source);
719         result->setSource0_Alpha(source);
720     }
721     if ((p = getEffectPropertyChild(effect, envProp, "source1-alpha"))) {
722         TexEnvCombine::SourceParam source = TexEnvCombine::PREVIOUS;
723         findAttr(sourceParams, p, source);
724         result->setSource1_Alpha(source);
725     }
726     if ((p = getEffectPropertyChild(effect, envProp, "source2-alpha"))) {
727         TexEnvCombine::SourceParam source = TexEnvCombine::CONSTANT;
728         findAttr(sourceParams, p, source);
729         result->setSource2_Alpha(source);
730     }
731     if ((p = getEffectPropertyChild(effect, envProp, "operand0-rgb"))) {
732         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
733         findAttr(operandParams, p, op);
734         result->setOperand0_RGB(op);
735     }
736     if ((p = getEffectPropertyChild(effect, envProp, "operand1-rgb"))) {
737         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_COLOR;
738         findAttr(operandParams, p, op);
739         result->setOperand1_RGB(op);
740     }
741     if ((p = getEffectPropertyChild(effect, envProp, "operand2-rgb"))) {
742         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
743         findAttr(operandParams, p, op);
744         result->setOperand2_RGB(op);
745     }
746     if ((p = getEffectPropertyChild(effect, envProp, "operand0-alpha"))) {
747         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
748         findAttr(operandParams, p, op);
749         result->setOperand0_Alpha(op);
750     }
751     if ((p = getEffectPropertyChild(effect, envProp, "operand1-alpha"))) {
752         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
753         findAttr(operandParams, p, op);
754         result->setOperand1_Alpha(op);
755     }
756     if ((p = getEffectPropertyChild(effect, envProp, "operand2-alpha"))) {
757         TexEnvCombine::OperandParam op = TexEnvCombine::SRC_ALPHA;
758         findAttr(operandParams, p, op);
759         result->setOperand2_Alpha(op);
760     }
761     if ((p = getEffectPropertyChild(effect, envProp, "scale-rgb"))) {
762         result->setScale_RGB(p->getValue<float>());
763     }
764     if ((p = getEffectPropertyChild(effect, envProp, "scale-alpha"))) {
765         result->setScale_Alpha(p->getValue<float>());
766     }
767 #if 0
768     if ((p = getEffectPropertyChild(effect, envProp, "constant-color"))) {
769         SGVec4d color = p->getValue<SGVec4d>();
770         result->setConstantColor(toOsg(color));
771     } else if ((p = getEffectPropertyChild(effect, envProp,
772                                            "light-direction"))) {
773         SGVec3d direction = p->getValue<SGVec3d>();
774         result->setConstantColorAsLightDirection(toOsg(direction));
775     }
776 #endif
777     const SGPropertyNode* colorNode = envProp->getChild("constant-color");
778     if (colorNode)
779         initFromParameters(effect, colorNode, result,
780                            &TexEnvCombine::setConstantColor, colorFields,
781                            options);
782     return result;
783 }
784
785 EffectNameValue<TexGen::Mode> tgenModeInit[] =
786 {
787     { "object-linear", TexGen::OBJECT_LINEAR},
788     { "eye-linear", TexGen::EYE_LINEAR},
789     { "sphere-map", TexGen::SPHERE_MAP},
790     { "normal-map", TexGen::NORMAL_MAP},
791     { "reflection-map", TexGen::REFLECTION_MAP}
792 };
793
794 EffectPropertyMap<TexGen::Mode> tgenModes(tgenModeInit);
795
796 EffectNameValue<TexGen::Coord> tgenCoordInit[] =
797 {
798     {"s", TexGen::S},
799     {"t", TexGen::T},
800     {"r", TexGen::R},
801     {"q", TexGen::Q}
802 };
803
804 EffectPropertyMap<TexGen::Coord> tgenCoords(tgenCoordInit);
805
806 TexGen* buildTexGen(Effect* effect, const SGPropertyNode* tgenProp)
807 {
808     if (!isAttributeActive(effect, tgenProp))
809         return 0;
810     TexGen* result = new TexGen;
811     TexGen::Mode mode = TexGen::OBJECT_LINEAR;
812     findAttr(tgenModes, getEffectPropertyChild(effect, tgenProp, "mode"), mode);
813     result->setMode(mode);
814     const SGPropertyNode* planesNode = tgenProp->getChild("planes");
815     if (planesNode) {
816         for (int i = 0; i < planesNode->nChildren(); ++i) {
817             const SGPropertyNode* planeNode = planesNode->getChild(i);
818             TexGen::Coord coord;
819             findAttr(tgenCoords, planeNode->getName(), coord);
820             const SGPropertyNode* realNode
821                 = getEffectPropertyNode(effect, planeNode);
822             SGVec4d plane = realNode->getValue<SGVec4d>();
823             result->setPlane(coord, toOsg(plane));
824         }
825     }
826     return result;
827 }
828
829 bool makeTextureParameters(SGPropertyNode* paramRoot, const StateSet* ss)
830 {
831     SGPropertyNode* texUnit = makeChild(paramRoot, "texture");
832     const Texture* tex = getStateAttribute<Texture>(0, ss);
833     const Texture2D* texture = dynamic_cast<const Texture2D*>(tex);
834     makeChild(texUnit, "unit")->setValue(0);
835     if (!tex) {
836         // The default shader-based technique ignores active
837         makeChild(texUnit, "active")->setValue(false);
838         return false;
839     }
840     const Image* image = texture->getImage();
841     string imageName;
842     if (image) {
843         imageName = image->getFileName();
844     } else {
845         makeChild(texUnit, "active")->setValue(false);
846         makeChild(texUnit, "type")->setValue("white");
847         return false;
848     }
849     makeChild(texUnit, "active")->setValue(true);
850     makeChild(texUnit, "type")->setValue("2d");
851     string filter = findName(filterModes,
852                              texture->getFilter(Texture::MIN_FILTER));
853     string magFilter = findName(filterModes,
854                              texture->getFilter(Texture::MAG_FILTER));
855     string wrapS = findName(wrapModes, texture->getWrap(Texture::WRAP_S));
856     string wrapT = findName(wrapModes, texture->getWrap(Texture::WRAP_T));
857     string wrapR = findName(wrapModes, texture->getWrap(Texture::WRAP_R));
858     makeChild(texUnit, "image")->setStringValue(imageName);
859     makeChild(texUnit, "filter")->setStringValue(filter);
860     makeChild(texUnit, "mag-filter")->setStringValue(magFilter);
861     makeChild(texUnit, "wrap-s")->setStringValue(wrapS);
862     makeChild(texUnit, "wrap-t")->setStringValue(wrapT);
863     makeChild(texUnit, "wrap-r")->setStringValue(wrapR);
864     return true;
865 }
866
867 }