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