]> git.mxchange.org Git - simgear.git/blob - simgear/scene/material/mat.cxx
Race-condition fix in get_effect.
[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/threads/SGGuard.hxx>
54
55 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
56 #include <simgear/props/props_io.hxx>
57 #include <simgear/props/vectorPropTemplates.hxx>
58 #include <simgear/scene/model/model.hxx>
59 #include <simgear/scene/material/matmodel.hxx>
60 #include <simgear/scene/util/RenderConstants.hxx>
61 #include <simgear/scene/util/StateAttributeFactory.hxx>
62 #include <simgear/props/condition.hxx>
63 #include <simgear/scene/util/SGSceneFeatures.hxx>
64 #include <simgear/scene/tgdb/SGTexturedTriangleBin.hxx>
65
66 #include "Effect.hxx"
67 #include "Technique.hxx"
68 #include "Pass.hxx"
69
70 using std::map;
71 using std::string;
72 using namespace simgear;
73
74 \f
75 ////////////////////////////////////////////////////////////////////////
76 // Constructors and destructor.
77 ////////////////////////////////////////////////////////////////////////
78
79 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
80                                              const SGReaderWriterOptions* o)
81     : effect(e), effect_realized(l), options(o)
82 {
83 }
84
85 SGMaterial::_internal_state::_internal_state(Effect *e, const string &t, bool l, 
86                                              const SGReaderWriterOptions* o)
87     : effect(e), effect_realized(l), options(o)
88 {
89     texture_paths.push_back(std::make_pair(t,0));
90 }
91
92 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
93 {
94     texture_paths.push_back(std::make_pair(t,i));
95 }
96
97 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
98                         const SGPropertyNode *props,
99                         SGPropertyNode *prop_root )
100 {
101     init();
102     read_properties( options, props, prop_root );
103     buildEffectProperties(options);
104 }
105
106 SGMaterial::SGMaterial( const osgDB::Options* options,
107                         const SGPropertyNode *props, 
108                         SGPropertyNode *prop_root)
109 {
110     osg::ref_ptr<SGReaderWriterOptions> opt;
111     opt = SGReaderWriterOptions::copyOrCreate(options);
112     init();
113     read_properties(opt.get(), props, prop_root);
114     buildEffectProperties(opt.get());
115 }
116
117 SGMaterial::~SGMaterial (void)
118 {
119 }
120
121 \f
122 ////////////////////////////////////////////////////////////////////////
123 // Public methods.
124 ////////////////////////////////////////////////////////////////////////
125
126 void
127 SGMaterial::read_properties(const SGReaderWriterOptions* options,
128                             const SGPropertyNode *props,
129                             SGPropertyNode *prop_root)
130 {
131     std::vector<bool> dds;
132     std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
133     for (unsigned int i = 0; i < textures.size(); i++)
134     {
135         string tname = textures[i]->getStringValue();
136
137         if (tname.empty()) {
138             tname = "unknown.rgb";
139         }
140
141         SGPath tpath("Textures.high");
142         tpath.append(tname);
143         string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
144         if (fullTexPath.empty()) {
145             tpath.set("Textures");
146             tpath.append(tname);
147             fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
148             if (fullTexPath.empty()) {
149                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
150                         << tname << "\" in Textures or Textures.high folders.");
151             }
152         }
153
154         if (tpath.lower_extension() == "dds") {
155             dds.push_back(true);
156         } else {
157             dds.push_back(false);
158         }
159
160         if (!fullTexPath.empty() ) {
161             _internal_state st( NULL, fullTexPath, false, options );
162             _status.push_back( st );
163         }
164     }
165
166     std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
167     for (unsigned int i = 0; i < texturesets.size(); i++)
168     {
169         _internal_state st( NULL, false, options );
170         std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
171         for (unsigned int j = 0; j < textures.size(); j++)
172         {
173             string tname = textures[j]->getStringValue();
174             if (tname.empty()) {
175                 tname = "unknown.rgb";
176             }
177
178             SGPath tpath("Textures.high");
179             tpath.append(tname);
180             string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
181             if (fullTexPath.empty()) {
182                 tpath.set("Textures");
183                 tpath.append(tname);
184                 fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
185                 if (fullTexPath.empty() ) {
186                     SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
187                             << tname << "\" in Textures or Textures.high folders.");
188                 }
189             }
190
191             if (j == 0) {
192                 if (tpath.lower_extension() == "dds") {
193                     dds.push_back(true);
194                 } else {
195                     dds.push_back(false);
196                 }
197             }
198
199             st.add_texture(fullTexPath, textures[j]->getIndex());
200         }
201
202         if (!st.texture_paths.empty() ) {
203             _status.push_back( st );
204         }
205     }
206
207     if (textures.empty() && texturesets.empty()) {
208         SGPath tpath("Textures");
209         tpath.append("Terrain");
210         tpath.append("unknown.rgb");
211         _internal_state st( NULL, tpath.str(), true, options );
212         _status.push_back( st );
213     }
214     
215     std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
216     for (unsigned int i = 0; i < masks.size(); i++)
217     {
218         string omname = masks[i]->getStringValue();
219
220         if (! omname.empty()) {
221             SGPath ompath("Textures.high");
222             ompath.append(omname);
223             string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
224
225             if (fullMaskPath.empty()) {
226                 ompath.set("Textures");
227                 ompath.append(omname);
228                 fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
229             }
230
231             if (fullMaskPath.empty()) {
232                 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
233                         << omname << "\" in Textures or Textures.high folders.");
234             }
235             else
236             {
237                 osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
238                 if (image && image->valid())
239                 {
240                     osg::Texture2D* object_mask = new osg::Texture2D;
241
242                     bool dds_mask = (ompath.lower_extension() == "dds");
243
244                     if (i < dds.size() && dds[i] != dds_mask) {
245                         // Texture format does not match mask format. This is relevant for
246                         // the object mask, as DDS textures have an origin at the bottom
247                         // left rather than top left. Therefore we flip a copy of the image
248                         // (otherwise a second reference to the object mask would flip it
249                         // back!).                
250                         SG_LOG(SG_GENERAL, SG_DEBUG, "Flipping object mask" << omname);  
251                         image = (osg::Image* ) image->clone(osg::CopyOp::SHALLOW_COPY);
252                         image->flipVertical();
253                     }
254
255                     object_mask->setImage(image);
256
257                     // We force the filtering to be nearest, as the red channel (rotation)
258                     // in particular, doesn't make sense to be interpolated between pixels.
259                     object_mask->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
260                     object_mask->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
261
262                     object_mask->setDataVariance(osg::Object::STATIC);
263                     object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
264                     object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
265                     _masks.push_back(object_mask);
266                 }
267             }
268         }
269     }
270
271     xsize = props->getDoubleValue("xsize", 0.0);
272     ysize = props->getDoubleValue("ysize", 0.0);
273     wrapu = props->getBoolValue("wrapu", true);
274     wrapv = props->getBoolValue("wrapv", true);
275     mipmap = props->getBoolValue("mipmap", true);
276     light_coverage = props->getDoubleValue("light-coverage", 0.0);
277     
278     // Building properties
279     building_coverage = props->getDoubleValue("building-coverage", 0.0);
280     building_spacing = props->getDoubleValue("building-spacing-m", 5.0);
281     
282     string bt = props->getStringValue("building-texture", "Textures/buildings.png");
283     building_texture = SGModelLib::findDataFile(bt, options);    
284     
285     if (building_texture.empty()) {
286         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
287     }
288     
289     bt = props->getStringValue("building-lightmap", "Textures/buildings-lightmap.png");
290     building_lightmap = SGModelLib::findDataFile(bt, options);    
291     
292     if (building_lightmap.empty()) {
293         SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
294     }    
295             
296     building_small_ratio = props->getDoubleValue("building-small-ratio", 0.8);
297     building_medium_ratio = props->getDoubleValue("building-medium-ratio", 0.15);
298     building_large_ratio =  props->getDoubleValue("building-large-ratio", 0.05);
299     
300     building_small_pitch =  props->getDoubleValue("building-small-pitch", 0.8);
301     building_medium_pitch =  props->getDoubleValue("building-medium-pitch", 0.2);
302     building_large_pitch =  props->getDoubleValue("building-large-pitch", 0.1);
303
304     building_small_min_floors = props->getIntValue("building-small-min-floors", 1);
305     building_small_max_floors = props->getIntValue("building-small-max-floors", 3);
306     building_medium_min_floors = props->getIntValue("building-medium-min-floors", 3);
307     building_medium_max_floors = props->getIntValue("building-medium-max-floors", 8);
308     building_large_min_floors = props->getIntValue("building-large-min-floors", 5);
309     building_large_max_floors = props->getIntValue("building-large-max-floors", 20);
310     
311     building_small_min_width = props->getFloatValue("building-small-min-width-m", 15.0);
312     building_small_max_width = props->getFloatValue("building-small-max-width-m", 60.0);
313     building_small_min_depth = props->getFloatValue("building-small-min-depth-m", 10.0);
314     building_small_max_depth = props->getFloatValue("building-small-max-depth-m", 20.0);
315     
316     building_medium_min_width = props->getFloatValue("building-medium-min-width-m", 25.0);
317     building_medium_max_width = props->getFloatValue("building-medium-max-width-m", 50.0);
318     building_medium_min_depth = props->getFloatValue("building-medium-min-depth-m", 20.0);
319     building_medium_max_depth = props->getFloatValue("building-medium-max-depth-m", 50.0);
320     
321     building_large_min_width = props->getFloatValue("building-large-min-width-m", 50.0);
322     building_large_max_width = props->getFloatValue("building-large-max-width-m", 75.0);
323     building_large_min_depth = props->getFloatValue("building-large-min-depth-m", 50.0);
324     building_large_max_depth = props->getFloatValue("building-large-max-depth-m", 75.0);
325
326     building_range = props->getDoubleValue("building-range-m", 10000.0);
327     
328     cos_object_max_density_slope_angle  = cos(props->getFloatValue("object-max-density-angle-deg", 20.0) * osg::PI/180.0);
329     cos_object_zero_density_slope_angle = cos(props->getFloatValue("object-zero-density-angle-deg", 30.0) * osg::PI/180.0);
330         
331     // Random vegetation properties
332     wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
333     tree_height = props->getDoubleValue("tree-height-m", 0.0);
334     tree_width = props->getDoubleValue("tree-width-m", 0.0);
335     tree_range = props->getDoubleValue("tree-range-m", 0.0);
336     tree_varieties = props->getIntValue("tree-varieties", 1);
337     cos_tree_max_density_slope_angle  = cos(props->getFloatValue("tree-max-density-angle-deg", 30.0) * osg::PI/180.0);
338     cos_tree_zero_density_slope_angle = cos(props->getFloatValue("tree-zero-density-angle-deg", 45.0) * osg::PI/180.0);
339
340     const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
341     
342     if (treeTexNode) {
343         string treeTexPath = props->getStringValue("tree-texture");
344
345         if (! treeTexPath.empty()) {
346             SGPath treePath("Textures.high");
347             treePath.append(treeTexPath);
348             tree_texture = SGModelLib::findDataFile(treePath.str(), options);
349
350             if (tree_texture.empty()) {
351                 treePath.set("Textures");
352                 treePath.append(treeTexPath);
353                 tree_texture = SGModelLib::findDataFile(treePath.str(), options);
354             }
355         }
356     }
357
358     // surface values for use with ground reactions
359     _solid = props->getBoolValue("solid", _solid);
360     _friction_factor = props->getDoubleValue("friction-factor", _friction_factor);
361     _rolling_friction = props->getDoubleValue("rolling-friction", _rolling_friction);
362     _bumpiness = props->getDoubleValue("bumpiness", _bumpiness);
363     _load_resistance = props->getDoubleValue("load-resistance", _load_resistance);
364
365     // Taken from default values as used in ac3d
366     ambient[0] = props->getDoubleValue("ambient/r", 0.2);
367     ambient[1] = props->getDoubleValue("ambient/g", 0.2);
368     ambient[2] = props->getDoubleValue("ambient/b", 0.2);
369     ambient[3] = props->getDoubleValue("ambient/a", 1.0);
370
371     diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
372     diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
373     diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
374     diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
375
376     specular[0] = props->getDoubleValue("specular/r", 0.0);
377     specular[1] = props->getDoubleValue("specular/g", 0.0);
378     specular[2] = props->getDoubleValue("specular/b", 0.0);
379     specular[3] = props->getDoubleValue("specular/a", 1.0);
380
381     emission[0] = props->getDoubleValue("emissive/r", 0.0);
382     emission[1] = props->getDoubleValue("emissive/g", 0.0);
383     emission[2] = props->getDoubleValue("emissive/b", 0.0);
384     emission[3] = props->getDoubleValue("emissive/a", 1.0);
385
386     shininess = props->getDoubleValue("shininess", 1.0);
387
388     if (props->hasChild("effect"))
389         effect = props->getStringValue("effect");
390
391     std::vector<SGPropertyNode_ptr> object_group_nodes =
392             ((SGPropertyNode *)props)->getChildren("object-group");
393     for (unsigned int i = 0; i < object_group_nodes.size(); i++)
394         object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
395
396     // read glyph table for taxi-/runway-signs
397     std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
398     for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
399         const char *name = glyph_nodes[i]->getStringValue("name");
400         if (name)
401             glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
402     }
403     
404     // Read parameters entry, which is passed into the effect
405     if (props->hasChild("parameters")) {
406         parameters = props->getChild("parameters");
407     } else {
408         parameters = new SGPropertyNode();
409     }
410
411     // Read conditions node
412     const SGPropertyNode *conditionNode = props->getChild("condition");
413     if (conditionNode) {
414         condition = sgReadCondition(prop_root, conditionNode);
415     }
416 }
417
418
419 \f
420 ////////////////////////////////////////////////////////////////////////
421 // Private methods.
422 ////////////////////////////////////////////////////////////////////////
423
424 void 
425 SGMaterial::init ()
426 {
427     _status.clear();
428     xsize = 0;
429     ysize = 0;
430     wrapu = true;
431     wrapv = true;
432
433     mipmap = true;
434     light_coverage = 0.0;
435     building_coverage = 0.0;
436
437     shininess = 1.0;
438     for (int i = 0; i < 4; i++) {
439         ambient[i]  = (i < 3) ? 0.2 : 1.0;
440         specular[i] = (i < 3) ? 0.0 : 1.0;
441         diffuse[i]  = (i < 3) ? 0.8 : 1.0;
442         emission[i] = (i < 3) ? 0.0 : 1.0;
443     }
444     effect = "Effects/terrain-default";
445 }
446
447 Effect* SGMaterial::get_effect(int i)
448 {    
449     if(!_status[i].effect_realized) {
450         if (!_status[i].effect.valid())
451             return 0;
452         _status[i].effect->realizeTechniques(_status[i].options.get());
453         _status[i].effect_realized = true;
454     }
455     return _status[i].effect.get();
456 }
457
458 Effect* SGMaterial::get_effect(const SGTexturedTriangleBin& triangleBin)
459 {
460     SGGuard<SGMutex> g(_lock);
461     if (_status.empty()) {
462         SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
463         return 0;
464     }
465     
466     int i = triangleBin.getTextureIndex() % _status.size();
467     return get_effect(i);
468 }
469
470 Effect* SGMaterial::get_effect()
471 {
472     SGGuard<SGMutex> g(_lock);
473     return get_effect(0);
474 }
475
476
477 osg::Texture2D* SGMaterial::get_object_mask(const SGTexturedTriangleBin& triangleBin)
478 {
479     if (_status.empty()) {
480         SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
481         return 0;
482     }
483     
484     // Note that the object mask is closely linked to the texture/effect
485     // so we index based on the texture index, 
486     unsigned int i = triangleBin.getTextureIndex() % _status.size();
487     if (i < _masks.size()) {
488         return _masks[i];
489     } else {
490         return 0;
491     }
492 }
493
494 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
495 {
496     using namespace osg;
497     ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
498     SGPropertyNode_ptr propRoot = new SGPropertyNode();
499     makeChild(propRoot, "inherits-from")->setStringValue(effect);
500     
501     SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
502     copyProperties(parameters, paramProp);
503     
504     SGPropertyNode* materialProp = makeChild(paramProp, "material");
505     makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));
506     makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
507     makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
508     makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
509     makeChild(materialProp, "shininess")->setFloatValue(shininess);
510     if (ambient[3] < 1 || diffuse[3] < 1 ||
511         specular[3] < 1 || emission[3] < 1) {
512         makeChild(paramProp, "transparent")->setBoolValue(true);
513         SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
514         makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
515         makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
516     }
517     BOOST_FOREACH(_internal_state& matState, _status)
518     {
519         SGPropertyNode_ptr effectProp = new SGPropertyNode();
520         copyProperties(propRoot, effectProp);
521         SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
522         for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
523             SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
524             makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
525             makeChild(texProp, "filter")
526                 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
527             makeChild(texProp, "wrap-s")
528                 ->setStringValue(wrapu ? "repeat" : "clamp-to-edge");
529             makeChild(texProp, "wrap-t")
530                 ->setStringValue(wrapv ? "repeat" : "clamp-to-edge");
531         }
532         makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
533         makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
534         makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
535         makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
536
537         matState.effect = makeEffect(effectProp, false, options);
538         if (matState.effect.valid())
539             matState.effect->setUserData(user.get());
540     }
541 }
542
543 SGMaterialGlyph* SGMaterial::get_glyph (const string& name) const
544 {
545     map<string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
546     it = glyphs.find(name);
547     if (it == glyphs.end())
548         return 0;
549
550     return it->second;
551 }
552
553 bool SGMaterial::valid() const
554
555   if (condition) {
556     return condition->test();       
557   } else {
558     return true;
559   }
560 }
561
562 \f
563 ////////////////////////////////////////////////////////////////////////
564 // SGMaterialGlyph.
565 ////////////////////////////////////////////////////////////////////////
566
567 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
568     _left(p->getDoubleValue("left", 0.0)),
569     _right(p->getDoubleValue("right", 1.0))
570 {
571 }
572
573 void
574 SGSetTextureFilter( int max) {
575     SGSceneFeatures::instance()->setTextureFilter( max);
576 }
577
578 int
579 SGGetTextureFilter() {
580     return SGSceneFeatures::instance()->getTextureFilter();
581 }