]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/mat.cxx
5888b8672d17cdf1e3e49cf5acf320817e19f785
[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/Texture2D>
44 #include <osgDB/ReaderWriter>
45 #include <osgDB/ReadFile>
46 #include <osgDB/Registry>
47 #include <osgDB/FileUtils>
48
49 #include <simgear/debug/logstream.hxx>
50 #include <simgear/misc/sg_path.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
53 #include <simgear/props/props_io.hxx>
54 #include <simgear/scene/model/model.hxx>
55 #include <simgear/scene/util/RenderConstants.hxx>
56 #include <simgear/scene/util/StateAttributeFactory.hxx>
57
58 #include "Effect.hxx"
59 #include "Technique.hxx"
60 #include "Pass.hxx"
61
62 using std::map;
63 using std::string;
64 using namespace simgear;
65
66 \f
67 ////////////////////////////////////////////////////////////////////////
68 // Constructors and destructor.
69 ////////////////////////////////////////////////////////////////////////
70
71 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
72                                              const SGReaderWriterOptions* o)
73     : effect(e), effect_realized(l), options(o)
74 {
75 }
76
77 SGMaterial::_internal_state::_internal_state(Effect *e, const string &t, bool l, 
78                                              const SGReaderWriterOptions* o)
79     : effect(e), effect_realized(l), options(o)
80 {
81     texture_paths.push_back(std::make_pair(t,0));
82 }
83
84 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
85 {
86     texture_paths.push_back(std::make_pair(t,i));
87 }
88
89 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
90                         const SGPropertyNode *props )
91 {
92     init();
93     read_properties( options, props );
94     buildEffectProperties(options);
95 }
96
97 SGMaterial::SGMaterial( const osgDB::ReaderWriter::Options* options,
98                         const SGPropertyNode *props )
99 {
100     osg::ref_ptr<const SGReaderWriterOptions> sgOptions;
101     if (options)
102         sgOptions = new SGReaderWriterOptions(*options);
103     init();
104     read_properties( sgOptions.get(), props );
105     buildEffectProperties(sgOptions.get());
106 }
107
108 SGMaterial::~SGMaterial (void)
109 {
110 }
111
112 \f
113 ////////////////////////////////////////////////////////////////////////
114 // Public methods.
115 ////////////////////////////////////////////////////////////////////////
116
117 void
118 SGMaterial::read_properties(const SGReaderWriterOptions* options,
119                             const SGPropertyNode *props)
120 {
121   std::vector<bool> dds;
122   std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
123   for (unsigned int i = 0; i < textures.size(); i++)
124   {
125     string tname = textures[i]->getStringValue();
126     
127     if (tname.empty()) {
128         tname = "unknown.rgb";
129     }
130     
131     if (tname.rfind(".dds") == (tname.length() - 4)) {
132       dds.push_back(true);
133     } else {
134       dds.push_back(false);      
135     }  
136     
137     SGPath tpath("Textures.high");
138     tpath.append(tname);
139     string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
140     if (fullTexPath.empty()) {
141       tpath = SGPath("Textures");
142       tpath.append(tname);
143       fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
144     }
145     
146     if (!fullTexPath.empty() ) {
147       _internal_state st( NULL, fullTexPath, false, options );
148       _status.push_back( st );
149     }
150   }
151
152   std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
153   for (unsigned int i = 0; i < texturesets.size(); i++)
154   {
155     _internal_state st( NULL, false, options );
156     std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
157     for (unsigned int j = 0; j < textures.size(); j++)
158     {
159       string tname = textures[j]->getStringValue();
160       if (tname.empty()) {
161           tname = "unknown.rgb";
162       }
163       
164       if (j == 0) {
165         if (tname.rfind(".dds") == (tname.length() - 4)) {
166           dds.push_back(true);
167         } else {
168           dds.push_back(false);      
169         }  
170       }
171   
172       SGPath tpath("Textures.high");
173       tpath.append(tname);
174       string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
175       if (fullTexPath.empty()) {
176         tpath = SGPath("Textures");
177         tpath.append(tname);
178         fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
179       }
180       
181       st.add_texture(fullTexPath, textures[j]->getIndex());
182     }
183
184     if (!st.texture_paths.empty() ) {
185       _status.push_back( st );
186     }
187   }
188
189   if (textures.size() == 0 && texturesets.size() == 0) {
190     SGPath tpath("Textures");
191     tpath.append("Terrain");
192     tpath.append("unknown.rgb");
193     _internal_state st( NULL, tpath.str(), true, options );
194     _status.push_back( st );
195   }
196   
197   std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
198   for (unsigned int i = 0; i < masks.size(); i++)
199   {
200     string omname = masks[i]->getStringValue();
201     
202     if (! omname.empty()) {
203       SGPath ompath("Textures.high");
204       ompath.append(omname);
205       string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
206       
207       if (fullMaskPath.empty()) {
208         ompath = SGPath("Textures");
209         ompath.append(omname);
210         fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
211       }    
212       
213       osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
214       if (image->valid())
215       {
216         osg::Texture2D* object_mask = new osg::Texture2D;
217         
218         if (dds[i]) {
219           // Texture is a DDS. This is relevant for the object mask, as DDS
220           // textures have an origin at the bottom left rather than top
221           // left, therefore we flip the object mask vertically.
222           image->flipVertical();          
223         }
224         
225         object_mask->setImage(image);
226         object_mask->setDataVariance(osg::Object::STATIC);
227         object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
228         object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
229         _masks.push_back(object_mask);
230       } 
231     }
232   } 
233
234   xsize = props->getDoubleValue("xsize", 0.0);
235   ysize = props->getDoubleValue("ysize", 0.0);
236   wrapu = props->getBoolValue("wrapu", true);
237   wrapv = props->getBoolValue("wrapv", true);
238   mipmap = props->getBoolValue("mipmap", true);
239   light_coverage = props->getDoubleValue("light-coverage", 0.0);
240   wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
241   tree_height = props->getDoubleValue("tree-height-m", 0.0);
242   tree_width = props->getDoubleValue("tree-width-m", 0.0);
243   tree_range = props->getDoubleValue("tree-range-m", 0.0);
244   tree_varieties = props->getIntValue("tree-varieties", 1);
245
246   const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
247   
248   if (treeTexNode) {
249     string treeTexPath = props->getStringValue("tree-texture");
250     
251     if (! treeTexPath.empty()) {
252       SGPath treePath("Textures.high");
253       treePath.append(treeTexPath);
254       tree_texture = SGModelLib::findDataFile(treePath.str(), options);
255       
256       if (tree_texture.empty()) {
257         treePath = SGPath("Textures");
258         treePath.append(treeTexPath);
259         tree_texture = SGModelLib::findDataFile(treePath.str(), options);
260       }    
261     }
262   }
263   
264   // surface values for use with ground reactions
265   solid = props->getBoolValue("solid", true);
266   friction_factor = props->getDoubleValue("friction-factor", 1.0);
267   rolling_friction = props->getDoubleValue("rolling-friction", 0.02);
268   bumpiness = props->getDoubleValue("bumpiness", 0.0);
269   load_resistance = props->getDoubleValue("load-resistance", 1e30);
270
271   // Taken from default values as used in ac3d
272   ambient[0] = props->getDoubleValue("ambient/r", 0.2);
273   ambient[1] = props->getDoubleValue("ambient/g", 0.2);
274   ambient[2] = props->getDoubleValue("ambient/b", 0.2);
275   ambient[3] = props->getDoubleValue("ambient/a", 1.0);
276
277   diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
278   diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
279   diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
280   diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
281
282   specular[0] = props->getDoubleValue("specular/r", 0.0);
283   specular[1] = props->getDoubleValue("specular/g", 0.0);
284   specular[2] = props->getDoubleValue("specular/b", 0.0);
285   specular[3] = props->getDoubleValue("specular/a", 1.0);
286
287   emission[0] = props->getDoubleValue("emissive/r", 0.0);
288   emission[1] = props->getDoubleValue("emissive/g", 0.0);
289   emission[2] = props->getDoubleValue("emissive/b", 0.0);
290   emission[3] = props->getDoubleValue("emissive/a", 1.0);
291
292   shininess = props->getDoubleValue("shininess", 1.0);
293
294   if (props->hasChild("effect"))
295       effect = props->getStringValue("effect");
296   
297   std::vector<SGPropertyNode_ptr> object_group_nodes =
298     ((SGPropertyNode *)props)->getChildren("object-group");
299   for (unsigned int i = 0; i < object_group_nodes.size(); i++)
300     object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
301
302   // read glyph table for taxi-/runway-signs
303   std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
304   for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
305     const char *name = glyph_nodes[i]->getStringValue("name");
306     if (name)
307       glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
308   }
309 }
310
311
312 \f
313 ////////////////////////////////////////////////////////////////////////
314 // Private methods.
315 ////////////////////////////////////////////////////////////////////////
316
317 void 
318 SGMaterial::init ()
319 {
320     _status.clear();
321     xsize = 0;
322     ysize = 0;
323     wrapu = true;
324     wrapv = true;
325
326     mipmap = true;
327     light_coverage = 0.0;
328
329     solid = true;
330     friction_factor = 1;
331     rolling_friction = 0.02;
332     bumpiness = 0;
333     load_resistance = 1e30;
334
335     shininess = 1.0;
336     for (int i = 0; i < 4; i++) {
337         ambient[i]  = (i < 3) ? 0.2 : 1.0;
338         specular[i] = (i < 3) ? 0.0 : 1.0;
339         diffuse[i]  = (i < 3) ? 0.8 : 1.0;
340         emission[i] = (i < 3) ? 0.0 : 1.0;
341     }
342     effect = "Effects/terrain-default";
343 }
344
345 Effect* SGMaterial::get_effect(int i)
346 {    
347     if(!_status[i].effect_realized) {
348         _status[i].effect->realizeTechniques(_status[i].options.get());
349         _status[i].effect_realized = true;
350     }
351     return _status[i].effect.get();
352 }
353
354 Effect* SGMaterial::get_effect(SGTexturedTriangleBin triangleBin)
355 {
356     if (_status.size() == 0) {
357         SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
358         return 0;
359     }
360     
361     int i = triangleBin.getTextureIndex() % _status.size();
362     return get_effect(i);
363 }
364
365 Effect* SGMaterial::get_effect()
366 {
367     return get_effect(0);
368 }
369
370
371 osg::Texture2D* SGMaterial::get_object_mask(SGTexturedTriangleBin triangleBin)
372 {
373     if (_status.size() == 0) {
374         SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
375         return 0;
376     }
377     
378     // Note that the object mask is closely linked to the texture/effect
379     // so we index based on the texture index, 
380     unsigned int i = triangleBin.getTextureIndex() % _status.size();
381     if (i < _masks.size()) {
382         return _masks[i];      
383     } else {
384         return 0;      
385     }
386 }
387
388 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
389 {
390     using namespace osg;
391     ref_ptr<SGReaderWriterOptions> xmlOptions;
392     if (options)
393         xmlOptions = new SGReaderWriterOptions(*options);
394     ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
395     SGPropertyNode_ptr propRoot = new SGPropertyNode();
396     makeChild(propRoot, "inherits-from")->setStringValue(effect);
397     SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
398     SGPropertyNode* materialProp = makeChild(paramProp, "material");
399     makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));    
400     makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
401     makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
402     makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
403     makeChild(materialProp, "shininess")->setFloatValue(shininess);
404     if (ambient[3] < 1 || diffuse[3] < 1 ||
405         specular[3] < 1 || emission[3] < 1) {
406         makeChild(paramProp, "transparent")->setBoolValue(true);
407         SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
408         makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
409         makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
410     }
411     BOOST_FOREACH(_internal_state& matState, _status)
412     {
413         SGPropertyNode_ptr effectProp = new SGPropertyNode();
414         copyProperties(propRoot, effectProp);
415         SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
416         for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
417             SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
418             makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
419             makeChild(texProp, "filter")
420                 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
421             makeChild(texProp, "wrap-s")
422                 ->setStringValue(wrapu ? "repeat" : "clamp");
423             makeChild(texProp, "wrap-t")
424                 ->setStringValue(wrapv ? "repeat" : "clamp");
425         }
426         makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
427         makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
428         makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
429         makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
430
431         matState.effect = makeEffect(effectProp, false, xmlOptions.get());
432         matState.effect->setUserData(user.get());
433     }
434 }
435
436 SGMaterialGlyph* SGMaterial::get_glyph (const string& name) const
437 {
438   map<string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
439   it = glyphs.find(name);
440   if (it == glyphs.end())
441     return 0;
442
443   return it->second;
444 }
445
446 \f
447 ////////////////////////////////////////////////////////////////////////
448 // SGMaterialGlyph.
449 ////////////////////////////////////////////////////////////////////////
450
451 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
452     _left(p->getDoubleValue("left", 0.0)),
453     _right(p->getDoubleValue("right", 1.0))
454 {
455 }
456
457 void
458 SGSetTextureFilter( int max) {
459         SGSceneFeatures::instance()->setTextureFilter( max);
460 }
461
462 int
463 SGGetTextureFilter() {
464         return SGSceneFeatures::instance()->getTextureFilter();
465 }