]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/mat.cxx
582571f3096d734e58558fb077520530c44f32b6
[simgear.git] / simgear / scene / material / mat.cxx
1 // mat.cxx -- class to handle material properties
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2000  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <simgear_config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <string.h>
31 #include <map>
32 #include <vector>
33 #include <string>
34
35 #include <boost/foreach.hpp>
36 #include "mat.hxx"
37
38 #include <osg/CullFace>
39 #include <osg/Material>
40 #include <osg/ShadeModel>
41 #include <osg/StateSet>
42 #include <osg/TexEnv>
43 #include <osg/Texture>
44 #include <osg/Texture2D>
45 #include <osgDB/ReaderWriter>
46 #include <osgDB/ReadFile>
47 #include <osgDB/Registry>
48 #include <osgDB/FileUtils>
49
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/misc/sg_path.hxx>
52 #include <simgear/misc/sgstream.hxx>
53 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
54 #include <simgear/props/props_io.hxx>
55 #include <simgear/scene/model/model.hxx>
56 #include <simgear/scene/util/RenderConstants.hxx>
57 #include <simgear/scene/util/StateAttributeFactory.hxx>
58
59 #include "Effect.hxx"
60 #include "Technique.hxx"
61 #include "Pass.hxx"
62
63 using std::map;
64 using std::string;
65 using namespace simgear;
66
67 \f
68 ////////////////////////////////////////////////////////////////////////
69 // Constructors and destructor.
70 ////////////////////////////////////////////////////////////////////////
71
72 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
73                                              const SGReaderWriterOptions* o)
74     : effect(e), effect_realized(l), options(o)
75 {
76 }
77
78 SGMaterial::_internal_state::_internal_state(Effect *e, const string &t, bool l, 
79                                              const SGReaderWriterOptions* o)
80     : effect(e), effect_realized(l), options(o)
81 {
82     texture_paths.push_back(std::make_pair(t,0));
83 }
84
85 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
86 {
87     texture_paths.push_back(std::make_pair(t,i));
88 }
89
90 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
91                         const SGPropertyNode *props,
92                         SGPropertyNode *prop_root )
93 {
94     init();
95     read_properties( options, props, prop_root );
96     buildEffectProperties(options);
97 }
98
99 SGMaterial::SGMaterial( const osgDB::Options* options,
100                         const SGPropertyNode *props, 
101                         SGPropertyNode *prop_root)
102 {
103     osg::ref_ptr<SGReaderWriterOptions> opt;
104     opt = SGReaderWriterOptions::copyOrCreate(options);
105     init();
106     read_properties(opt.get(), props, prop_root);
107     buildEffectProperties(opt.get());
108 }
109
110 SGMaterial::~SGMaterial (void)
111 {
112 }
113
114 \f
115 ////////////////////////////////////////////////////////////////////////
116 // Public methods.
117 ////////////////////////////////////////////////////////////////////////
118
119 void
120 SGMaterial::read_properties(const SGReaderWriterOptions* options,
121                             const SGPropertyNode *props,
122                             SGPropertyNode *prop_root)
123 {
124     std::vector<bool> dds;
125     std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
126     for (unsigned int i = 0; i < textures.size(); i++)
127     {
128         string tname = textures[i]->getStringValue();
129
130         if (tname.empty()) {
131             tname = "unknown.rgb";
132         }
133
134         SGPath tpath("Textures.high");
135         tpath.append(tname);
136         string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
137         if (fullTexPath.empty()) {
138             tpath = SGPath("Textures");
139             tpath.append(tname);
140             fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
141             if (fullTexPath.empty()) {
142                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
143                         << tname << "\" in Textures or Textures.high folders.");
144             }
145         }
146
147         if (tpath.lower_extension() == "dds") {
148             dds.push_back(true);
149         } else {
150             dds.push_back(false);
151         }
152
153         if (!fullTexPath.empty() ) {
154             _internal_state st( NULL, fullTexPath, false, options );
155             _status.push_back( st );
156         }
157     }
158
159     std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
160     for (unsigned int i = 0; i < texturesets.size(); i++)
161     {
162         _internal_state st( NULL, false, options );
163         std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
164         for (unsigned int j = 0; j < textures.size(); j++)
165         {
166             string tname = textures[j]->getStringValue();
167             if (tname.empty()) {
168                 tname = "unknown.rgb";
169             }
170
171             SGPath tpath("Textures.high");
172             tpath.append(tname);
173             string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
174             if (fullTexPath.empty()) {
175                 tpath = SGPath("Textures");
176                 tpath.append(tname);
177                 fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
178                 if (fullTexPath.empty() ) {
179                     SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
180                             << tname << "\" in Textures or Textures.high folders.");
181                 }
182             }
183
184             if (j == 0) {
185                 if (tpath.lower_extension() == "dds") {
186                     dds.push_back(true);
187                 } else {
188                     dds.push_back(false);
189                 }
190             }
191
192             st.add_texture(fullTexPath, textures[j]->getIndex());
193         }
194
195         if (!st.texture_paths.empty() ) {
196             _status.push_back( st );
197         }
198     }
199
200     if (textures.size() == 0 && texturesets.size() == 0) {
201         SGPath tpath("Textures");
202         tpath.append("Terrain");
203         tpath.append("unknown.rgb");
204         _internal_state st( NULL, tpath.str(), true, options );
205         _status.push_back( st );
206     }
207     
208     std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
209     for (unsigned int i = 0; i < masks.size(); i++)
210     {
211         string omname = masks[i]->getStringValue();
212
213         if (! omname.empty()) {
214             SGPath ompath("Textures.high");
215             ompath.append(omname);
216             string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
217
218             if (fullMaskPath.empty()) {
219                 ompath = SGPath("Textures");
220                 ompath.append(omname);
221                 fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
222             }
223
224             if (fullMaskPath.empty()) {
225                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
226                         << omname << "\" in Textures or Textures.high folders.");
227             }
228             else
229             {
230                 osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
231                 if (image && image->valid())
232                 {
233                     osg::Texture2D* object_mask = new osg::Texture2D;
234
235                     bool dds_mask = (ompath.lower_extension() == "dds");
236
237                     if (dds[i] != dds_mask) {
238                         // Texture format does not match mask format. This is relevant for
239                         // the object mask, as DDS textures have an origin at the bottom
240                         // left rather than top left, therefore we flip the object mask
241                         // vertically.
242                         image->flipVertical();
243                     }
244
245                     object_mask->setImage(image);
246
247                     // We force the filtering to be nearest, as the red channel (rotation)
248                     // in particular, doesn't make sense to be interpolated between pixels.
249                     object_mask->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
250                     object_mask->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
251
252                     object_mask->setDataVariance(osg::Object::STATIC);
253                     object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
254                     object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
255                     _masks.push_back(object_mask);
256                 }
257             }
258         }
259     }
260
261     xsize = props->getDoubleValue("xsize", 0.0);
262     ysize = props->getDoubleValue("ysize", 0.0);
263     wrapu = props->getBoolValue("wrapu", true);
264     wrapv = props->getBoolValue("wrapv", true);
265     mipmap = props->getBoolValue("mipmap", true);
266     light_coverage = props->getDoubleValue("light-coverage", 0.0);
267     wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
268     tree_height = props->getDoubleValue("tree-height-m", 0.0);
269     tree_width = props->getDoubleValue("tree-width-m", 0.0);
270     tree_range = props->getDoubleValue("tree-range-m", 0.0);
271     tree_varieties = props->getIntValue("tree-varieties", 1);
272
273     const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
274     
275     if (treeTexNode) {
276         string treeTexPath = props->getStringValue("tree-texture");
277
278         if (! treeTexPath.empty()) {
279             SGPath treePath("Textures.high");
280             treePath.append(treeTexPath);
281             tree_texture = SGModelLib::findDataFile(treePath.str(), options);
282
283             if (tree_texture.empty()) {
284                 treePath = SGPath("Textures");
285                 treePath.append(treeTexPath);
286                 tree_texture = SGModelLib::findDataFile(treePath.str(), options);
287             }
288         }
289     }
290
291     // surface values for use with ground reactions
292     solid = props->getBoolValue("solid", true);
293     friction_factor = props->getDoubleValue("friction-factor", 1.0);
294     rolling_friction = props->getDoubleValue("rolling-friction", 0.02);
295     bumpiness = props->getDoubleValue("bumpiness", 0.0);
296     load_resistance = props->getDoubleValue("load-resistance", 1e30);
297
298     // Taken from default values as used in ac3d
299     ambient[0] = props->getDoubleValue("ambient/r", 0.2);
300     ambient[1] = props->getDoubleValue("ambient/g", 0.2);
301     ambient[2] = props->getDoubleValue("ambient/b", 0.2);
302     ambient[3] = props->getDoubleValue("ambient/a", 1.0);
303
304     diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
305     diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
306     diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
307     diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
308
309     specular[0] = props->getDoubleValue("specular/r", 0.0);
310     specular[1] = props->getDoubleValue("specular/g", 0.0);
311     specular[2] = props->getDoubleValue("specular/b", 0.0);
312     specular[3] = props->getDoubleValue("specular/a", 1.0);
313
314     emission[0] = props->getDoubleValue("emissive/r", 0.0);
315     emission[1] = props->getDoubleValue("emissive/g", 0.0);
316     emission[2] = props->getDoubleValue("emissive/b", 0.0);
317     emission[3] = props->getDoubleValue("emissive/a", 1.0);
318
319     shininess = props->getDoubleValue("shininess", 1.0);
320
321     if (props->hasChild("effect"))
322         effect = props->getStringValue("effect");
323
324     std::vector<SGPropertyNode_ptr> object_group_nodes =
325             ((SGPropertyNode *)props)->getChildren("object-group");
326     for (unsigned int i = 0; i < object_group_nodes.size(); i++)
327         object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
328
329     // read glyph table for taxi-/runway-signs
330     std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
331     for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
332         const char *name = glyph_nodes[i]->getStringValue("name");
333         if (name)
334             glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
335     }
336
337     // Read conditions node
338     const SGPropertyNode *conditionNode = props->getChild("condition");
339     if (conditionNode) {
340         condition = sgReadCondition(prop_root, conditionNode);
341     }
342 }
343
344
345 \f
346 ////////////////////////////////////////////////////////////////////////
347 // Private methods.
348 ////////////////////////////////////////////////////////////////////////
349
350 void 
351 SGMaterial::init ()
352 {
353     _status.clear();
354     xsize = 0;
355     ysize = 0;
356     wrapu = true;
357     wrapv = true;
358
359     mipmap = true;
360     light_coverage = 0.0;
361
362     solid = true;
363     friction_factor = 1;
364     rolling_friction = 0.02;
365     bumpiness = 0;
366     load_resistance = 1e30;
367
368     shininess = 1.0;
369     for (int i = 0; i < 4; i++) {
370         ambient[i]  = (i < 3) ? 0.2 : 1.0;
371         specular[i] = (i < 3) ? 0.0 : 1.0;
372         diffuse[i]  = (i < 3) ? 0.8 : 1.0;
373         emission[i] = (i < 3) ? 0.0 : 1.0;
374     }
375     effect = "Effects/terrain-default";
376 }
377
378 Effect* SGMaterial::get_effect(int i)
379 {    
380     if(!_status[i].effect_realized) {
381         _status[i].effect->realizeTechniques(_status[i].options.get());
382         _status[i].effect_realized = true;
383     }
384     return _status[i].effect.get();
385 }
386
387 Effect* SGMaterial::get_effect(SGTexturedTriangleBin triangleBin)
388 {
389     if (_status.size() == 0) {
390         SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
391         return 0;
392     }
393     
394     int i = triangleBin.getTextureIndex() % _status.size();
395     return get_effect(i);
396 }
397
398 Effect* SGMaterial::get_effect()
399 {
400     return get_effect(0);
401 }
402
403
404 osg::Texture2D* SGMaterial::get_object_mask(SGTexturedTriangleBin triangleBin)
405 {
406     if (_status.size() == 0) {
407         SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
408         return 0;
409     }
410     
411     // Note that the object mask is closely linked to the texture/effect
412     // so we index based on the texture index, 
413     unsigned int i = triangleBin.getTextureIndex() % _status.size();
414     if (i < _masks.size()) {
415         return _masks[i];
416     } else {
417         return 0;
418     }
419 }
420
421 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
422 {
423     using namespace osg;
424     ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
425     SGPropertyNode_ptr propRoot = new SGPropertyNode();
426     makeChild(propRoot, "inherits-from")->setStringValue(effect);
427     SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
428     SGPropertyNode* materialProp = makeChild(paramProp, "material");
429     makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));    
430     makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
431     makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
432     makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
433     makeChild(materialProp, "shininess")->setFloatValue(shininess);
434     if (ambient[3] < 1 || diffuse[3] < 1 ||
435         specular[3] < 1 || emission[3] < 1) {
436         makeChild(paramProp, "transparent")->setBoolValue(true);
437         SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
438         makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
439         makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
440     }
441     BOOST_FOREACH(_internal_state& matState, _status)
442     {
443         SGPropertyNode_ptr effectProp = new SGPropertyNode();
444         copyProperties(propRoot, effectProp);
445         SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
446         for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
447             SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
448             makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
449             makeChild(texProp, "filter")
450                 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
451             makeChild(texProp, "wrap-s")
452                 ->setStringValue(wrapu ? "repeat" : "clamp");
453             makeChild(texProp, "wrap-t")
454                 ->setStringValue(wrapv ? "repeat" : "clamp");
455         }
456         makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
457         makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
458         makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
459         makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
460
461         matState.effect = makeEffect(effectProp, false, options);
462         matState.effect->setUserData(user.get());
463     }
464 }
465
466 SGMaterialGlyph* SGMaterial::get_glyph (const string& name) const
467 {
468     map<string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
469     it = glyphs.find(name);
470     if (it == glyphs.end())
471         return 0;
472
473     return it->second;
474 }
475
476 \f
477 ////////////////////////////////////////////////////////////////////////
478 // SGMaterialGlyph.
479 ////////////////////////////////////////////////////////////////////////
480
481 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
482     _left(p->getDoubleValue("left", 0.0)),
483     _right(p->getDoubleValue("right", 1.0))
484 {
485 }
486
487 void
488 SGSetTextureFilter( int max) {
489     SGSceneFeatures::instance()->setTextureFilter( max);
490 }
491
492 int
493 SGGetTextureFilter() {
494     return SGSceneFeatures::instance()->getTextureFilter();
495 }