]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/TextureBuilder.cxx
Move Texture unit builder into TexBuilder.cxx
[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
23 #include "Pass.hxx"
24
25 #include <osg/TexEnv>
26 #include <osg/TexEnvCombine>
27 #include <osg/Texture1D>
28 #include <osg/Texture2D>
29 #include <osg/Texture3D>
30 #include <osg/TextureRectangle>
31 #include <osgDB/FileUtils>
32
33 #include <boost/lexical_cast.hpp>
34 #include <boost/tuple/tuple.hpp>
35 #include <boost/tuple/tuple_comparison.hpp>
36
37 #include <simgear/scene/util/SGSceneFeatures.hxx>
38 #include <simgear/scene/util/StateAttributeFactory.hxx>
39 #include <simgear/math/SGMath.hxx>
40 #include <simgear/structure/OSGUtils.hxx>
41
42 #include "Noise.hxx"
43
44 namespace simgear
45 {
46 using namespace std;
47 using namespace osg;
48
49 using namespace effect;
50
51 // Hack to force inclusion of TextureBuilder.cxx in library
52 osg::Texture* TextureBuilder::buildFromType(Effect* effect, const string& type,
53                                             const SGPropertyNode*props,
54                                             const osgDB::ReaderWriter::Options*
55                                             options)
56 {
57     return EffectBuilder<Texture>::buildFromType(effect, type, props, options);
58 }
59
60 typedef boost::tuple<string, Texture::FilterMode, Texture::FilterMode,
61                      Texture::WrapMode, Texture::WrapMode, Texture::WrapMode,
62                      string> TexTuple;
63
64 EffectNameValue<TexEnv::Mode> texEnvModesInit[] =
65 {
66     {"add", TexEnv::ADD},
67     {"blend", TexEnv::BLEND},
68     {"decal", TexEnv::DECAL},
69     {"modulate", TexEnv::MODULATE},
70     {"replace", TexEnv::REPLACE}
71 };
72 EffectPropertyMap<TexEnv::Mode> texEnvModes(texEnvModesInit);
73
74 TexEnv* buildTexEnv(Effect* effect, const SGPropertyNode* prop)
75 {
76     const SGPropertyNode* modeProp = getEffectPropertyChild(effect, prop,
77                                                             "mode");
78     const SGPropertyNode* colorProp = getEffectPropertyChild(effect, prop,
79                                                              "color");
80     if (!modeProp)
81         return 0;
82     TexEnv::Mode mode = TexEnv::MODULATE;
83     findAttr(texEnvModes, modeProp, mode);
84     if (mode == TexEnv::MODULATE) {
85         return StateAttributeFactory::instance()->getStandardTexEnv();
86     }
87     TexEnv* env = new TexEnv(mode);
88     if (colorProp)
89         env->setColor(toOsg(colorProp->getValue<SGVec4d>()));
90     return env;
91  }
92
93
94 void TextureUnitBuilder::buildAttribute(Effect* effect, Pass* pass,
95                                         const SGPropertyNode* prop,
96                                         const osgDB::ReaderWriter::Options* options)
97 {
98     if (!isAttributeActive(effect, prop))
99         return;
100     // Decode the texture unit
101     int unit = 0;
102     const SGPropertyNode* pUnit = prop->getChild("unit");
103     if (pUnit) {
104         unit = pUnit->getValue<int>();
105     } else {
106         const SGPropertyNode* pName = prop->getChild("name");
107         if (pName)
108             try {
109                 unit = boost::lexical_cast<int>(pName->getStringValue());
110             } catch (boost::bad_lexical_cast& lex) {
111                 SG_LOG(SG_INPUT, SG_ALERT, "can't decode name as texture unit "
112                        << lex.what());
113             }
114     }
115     const SGPropertyNode* pType = getEffectPropertyChild(effect, prop, "type");
116     string type;
117     if (!pType)
118         type = "2d";
119     else
120         type = pType->getStringValue();
121     Texture* texture = 0;
122     try {
123         texture = TextureBuilder::buildFromType(effect, type, prop,
124                                                 options);
125     }
126     catch (BuilderException& e) {
127         SG_LOG(SG_INPUT, SG_ALERT, "No image file for texture, using white ");
128         texture = StateAttributeFactory::instance()->getWhiteTexture();
129     }
130     pass->setTextureAttributeAndModes(unit, texture);
131     const SGPropertyNode* envProp = prop->getChild("environment");
132     if (envProp) {
133         TexEnv* env = buildTexEnv(effect, envProp);
134         if (env)
135             pass->setTextureAttributeAndModes(unit, env);
136     }
137 }
138
139 // InstallAttributeBuilder call is in Effect.cxx to force this file to
140 // be linked in.
141
142 namespace
143 {
144 EffectNameValue<Texture::FilterMode> filterModesInit[] =
145 {
146     { "linear", Texture::LINEAR },
147     { "linear-mipmap-linear", Texture::LINEAR_MIPMAP_LINEAR},
148     { "linear-mipmap-nearest", Texture::LINEAR_MIPMAP_NEAREST},
149     { "nearest", Texture::NEAREST},
150     { "nearest-mipmap-linear", Texture::NEAREST_MIPMAP_LINEAR},
151     { "nearest-mipmap-nearest", Texture::NEAREST_MIPMAP_NEAREST}
152 };
153 EffectPropertyMap<Texture::FilterMode> filterModes(filterModesInit);
154
155 EffectNameValue<Texture::WrapMode> wrapModesInit[] =
156 {
157     {"clamp", Texture::CLAMP},
158     {"clamp-to-border", Texture::CLAMP_TO_BORDER},
159     {"clamp-to-edge", Texture::CLAMP_TO_EDGE},
160     {"mirror", Texture::MIRROR},
161     {"repeat", Texture::REPEAT}
162 };
163 EffectPropertyMap<Texture::WrapMode> wrapModes(wrapModesInit);
164
165
166 TexTuple makeTexTuple(Effect* effect, const SGPropertyNode* props,
167                       const osgDB::ReaderWriter::Options* options,
168                       const string& texType)
169 {
170     Texture::FilterMode minFilter = Texture::LINEAR_MIPMAP_LINEAR;
171     findAttr(filterModes, getEffectPropertyChild(effect, props, "filter"),
172              minFilter);
173     Texture::FilterMode magFilter = Texture::LINEAR;
174     findAttr(filterModes, getEffectPropertyChild(effect, props,
175                                                  "mag-filter"),
176              magFilter);
177     const SGPropertyNode* pWrapS
178         = getEffectPropertyChild(effect, props, "wrap-s");
179     Texture::WrapMode sWrap = Texture::CLAMP;
180     findAttr(wrapModes, pWrapS, sWrap);
181     const SGPropertyNode* pWrapT
182         = getEffectPropertyChild(effect, props, "wrap-t");
183     Texture::WrapMode tWrap = Texture::CLAMP;
184     findAttr(wrapModes, pWrapT, tWrap);
185     const SGPropertyNode* pWrapR
186         = getEffectPropertyChild(effect, props, "wrap-r");
187     Texture::WrapMode rWrap = Texture::CLAMP;
188     findAttr(wrapModes, pWrapR, rWrap);
189     const SGPropertyNode* pImage
190         = getEffectPropertyChild(effect, props, "image");
191     string imageName;
192     if (pImage)
193         imageName = pImage->getStringValue();
194     string absFileName = osgDB::findDataFile(imageName, options);
195     return TexTuple(absFileName, minFilter, magFilter, sWrap, tWrap, rWrap,
196                     texType);
197 }
198
199 void setAttrs(const TexTuple& attrs, Texture* tex,
200               const osgDB::ReaderWriter::Options* options)
201 {
202     const string& imageName = attrs.get<0>();
203     if (imageName.empty()) {
204         throw BuilderException("no image file");
205     } else {
206         osgDB::ReaderWriter::ReadResult result
207             = osgDB::Registry::instance()->readImage(imageName, options);
208         if (result.success()) {
209             osg::Image* image = result.getImage();
210             tex->setImage(GL_FRONT_AND_BACK, image);
211             int s = image->s();
212             int t = image->t();
213             if (s <= t && 32 <= s) {
214                 SGSceneFeatures::instance()->setTextureCompression(tex);
215             } else if (t < s && 32 <= t) {
216                 SGSceneFeatures::instance()->setTextureCompression(tex);
217             }
218             tex->setMaxAnisotropy(SGSceneFeatures::instance()
219                                   ->getTextureFilter());
220         } else {
221             SG_LOG(SG_INPUT, SG_ALERT, "failed to load effect texture file "
222                    << imageName);
223         }
224     }
225     // texture->setDataVariance(osg::Object::STATIC);
226     tex->setFilter(Texture::MIN_FILTER, attrs.get<1>());
227     tex->setFilter(Texture::MAG_FILTER, attrs.get<2>());
228     tex->setWrap(Texture::WRAP_S, attrs.get<3>());
229     tex->setWrap(Texture::WRAP_T, attrs.get<4>());
230     tex->setWrap(Texture::WRAP_R, attrs.get<5>());
231 }
232 }
233
234 template<typename T>
235 class TexBuilder : public TextureBuilder
236 {
237 public:
238     TexBuilder(const string& texType) : _type(texType) {}
239     Texture* build(Effect* effect, const SGPropertyNode*,
240                    const osgDB::ReaderWriter::Options* options);
241 protected:
242     typedef map<TexTuple, ref_ptr<T> > TexMap;
243     TexMap texMap;
244     const string _type;
245 };
246
247 template<typename T>
248 Texture* TexBuilder<T>::build(Effect* effect, const SGPropertyNode* props,
249                               const osgDB::ReaderWriter::Options* options)
250 {
251     TexTuple attrs = makeTexTuple(effect, props, options, _type);
252     typename TexMap::iterator itr = texMap.find(attrs);
253     if (itr != texMap.end())
254         return itr->second.get();
255     T* tex = new T;
256     setAttrs(attrs, tex, options);
257     texMap.insert(make_pair(attrs, tex));
258     return tex;
259 }
260
261
262 namespace
263 {
264 TextureBuilder::Registrar install1D("1d", new TexBuilder<Texture1D>("1d"));
265 TextureBuilder::Registrar install2D("2d", new TexBuilder<Texture2D>("2d"));
266 TextureBuilder::Registrar install3D("3d", new TexBuilder<Texture3D>("3d"));
267 }
268
269 class WhiteTextureBuilder : public TextureBuilder
270 {
271 public:
272     Texture* build(Effect* effect, const SGPropertyNode*,
273                    const osgDB::ReaderWriter::Options* options);
274 };
275
276 Texture* WhiteTextureBuilder::build(Effect* effect, const SGPropertyNode*,
277                                     const osgDB::ReaderWriter::Options* options)
278 {
279     return StateAttributeFactory::instance()->getWhiteTexture();
280 }
281
282 namespace
283 {
284 TextureBuilder::Registrar installWhite("white", new WhiteTextureBuilder);
285 }
286
287 osg::Image* make3DNoiseImage(int texSize)
288 {
289     osg::Image* image = new osg::Image;
290     image->setImage(texSize, texSize, texSize,
291                     4, GL_RGBA, GL_UNSIGNED_BYTE,
292                     new unsigned char[4 * texSize * texSize * texSize],
293                     osg::Image::USE_NEW_DELETE);
294
295     const int startFrequency = 4;
296     const int numOctaves = 4;
297
298     int f, i, j, k, inc;
299     double ni[3];
300     double inci, incj, inck;
301     int frequency = startFrequency;
302     GLubyte *ptr;
303     double amp = 0.5;
304
305     osg::notify(osg::WARN) << "creating 3D noise texture... ";
306
307     for (f = 0, inc = 0; f < numOctaves; ++f, frequency *= 2, ++inc, amp *= 0.5)
308     {
309         SetNoiseFrequency(frequency);
310         ptr = image->data();
311         ni[0] = ni[1] = ni[2] = 0;
312
313         inci = 1.0 / (texSize / frequency);
314         for (i = 0; i < texSize; ++i, ni[0] += inci)
315         {
316             incj = 1.0 / (texSize / frequency);
317             for (j = 0; j < texSize; ++j, ni[1] += incj)
318             {
319                 inck = 1.0 / (texSize / frequency);
320                 for (k = 0; k < texSize; ++k, ni[2] += inck, ptr += 4)
321                 {
322                     *(ptr+inc) = (GLubyte) (((noise3(ni) + 1.0) * amp) * 128.0);
323                 }
324             }
325         }
326     }
327
328     osg::notify(osg::WARN) << "DONE" << std::endl;
329     return image;
330 }
331
332 class NoiseBuilder : public TextureBuilder
333 {
334 public:
335     Texture* build(Effect* effect, const SGPropertyNode*,
336                    const osgDB::ReaderWriter::Options* options);
337 protected:
338     typedef map<int, ref_ptr<Texture3D> > NoiseMap;
339     NoiseMap _noises;
340 };
341
342 Texture* NoiseBuilder::build(Effect* effect, const SGPropertyNode* props,
343                              const osgDB::ReaderWriter::Options* options)
344 {
345     int texSize = 64;
346     const SGPropertyNode* sizeProp = getEffectPropertyChild(effect, props,
347                                                             "size");
348     if (sizeProp)
349         texSize = sizeProp->getValue<int>();
350     NoiseMap::iterator itr = _noises.find(texSize);
351     if (itr != _noises.end())
352         return itr->second.get();
353     Texture3D* noiseTexture = new osg::Texture3D;
354     noiseTexture->setFilter(osg::Texture3D::MIN_FILTER, osg::Texture3D::LINEAR);
355     noiseTexture->setFilter(osg::Texture3D::MAG_FILTER, osg::Texture3D::LINEAR);
356     noiseTexture->setWrap(osg::Texture3D::WRAP_S, osg::Texture3D::REPEAT);
357     noiseTexture->setWrap(osg::Texture3D::WRAP_T, osg::Texture3D::REPEAT);
358     noiseTexture->setWrap(osg::Texture3D::WRAP_R, osg::Texture3D::REPEAT);
359     noiseTexture->setImage( make3DNoiseImage(texSize) );
360     _noises.insert(make_pair(texSize, noiseTexture));
361     return noiseTexture;
362 }
363
364 namespace
365 {
366 TextureBuilder::Registrar installNoise("noise", new NoiseBuilder);
367 }
368
369 bool makeTextureParameters(SGPropertyNode* paramRoot, const StateSet* ss)
370 {
371     SGPropertyNode* texUnit = makeChild(paramRoot, "texture");
372     const Texture* tex = getStateAttribute<Texture>(0, ss);
373     const Texture2D* texture = dynamic_cast<const Texture2D*>(tex);
374     makeChild(texUnit, "unit")->setValue(0);
375     if (!tex) {
376         makeChild(texUnit, "active")->setValue(false);
377         makeChild(texUnit, "type")->setValue("white");
378         return false;
379     }
380     const Image* image = texture->getImage();
381     string imageName;
382     if (image) {
383         imageName = image->getFileName();
384     } else {
385         makeChild(texUnit, "active")->setValue(false);
386         makeChild(texUnit, "type")->setValue("white");
387         return false;
388     }
389     makeChild(texUnit, "active")->setValue(true);
390     makeChild(texUnit, "type")->setValue("2d");
391     string wrapS = findName(wrapModes, texture->getWrap(Texture::WRAP_S));
392     string wrapT = findName(wrapModes, texture->getWrap(Texture::WRAP_T));
393     string wrapR = findName(wrapModes, texture->getWrap(Texture::WRAP_R));
394     makeChild(texUnit, "image")->setStringValue(imageName);
395     makeChild(texUnit, "wrap-s")->setStringValue(wrapS);
396     makeChild(texUnit, "wrap-t")->setStringValue(wrapT);
397     makeChild(texUnit, "wrap-r")->setStringValue(wrapR);
398     return true;
399 }
400
401 }