1 // mat.cxx -- class to handle material properties
3 // Written by Curtis Olson, started May 1998.
5 // Copyright (C) 1998 - 2000 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
25 # include <simgear_config.h>
28 #include <simgear/compiler.h>
35 #include <boost/foreach.hpp>
38 #include <osg/CullFace>
39 #include <osg/Material>
40 #include <osg/ShadeModel>
41 #include <osg/StateSet>
43 #include <osg/Texture>
44 #include <osg/Texture2D>
45 #include <osgDB/ReaderWriter>
46 #include <osgDB/ReadFile>
47 #include <osgDB/Registry>
48 #include <osgDB/FileUtils>
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>
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>
67 #include "Technique.hxx"
71 using namespace simgear;
73 ////////////////////////////////////////////////////////////////////////
74 // Constructors and destructor.
75 ////////////////////////////////////////////////////////////////////////
77 SGMaterial::_internal_state::_internal_state(Effect *e, bool l,
78 const SGReaderWriterOptions* o)
79 : effect(e), effect_realized(l), options(o)
83 SGMaterial::_internal_state::_internal_state( Effect *e,
86 const SGReaderWriterOptions* o )
87 : effect(e), effect_realized(l), options(o)
89 texture_paths.push_back(std::make_pair(t,0));
92 void SGMaterial::_internal_state::add_texture(const std::string &t, int i)
94 texture_paths.push_back(std::make_pair(t,i));
97 SGMaterial::SGMaterial( const SGReaderWriterOptions* options,
98 const SGPropertyNode *props,
99 SGPropertyNode *prop_root,
101 SGSharedPtr<const SGCondition> c)
106 read_properties( options, props, prop_root );
107 buildEffectProperties(options);
110 SGMaterial::SGMaterial( const osgDB::Options* options,
111 const SGPropertyNode *props,
112 SGPropertyNode *prop_root,
114 SGSharedPtr<const SGCondition> c)
116 osg::ref_ptr<SGReaderWriterOptions> opt;
117 opt = SGReaderWriterOptions::copyOrCreate(options);
121 read_properties(opt.get(), props, prop_root);
122 buildEffectProperties(opt.get());
125 SGMaterial::~SGMaterial (void)
130 ////////////////////////////////////////////////////////////////////////
132 ////////////////////////////////////////////////////////////////////////
135 SGMaterial::read_properties(const SGReaderWriterOptions* options,
136 const SGPropertyNode *props,
137 SGPropertyNode *prop_root)
139 std::vector<bool> dds;
140 std::vector<SGPropertyNode_ptr> textures = props->getChildren("texture");
141 for (unsigned int i = 0; i < textures.size(); i++)
143 std::string tname = textures[i]->getStringValue();
146 tname = "unknown.rgb";
149 SGPath tpath("Textures");
151 std::string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
152 if (fullTexPath.empty()) {
153 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
154 << tname << "\" in Textures folders.");
157 if (tpath.lower_extension() == "dds") {
160 dds.push_back(false);
163 if (!fullTexPath.empty() ) {
164 _internal_state st( NULL, fullTexPath, false, options );
165 _status.push_back( st );
169 std::vector<SGPropertyNode_ptr> texturesets = props->getChildren("texture-set");
170 for (unsigned int i = 0; i < texturesets.size(); i++)
172 _internal_state st( NULL, false, options );
173 std::vector<SGPropertyNode_ptr> textures = texturesets[i]->getChildren("texture");
174 for (unsigned int j = 0; j < textures.size(); j++)
176 std::string tname = textures[j]->getStringValue();
178 tname = "unknown.rgb";
181 SGPath tpath("Textures");
183 std::string fullTexPath = SGModelLib::findDataFile(tpath.str(), options);
184 if (fullTexPath.empty()) {
185 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
186 << tname << "\" in Textures folders.");
190 if (tpath.lower_extension() == "dds") {
193 dds.push_back(false);
197 st.add_texture(fullTexPath, textures[j]->getIndex());
200 if (!st.texture_paths.empty() ) {
201 _status.push_back( st );
205 if (textures.empty() && texturesets.empty()) {
206 SGPath tpath("Textures");
207 tpath.append("Terrain");
208 tpath.append("unknown.rgb");
209 _internal_state st( NULL, tpath.str(), true, options );
210 _status.push_back( st );
213 std::vector<SGPropertyNode_ptr> masks = props->getChildren("object-mask");
214 for (unsigned int i = 0; i < masks.size(); i++)
216 std::string omname = masks[i]->getStringValue();
218 if (! omname.empty()) {
219 SGPath ompath("Textures");
220 ompath.append(omname);
221 std::string fullMaskPath = SGModelLib::findDataFile(ompath.str(), options);
223 if (fullMaskPath.empty()) {
224 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
225 << omname << "\" in Textures folders.");
229 osg::Image* image = osgDB::readImageFile(fullMaskPath, options);
230 if (image && image->valid())
232 Texture2DRef object_mask = new osg::Texture2D;
234 bool dds_mask = (ompath.lower_extension() == "dds");
236 if (i < dds.size() && dds[i] != dds_mask) {
237 // Texture format does not match mask format. This is relevant for
238 // the object mask, as DDS textures have an origin at the bottom
239 // left rather than top left. Therefore we flip a copy of the image
240 // (otherwise a second reference to the object mask would flip it
242 SG_LOG(SG_GENERAL, SG_DEBUG, "Flipping object mask" << omname);
243 image = (osg::Image* ) image->clone(osg::CopyOp::SHALLOW_COPY);
244 image->flipVertical();
247 object_mask->setImage(image);
249 // We force the filtering to be nearest, as the red channel (rotation)
250 // in particular, doesn't make sense to be interpolated between pixels.
251 object_mask->setFilter(osg::Texture::MIN_FILTER, osg::Texture::NEAREST);
252 object_mask->setFilter(osg::Texture::MAG_FILTER, osg::Texture::NEAREST);
254 object_mask->setDataVariance(osg::Object::STATIC);
255 object_mask->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT);
256 object_mask->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);
257 _masks.push_back(object_mask);
263 xsize = props->getDoubleValue("xsize", 0.0);
264 ysize = props->getDoubleValue("ysize", 0.0);
265 wrapu = props->getBoolValue("wrapu", true);
266 wrapv = props->getBoolValue("wrapv", true);
267 mipmap = props->getBoolValue("mipmap", true);
268 light_coverage = props->getDoubleValue("light-coverage", 0.0);
270 // Building properties
271 building_coverage = props->getDoubleValue("building-coverage", 0.0);
272 building_spacing = props->getDoubleValue("building-spacing-m", 5.0);
274 std::string bt = props->getStringValue( "building-texture",
275 "Textures/buildings.png" );
276 building_texture = SGModelLib::findDataFile(bt, options);
278 if (building_texture.empty()) {
279 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
282 bt = props->getStringValue("building-lightmap", "Textures/buildings-lightmap.png");
283 building_lightmap = SGModelLib::findDataFile(bt, options);
285 if (building_lightmap.empty()) {
286 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \"" << bt);
289 building_small_ratio = props->getDoubleValue("building-small-ratio", 0.8);
290 building_medium_ratio = props->getDoubleValue("building-medium-ratio", 0.15);
291 building_large_ratio = props->getDoubleValue("building-large-ratio", 0.05);
293 building_small_pitch = props->getDoubleValue("building-small-pitch", 0.8);
294 building_medium_pitch = props->getDoubleValue("building-medium-pitch", 0.2);
295 building_large_pitch = props->getDoubleValue("building-large-pitch", 0.1);
297 building_small_min_floors = props->getIntValue("building-small-min-floors", 1);
298 building_small_max_floors = props->getIntValue("building-small-max-floors", 3);
299 building_medium_min_floors = props->getIntValue("building-medium-min-floors", 3);
300 building_medium_max_floors = props->getIntValue("building-medium-max-floors", 8);
301 building_large_min_floors = props->getIntValue("building-large-min-floors", 5);
302 building_large_max_floors = props->getIntValue("building-large-max-floors", 20);
304 building_small_min_width = props->getFloatValue("building-small-min-width-m", 15.0);
305 building_small_max_width = props->getFloatValue("building-small-max-width-m", 60.0);
306 building_small_min_depth = props->getFloatValue("building-small-min-depth-m", 10.0);
307 building_small_max_depth = props->getFloatValue("building-small-max-depth-m", 20.0);
309 building_medium_min_width = props->getFloatValue("building-medium-min-width-m", 25.0);
310 building_medium_max_width = props->getFloatValue("building-medium-max-width-m", 50.0);
311 building_medium_min_depth = props->getFloatValue("building-medium-min-depth-m", 20.0);
312 building_medium_max_depth = props->getFloatValue("building-medium-max-depth-m", 50.0);
314 building_large_min_width = props->getFloatValue("building-large-min-width-m", 50.0);
315 building_large_max_width = props->getFloatValue("building-large-max-width-m", 75.0);
316 building_large_min_depth = props->getFloatValue("building-large-min-depth-m", 50.0);
317 building_large_max_depth = props->getFloatValue("building-large-max-depth-m", 75.0);
319 building_range = props->getDoubleValue("building-range-m", 10000.0);
321 cos_object_max_density_slope_angle = cos(props->getFloatValue("object-max-density-angle-deg", 20.0) * osg::PI/180.0);
322 cos_object_zero_density_slope_angle = cos(props->getFloatValue("object-zero-density-angle-deg", 30.0) * osg::PI/180.0);
324 // Random vegetation properties
325 wood_coverage = props->getDoubleValue("wood-coverage", 0.0);
326 tree_height = props->getDoubleValue("tree-height-m", 0.0);
327 tree_width = props->getDoubleValue("tree-width-m", 0.0);
328 tree_range = props->getDoubleValue("tree-range-m", 0.0);
329 tree_varieties = props->getIntValue("tree-varieties", 1);
330 cos_tree_max_density_slope_angle = cos(props->getFloatValue("tree-max-density-angle-deg", 30.0) * osg::PI/180.0);
331 cos_tree_zero_density_slope_angle = cos(props->getFloatValue("tree-zero-density-angle-deg", 45.0) * osg::PI/180.0);
333 const SGPropertyNode* treeTexNode = props->getChild("tree-texture");
336 std::string treeTexPath = props->getStringValue("tree-texture");
338 if (! treeTexPath.empty()) {
339 SGPath treePath("Textures");
340 treePath.append(treeTexPath);
341 tree_texture = SGModelLib::findDataFile(treePath.str(), options);
343 if (tree_texture.empty()) {
344 SG_LOG(SG_GENERAL, SG_ALERT, "Cannot find texture \""
345 << treeTexPath << "\" in Textures folders.");
350 // surface values for use with ground reactions
351 _solid = props->getBoolValue("solid", _solid);
352 _friction_factor = props->getDoubleValue("friction-factor", _friction_factor);
353 _rolling_friction = props->getDoubleValue("rolling-friction", _rolling_friction);
354 _bumpiness = props->getDoubleValue("bumpiness", _bumpiness);
355 _load_resistance = props->getDoubleValue("load-resistance", _load_resistance);
357 // Taken from default values as used in ac3d
358 ambient[0] = props->getDoubleValue("ambient/r", 0.2);
359 ambient[1] = props->getDoubleValue("ambient/g", 0.2);
360 ambient[2] = props->getDoubleValue("ambient/b", 0.2);
361 ambient[3] = props->getDoubleValue("ambient/a", 1.0);
363 diffuse[0] = props->getDoubleValue("diffuse/r", 0.8);
364 diffuse[1] = props->getDoubleValue("diffuse/g", 0.8);
365 diffuse[2] = props->getDoubleValue("diffuse/b", 0.8);
366 diffuse[3] = props->getDoubleValue("diffuse/a", 1.0);
368 specular[0] = props->getDoubleValue("specular/r", 0.0);
369 specular[1] = props->getDoubleValue("specular/g", 0.0);
370 specular[2] = props->getDoubleValue("specular/b", 0.0);
371 specular[3] = props->getDoubleValue("specular/a", 1.0);
373 emission[0] = props->getDoubleValue("emissive/r", 0.0);
374 emission[1] = props->getDoubleValue("emissive/g", 0.0);
375 emission[2] = props->getDoubleValue("emissive/b", 0.0);
376 emission[3] = props->getDoubleValue("emissive/a", 1.0);
378 shininess = props->getDoubleValue("shininess", 1.0);
380 if (props->hasChild("effect"))
381 effect = props->getStringValue("effect");
383 std::vector<SGPropertyNode_ptr> object_group_nodes =
384 ((SGPropertyNode *)props)->getChildren("object-group");
385 for (unsigned int i = 0; i < object_group_nodes.size(); i++)
386 object_groups.push_back(new SGMatModelGroup(object_group_nodes[i]));
388 // read glyph table for taxi-/runway-signs
389 std::vector<SGPropertyNode_ptr> glyph_nodes = props->getChildren("glyph");
390 for (unsigned int i = 0; i < glyph_nodes.size(); i++) {
391 const char *name = glyph_nodes[i]->getStringValue("name");
393 glyphs[name] = new SGMaterialGlyph(glyph_nodes[i]);
396 // Read parameters entry, which is passed into the effect
397 if (props->hasChild("parameters")) {
398 parameters = props->getChild("parameters");
400 parameters = new SGPropertyNode();
406 ////////////////////////////////////////////////////////////////////////
408 ////////////////////////////////////////////////////////////////////////
420 light_coverage = 0.0;
421 building_coverage = 0.0;
424 for (int i = 0; i < 4; i++) {
425 ambient[i] = (i < 3) ? 0.2 : 1.0;
426 specular[i] = (i < 3) ? 0.0 : 1.0;
427 diffuse[i] = (i < 3) ? 0.8 : 1.0;
428 emission[i] = (i < 3) ? 0.0 : 1.0;
430 effect = "Effects/terrain-default";
433 Effect* SGMaterial::get_effect(int i)
435 if(!_status[i].effect_realized) {
436 if (!_status[i].effect.valid())
438 _status[i].effect->realizeTechniques(_status[i].options.get());
439 _status[i].effect_realized = true;
441 return _status[i].effect.get();
444 Effect* SGMaterial::get_effect(const SGTexturedTriangleBin& triangleBin)
446 SGGuard<SGMutex> g(_lock);
447 if (_status.empty()) {
448 SG_LOG( SG_GENERAL, SG_WARN, "No effect available.");
452 int i = triangleBin.getTextureIndex() % _status.size();
453 return get_effect(i);
456 Effect* SGMaterial::get_effect()
458 SGGuard<SGMutex> g(_lock);
459 return get_effect(0);
463 osg::Texture2D* SGMaterial::get_object_mask(const SGTexturedTriangleBin& triangleBin)
465 if (_status.empty()) {
466 SG_LOG( SG_GENERAL, SG_WARN, "No mask available.");
470 // Note that the object mask is closely linked to the texture/effect
471 // so we index based on the texture index,
472 unsigned int i = triangleBin.getTextureIndex() % _status.size();
473 if (i < _masks.size()) {
474 return _masks[i].get();
480 void SGMaterial::buildEffectProperties(const SGReaderWriterOptions* options)
483 ref_ptr<SGMaterialUserData> user = new SGMaterialUserData(this);
484 SGPropertyNode_ptr propRoot = new SGPropertyNode();
485 makeChild(propRoot, "inherits-from")->setStringValue(effect);
487 SGPropertyNode* paramProp = makeChild(propRoot, "parameters");
488 copyProperties(parameters, paramProp);
490 SGPropertyNode* materialProp = makeChild(paramProp, "material");
491 makeChild(materialProp, "ambient")->setValue(SGVec4d(ambient));
492 makeChild(materialProp, "diffuse")->setValue(SGVec4d(diffuse));
493 makeChild(materialProp, "specular")->setValue(SGVec4d(specular));
494 makeChild(materialProp, "emissive")->setValue(SGVec4d(emission));
495 makeChild(materialProp, "shininess")->setFloatValue(shininess);
496 if (ambient[3] < 1 || diffuse[3] < 1 ||
497 specular[3] < 1 || emission[3] < 1) {
498 makeChild(paramProp, "transparent")->setBoolValue(true);
499 SGPropertyNode* binProp = makeChild(paramProp, "render-bin");
500 makeChild(binProp, "bin-number")->setIntValue(TRANSPARENT_BIN);
501 makeChild(binProp, "bin-name")->setStringValue("DepthSortedBin");
503 BOOST_FOREACH(_internal_state& matState, _status)
505 SGPropertyNode_ptr effectProp = new SGPropertyNode();
506 copyProperties(propRoot, effectProp);
507 SGPropertyNode* effectParamProp = effectProp->getChild("parameters", 0);
508 for (unsigned int i = 0; i < matState.texture_paths.size(); i++) {
509 SGPropertyNode* texProp = makeChild(effectParamProp, "texture", matState.texture_paths[i].second);
510 makeChild(texProp, "image")->setStringValue(matState.texture_paths[i].first);
511 makeChild(texProp, "filter")
512 ->setStringValue(mipmap ? "linear-mipmap-linear" : "nearest");
513 makeChild(texProp, "wrap-s")
514 ->setStringValue(wrapu ? "repeat" : "clamp-to-edge");
515 makeChild(texProp, "wrap-t")
516 ->setStringValue(wrapv ? "repeat" : "clamp-to-edge");
518 makeChild(effectParamProp, "xsize")->setDoubleValue(xsize);
519 makeChild(effectParamProp, "ysize")->setDoubleValue(ysize);
520 makeChild(effectParamProp, "scale")->setValue(SGVec3d(xsize,ysize,0.0));
521 makeChild(effectParamProp, "light-coverage")->setDoubleValue(light_coverage);
523 matState.effect = makeEffect(effectProp, false, options);
524 if (matState.effect.valid())
525 matState.effect->setUserData(user.get());
529 SGMaterialGlyph* SGMaterial::get_glyph (const std::string& name) const
531 map<std::string, SGSharedPtr<SGMaterialGlyph> >::const_iterator it;
532 it = glyphs.find(name);
533 if (it == glyphs.end())
539 bool SGMaterial::valid(SGVec2f loc) const
541 SG_LOG( SG_TERRAIN, SG_BULK, "Checking materials for location ("
545 // Check location first again the areas the material is valid for
546 AreaList::const_iterator i = areas->begin();
548 if (i == areas->end()) {
549 // No areas defined, so simply check against condition
551 return condition->test();
557 for (; i != areas->end(); i++) {
559 SG_LOG( SG_TERRAIN, SG_BULK, "Checking area ("
561 << i->y() << ") width:"
562 << i->width() << " height:"
564 // Areas defined, so check that the tile location falls within it
565 // before checking against condition
566 if (i->contains(loc.x(), loc.y())) {
568 return condition->test();
579 ////////////////////////////////////////////////////////////////////////
581 ////////////////////////////////////////////////////////////////////////
583 SGMaterialGlyph::SGMaterialGlyph(SGPropertyNode *p) :
584 _left(p->getDoubleValue("left", 0.0)),
585 _right(p->getDoubleValue("right", 1.0))
590 SGSetTextureFilter( int max) {
591 SGSceneFeatures::instance()->setTextureFilter( max);
595 SGGetTextureFilter() {
596 return SGSceneFeatures::instance()->getTextureFilter();