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