1 // obj.cxx -- routines to handle loading scenery and building the plib
4 // Written by Curtis Olson, started October 1997.
6 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 # include <simgear_config.h>
31 #include <simgear/compiler.h>
35 #include <osg/Geometry>
38 #include <osg/MatrixTransform>
40 #include <osg/StateSet>
43 #include <boost/foreach.hpp>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/io/sg_binobj.hxx>
49 #include <simgear/math/sg_geodesy.hxx>
50 #include <simgear/math/sg_random.h>
51 #include <simgear/math/SGMisc.hxx>
52 #include <simgear/scene/material/Effect.hxx>
53 #include <simgear/scene/material/EffectGeode.hxx>
54 #include <simgear/scene/material/mat.hxx>
55 #include <simgear/scene/material/matmodel.hxx>
56 #include <simgear/scene/material/matlib.hxx>
57 #include <simgear/scene/model/SGOffsetTransform.hxx>
58 #include <simgear/scene/util/SGUpdateVisitor.hxx>
59 #include <simgear/scene/util/SGNodeMasks.hxx>
60 #include <simgear/scene/util/QuadTreeBuilder.hxx>
61 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
63 #include "SGTexturedTriangleBin.hxx"
64 #include "SGLightBin.hxx"
65 #include "SGModelBin.hxx"
66 #include "SGBuildingBin.hxx"
67 #include "TreeBin.hxx"
68 #include "SGDirectionalLightBin.hxx"
69 #include "GroundLightManager.hxx"
72 #include "pt_lights.hxx"
74 using namespace simgear;
76 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
77 typedef std::list<SGLightBin> SGLightListBin;
78 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
80 struct SGTileGeometryBin {
81 SGMaterialTriangleMap materialTriangleMap;
82 SGLightBin tileLights;
83 SGLightBin randomTileLights;
84 SGTreeBinList randomForest;
85 SGDirectionalLightBin runwayLights;
86 SGDirectionalLightBin taxiLights;
87 SGDirectionalLightListBin vasiLights;
88 SGDirectionalLightListBin rabitLights;
89 SGLightListBin odalLights;
90 SGDirectionalLightListBin holdshortLights;
91 SGDirectionalLightListBin guardLights;
92 SGDirectionalLightListBin reilLights;
93 SGMatModelBin randomModels;
94 SGBuildingBinList randomBuildings;
97 getMaterialLightColor(const SGMaterial* material)
100 return SGVec4f(1, 1, 1, 0.8);
101 return material->get_light_color();
105 addPointGeometry(SGLightBin& lights,
106 const std::vector<SGVec3d>& vertices,
107 const SGVec4f& color,
108 const int_list& pts_v)
110 for (unsigned i = 0; i < pts_v.size(); ++i)
111 lights.insert(toVec3f(vertices[pts_v[i]]), color);
115 addPointGeometry(SGDirectionalLightBin& lights,
116 const std::vector<SGVec3d>& vertices,
117 const std::vector<SGVec3f>& normals,
118 const SGVec4f& color,
119 const int_list& pts_v,
120 const int_list& pts_n)
122 // If the normal indices match the vertex indices, use seperate
123 // normal indices. Else reuse the vertex indices for the normals.
124 if (pts_v.size() == pts_n.size()) {
125 for (unsigned i = 0; i < pts_v.size(); ++i)
126 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
128 for (unsigned i = 0; i < pts_v.size(); ++i)
129 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
134 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
136 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
137 SG_LOG(SG_TERRAIN, SG_ALERT,
138 "Group list sizes for points do not match!");
142 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
143 std::string materialName = obj.get_pt_materials()[grp];
144 SGMaterial* material = 0;
146 material = matlib->find(materialName);
147 SGVec4f color = getMaterialLightColor(material);
149 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
150 // Just plain lights. Not something for the runway.
151 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
152 obj.get_pts_v()[grp]);
153 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
154 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
155 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
156 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
157 } else if (materialName == "RWY_VASI_LIGHTS") {
158 vasiLights.push_back(SGDirectionalLightBin());
159 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
160 obj.get_normals(), color, obj.get_pts_v()[grp],
161 obj.get_pts_n()[grp]);
162 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
163 rabitLights.push_back(SGDirectionalLightBin());
164 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
165 obj.get_normals(), color, obj.get_pts_v()[grp],
166 obj.get_pts_n()[grp]);
167 } else if (materialName == "RWY_ODALS_LIGHTS") {
168 odalLights.push_back(SGLightBin());
169 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
170 color, obj.get_pts_v()[grp]);
171 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
172 holdshortLights.push_back(SGDirectionalLightBin());
173 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
174 obj.get_normals(), color, obj.get_pts_v()[grp],
175 obj.get_pts_n()[grp]);
176 } else if (materialName == "RWY_GUARD_LIGHTS") {
177 guardLights.push_back(SGDirectionalLightBin());
178 addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
179 obj.get_normals(), color, obj.get_pts_v()[grp],
180 obj.get_pts_n()[grp]);
181 } else if (materialName == "RWY_REIL_LIGHTS") {
182 reilLights.push_back(SGDirectionalLightBin());
183 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
184 obj.get_normals(), color, obj.get_pts_v()[grp],
185 obj.get_pts_n()[grp]);
187 // what is left must be runway lights
188 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
189 obj.get_normals(), color, obj.get_pts_v()[grp],
190 obj.get_pts_n()[grp]);
199 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
200 const SGVec2f& tcScale, unsigned i)
204 else if (tc.size() == 1)
205 return mult(texCoords[tc[0]], tcScale);
207 return mult(texCoords[tc[i]], tcScale);
211 addTriangleGeometry(SGTexturedTriangleBin& triangles,
212 const std::vector<SGVec3d>& vertices,
213 const std::vector<SGVec3f>& normals,
214 const std::vector<SGVec2f>& texCoords,
215 const int_list& tris_v,
216 const int_list& tris_n,
217 const int_list& tris_tc,
218 const SGVec2f& tcScale)
220 if (tris_v.size() != tris_n.size()) {
221 // If the normal indices do not match, they should be inmplicitly
222 // the same than the vertex indices. So just call ourselves again
223 // with the matching index vector.
224 addTriangleGeometry(triangles, vertices, normals, texCoords,
225 tris_v, tris_v, tris_tc, tcScale);
229 for (unsigned i = 2; i < tris_v.size(); i += 3) {
231 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
232 v0.normal = normals[tris_n[i-2]];
233 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
235 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
236 v1.normal = normals[tris_n[i-1]];
237 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
239 v2.vertex = toVec3f(vertices[tris_v[i]]);
240 v2.normal = normals[tris_n[i]];
241 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
242 triangles.insert(v0, v1, v2);
247 addStripGeometry(SGTexturedTriangleBin& triangles,
248 const std::vector<SGVec3d>& vertices,
249 const std::vector<SGVec3f>& normals,
250 const std::vector<SGVec2f>& texCoords,
251 const int_list& strips_v,
252 const int_list& strips_n,
253 const int_list& strips_tc,
254 const SGVec2f& tcScale)
256 if (strips_v.size() != strips_n.size()) {
257 // If the normal indices do not match, they should be inmplicitly
258 // the same than the vertex indices. So just call ourselves again
259 // with the matching index vector.
260 addStripGeometry(triangles, vertices, normals, texCoords,
261 strips_v, strips_v, strips_tc, tcScale);
265 for (unsigned i = 2; i < strips_v.size(); ++i) {
267 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
268 v0.normal = normals[strips_n[i-2]];
269 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
271 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
272 v1.normal = normals[strips_n[i-1]];
273 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
275 v2.vertex = toVec3f(vertices[strips_v[i]]);
276 v2.normal = normals[strips_n[i]];
277 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
279 triangles.insert(v1, v0, v2);
281 triangles.insert(v0, v1, v2);
286 addFanGeometry(SGTexturedTriangleBin& triangles,
287 const std::vector<SGVec3d>& vertices,
288 const std::vector<SGVec3f>& normals,
289 const std::vector<SGVec2f>& texCoords,
290 const int_list& fans_v,
291 const int_list& fans_n,
292 const int_list& fans_tc,
293 const SGVec2f& tcScale)
295 if (fans_v.size() != fans_n.size()) {
296 // If the normal indices do not match, they should be implicitly
297 // the same than the vertex indices. So just call ourselves again
298 // with the matching index vector.
299 addFanGeometry(triangles, vertices, normals, texCoords,
300 fans_v, fans_v, fans_tc, tcScale);
305 v0.vertex = toVec3f(vertices[fans_v[0]]);
306 v0.normal = normals[fans_n[0]];
307 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
309 v1.vertex = toVec3f(vertices[fans_v[1]]);
310 v1.normal = normals[fans_n[1]];
311 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
312 for (unsigned i = 2; i < fans_v.size(); ++i) {
314 v2.vertex = toVec3f(vertices[fans_v[i]]);
315 v2.normal = normals[fans_n[i]];
316 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
317 triangles.insert(v0, v1, v2);
322 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
325 return SGVec2f(1, 1);
326 SGMaterial* material = matlib->find(name);
328 return SGVec2f(1, 1);
330 return material->get_tex_coord_scale();
334 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
336 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
337 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
338 SG_LOG(SG_TERRAIN, SG_ALERT,
339 "Group list sizes for triangles do not match!");
343 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
344 std::string materialName = obj.get_tri_materials()[grp];
345 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
346 addTriangleGeometry(materialTriangleMap[materialName],
347 obj.get_wgs84_nodes(), obj.get_normals(),
348 obj.get_texcoords(), obj.get_tris_v()[grp],
349 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
353 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
354 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
355 SG_LOG(SG_TERRAIN, SG_ALERT,
356 "Group list sizes for strips do not match!");
359 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
360 std::string materialName = obj.get_strip_materials()[grp];
361 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
362 addStripGeometry(materialTriangleMap[materialName],
363 obj.get_wgs84_nodes(), obj.get_normals(),
364 obj.get_texcoords(), obj.get_strips_v()[grp],
365 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
369 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
370 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
371 SG_LOG(SG_TERRAIN, SG_ALERT,
372 "Group list sizes for fans do not match!");
375 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
376 std::string materialName = obj.get_fan_materials()[grp];
377 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
378 addFanGeometry(materialTriangleMap[materialName],
379 obj.get_wgs84_nodes(), obj.get_normals(),
380 obj.get_texcoords(), obj.get_fans_v()[grp],
381 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
387 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
389 if (materialTriangleMap.empty())
393 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
394 //osg::Geode* geode = new osg::Geode;
395 SGMaterialTriangleMap::const_iterator i;
396 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
397 osg::Geometry* geometry = i->second.buildGeometry();
400 mat = matlib->find(i->first);
401 eg = new EffectGeode;
402 eg->setName("EffectGeode");
404 eg->setEffect(mat->get_effect(i->second));
405 eg->addDrawable(geometry);
406 eg->runGenerators(geometry); // Generate extra data needed by effect
408 group->setName("surfaceGeometryGroup");
418 void computeRandomSurfaceLights(SGMaterialLib* matlib)
420 SGMaterialTriangleMap::iterator i;
422 // generate a repeatable random seed
424 mt_init(&seed, unsigned(123));
426 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
427 SGMaterial *mat = matlib->find(i->first);
431 float coverage = mat->get_light_coverage();
434 if (coverage < 10000.0) {
435 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
436 << coverage << ", pushing up to 10000");
440 std::vector<SGVec3f> randomPoints;
441 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
442 std::vector<SGVec3f>::iterator j;
443 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
444 float zombie = mt_rand(&seed);
445 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
446 float factor = mt_rand(&seed);
451 if ( zombie > 0.5 ) {
452 // 50% chance of yellowish
453 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
454 } else if (zombie > 0.15f) {
455 // 35% chance of whitish
456 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
457 } else if (zombie > 0.05f) {
458 // 10% chance of orangish
459 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
461 // 5% chance of redish
462 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
464 randomTileLights.insert(*j, color);
469 void computeRandomObjectsAndBuildings(
470 SGMaterialLib* matlib,
471 float building_density,
472 bool use_random_objects,
473 bool use_random_buildings)
475 SGMaterialTriangleMap::iterator i;
477 // generate a repeatable random seed
479 mt_init(&seed, unsigned(123));
481 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
482 SGMaterial *mat = matlib->find(i->first);
483 SGTexturedTriangleBin triangleBin = i->second;
488 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
489 int group_count = mat->get_object_group_count();
490 float building_coverage = mat->get_building_coverage();
491 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
492 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
495 SGBuildingBin* bin = NULL;
497 if (building_coverage > 0) {
498 BOOST_FOREACH(bin, randomBuildings)
500 if (bin->getMaterialName() == mat->get_names()[0]) {
507 bin = new SGBuildingBin(mat);
508 randomBuildings.push_back(bin);
512 unsigned num = i->second.getNumTriangles();
513 int random_dropped = 0;
514 int mask_dropped = 0;
515 int building_dropped = 0;
516 int triangle_dropped = 0;
518 for (unsigned i = 0; i < num; ++i) {
519 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
521 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
522 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
523 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
524 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
525 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
526 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
527 SGVec3f normal = cross(v0, v1);
529 // Ensure the slope isn't too steep by checking the
530 // cos of the angle between the slope normal and the
531 // vertical (conveniently the z-component of the normalized
532 // normal) and values passed in.
533 float cos = normalize(normal).z();
534 float slope_density = 1.0;
535 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
536 if (cos < cos_max_density_angle) {
538 (cos - cos_zero_density_angle) /
539 (cos_max_density_angle - cos_zero_density_angle);
542 // Containers to hold the random buildings and objects generated
543 // for this triangle for collision detection purposes.
544 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
545 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
548 float area = 0.5f*length(normal);
549 if (area <= SGLimitsf::min())
552 // Generate any random objects
553 if (use_random_objects && (group_count > 0))
555 for (int j = 0; j < group_count; j++)
557 SGMatModelGroup *object_group = mat->get_object_group(j);
558 int nObjects = object_group->get_object_count();
560 if (nObjects == 0) continue;
562 // For each of the random models in the group, determine an appropriate
563 // number of random placements and insert them.
564 for (int k = 0; k < nObjects; k++) {
565 SGMatModel * object = object_group->get_object(k);
567 // Determine the number of objecst to place, taking into account
568 // the slope density factor.
569 double n = slope_density * area / object->get_coverage_m2();
571 // Use the zombie door method to determine fractional object placement.
572 n = n + mt_rand(&seed);
574 // place an object each unit of area
576 float a = mt_rand(&seed);
577 float b = mt_rand(&seed);
583 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
584 float rotation = static_cast<float>(mt_rand(&seed));
586 // Check that the point is sufficiently far from
587 // the edge of the triangle by measuring the distance
588 // from the three lines that make up the triangle.
589 float spacing = object->get_spacing_m();
591 SGVec3f p = randomPoint - vorigin;
592 float edges[] = { length(cross(p , p - v0)) / length(v0),
593 length(cross(p - v0, p - v1)) / length(v1 - v0),
594 length(cross(p - v1, p )) / length(v1) };
595 float edge_dist = *std::min_element(edges, edges + 3);
597 if (edge_dist < spacing) {
602 if (object_mask != NULL) {
603 SGVec2f texCoord = torigin + a*t0 + b*t1;
605 // Check this random point against the object mask
606 // blue (for buildings) channel.
607 osg::Image* img = object_mask->getImage();
608 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
609 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
611 if (mt_rand(&seed) > img->getColor(x, y).b()) {
612 // Failed object mask check
617 rotation = img->getColor(x,y).r();
622 // Check it isn't too close to any other random objects in the triangle
623 std::vector<std::pair<SGVec3f, float> >::iterator l;
624 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
625 float min_dist2 = (l->second + object->get_spacing_m()) *
626 (l->second + object->get_spacing_m());
628 if (distSqr(l->first, randomPoint) > min_dist2) {
635 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
636 randomModels.insert(randomPoint,
638 (int)object->get_randomized_range_m(&seed),
648 // Random objects now generated. Now generate the random buildings (if any);
649 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
651 // Calculate the number of buildings, taking into account building density (which is linear)
652 // and the slope density factor.
653 double num = building_density * building_density * slope_density * area / building_coverage;
655 // For partial units of area, use a zombie door method to
656 // create the proper random chance of an object being created
657 // for this triangle.
658 num = num + mt_rand(&seed);
664 // Cosine of the angle between the two vectors.
665 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
667 // Determine a grid spacing in each vector such that the correct
668 // coverage will result.
669 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
670 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
672 stepv0 = std::min(stepv0, 1.0f);
673 stepv1 = std::min(stepv1, 1.0f);
675 // Start at a random point. a will be immediately incremented below.
676 float a = -mt_rand(&seed) * stepv0;
677 float b = mt_rand(&seed) * stepv1;
679 // Place an object each unit of area
682 // Set the next location to place a building
685 if ((a + b) > 1.0f) {
686 // Reached the end of the scan-line on v0. Reset and increment
688 a = mt_rand(&seed) * stepv0;
693 // In a degenerate case of a single point, we might be outside the
694 // scanline. Note that we need to still ensure that a+b < 1.
695 b = mt_rand(&seed) * stepv1 * (1.0f - a);
698 if ((a + b) > 1.0f ) {
699 // Truly degenerate case - simply choose a random point guaranteed
700 // to fulfil the constraing of a+b < 1.
702 b = mt_rand(&seed) * (1.0f - a);
705 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
706 float rotation = mt_rand(&seed);
708 if (object_mask != NULL) {
709 SGVec2f texCoord = torigin + a*t0 + b*t1;
710 osg::Image* img = object_mask->getImage();
711 int x = (int) (img->s() * texCoord.x()) % img->s();
712 int y = (int) (img->t() * texCoord.y()) % img->t();
714 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
715 while (x < 0) x += img->s();
716 while (y < 0) y += img->t();
718 if (mt_rand(&seed) < img->getColor(x, y).b()) {
719 // Object passes mask. Rotation is taken from the red channel
720 rotation = img->getColor(x,y).r();
722 // Fails mask test - try again.
729 // Check building isn't too close to the triangle edge.
730 float type_roll = mt_rand(&seed);
731 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
732 float radius = bin->getBuildingMaxRadius(buildingtype);
734 // Determine the actual center of the building, by shifting from the
735 // center of the front face to the true center.
736 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
737 osg::Vec3f(0.0, 0.0, 1.0));
738 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
740 SGVec3f p = buildingCenter - vorigin;
741 float edges[] = { length(cross(p , p - v0)) / length(v0),
742 length(cross(p - v0, p - v1)) / length(v1 - v0),
743 length(cross(p - v1, p )) / length(v1) };
744 float edge_dist = *std::min_element(edges, edges + 3);
746 if (edge_dist < radius) {
752 // Check building isn't too close to random objects and other buildings.
754 std::vector<std::pair<SGVec3f, float> >::iterator iter;
756 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
757 float min_dist = iter->second + radius;
758 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
770 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
771 float min_dist = iter->second + radius;
772 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
784 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
785 triangleBuildingList.push_back(pt);
786 bin->insert(randomPoint, rotation, buildingtype);
791 triangleObjectsList.clear();
792 triangleBuildingList.clear();
795 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
796 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
797 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
798 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
802 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
804 SGMaterialTriangleMap::iterator i;
806 // generate a repeatable random seed
809 mt_init(&seed, unsigned(586));
811 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
812 SGMaterial *mat = matlib->find(i->first);
816 float wood_coverage = mat->get_wood_coverage();
817 if ((wood_coverage <= 0) || (vegetation_density <= 0))
820 // Attributes that don't vary by tree but do vary by material
824 BOOST_FOREACH(bin, randomForest)
826 if ((bin->texture == mat->get_tree_texture() ) &&
827 (bin->texture_varieties == mat->get_tree_varieties()) &&
828 (bin->range == mat->get_tree_range() ) &&
829 (bin->width == mat->get_tree_width() ) &&
830 (bin->height == mat->get_tree_height() ) ) {
838 bin->texture = mat->get_tree_texture();
839 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
840 bin->range = mat->get_tree_range();
841 bin->width = mat->get_tree_width();
842 bin->height = mat->get_tree_height();
843 bin->texture_varieties = mat->get_tree_varieties();
844 randomForest.push_back(bin);
847 std::vector<SGVec3f> randomPoints;
848 i->second.addRandomTreePoints(wood_coverage,
849 mat->get_object_mask(i->second),
851 mat->get_cos_tree_max_density_slope_angle(),
852 mat->get_cos_tree_zero_density_slope_angle(),
855 std::vector<SGVec3f>::iterator k;
856 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
862 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
864 if (!insertPtGeometry(obj, matlib))
866 if (!insertSurfaceGeometry(obj, matlib))
872 typedef std::pair<osg::Node*, int> ModelLOD;
873 struct MakeQuadLeaf {
874 osg::LOD* operator() () const { return new osg::LOD; }
877 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
879 leaf->addChild(mlod.first, 0, mlod.second);
882 struct GetModelLODCoord {
883 GetModelLODCoord() {}
884 GetModelLODCoord(const GetModelLODCoord& rhs)
886 osg::Vec3 operator() (const ModelLOD& mlod) const
888 return mlod.first->getBound().center();
892 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
893 GetModelLODCoord> RandomObjectsQuadtree;
896 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
899 if (!tile.read_bin(path))
902 SGMaterialLib* matlib = 0;
903 bool use_random_objects = false;
904 bool use_random_vegetation = false;
905 bool use_random_buildings = false;
906 float vegetation_density = 1.0f;
907 float building_density = 1.0f;
909 matlib = options->getMaterialLib();
910 SGPropertyNode* propertyNode = options->getPropertyNode().get();
913 = propertyNode->getBoolValue("/sim/rendering/random-objects",
915 use_random_vegetation
916 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
917 use_random_vegetation);
919 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
922 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
923 use_random_buildings);
925 = propertyNode->getFloatValue("/sim/rendering/building-density",
930 SGVec3d center = tile.get_gbs_center();
931 SGGeod geodPos = SGGeod::fromCart(center);
932 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
934 // rotate the tiles so that the bounding boxes get nearly axis aligned.
935 // this will help the collision tree's bounding boxes a bit ...
936 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
937 for (unsigned i = 0; i < nodes.size(); ++i)
938 nodes[i] = hlOr.transform(nodes[i]);
939 tile.set_wgs84_nodes(nodes);
941 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
942 std::vector<SGVec3f> normals = tile.get_normals();
943 for (unsigned i = 0; i < normals.size(); ++i)
944 normals[i] = hlOrf.transform(normals[i]);
945 tile.set_normals(normals);
947 SGTileGeometryBin tileGeometryBin;
948 if (!tileGeometryBin.insertBinObj(tile, matlib))
952 GroundLightManager* lightManager = GroundLightManager::instance();
954 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
955 osg::ref_ptr<osg::Group> randomObjects;
956 osg::ref_ptr<osg::Group> forestNode;
957 osg::ref_ptr<osg::Group> buildingNode;
958 osg::Group* terrainGroup = new osg::Group;
959 terrainGroup->setName("BTGTerrainGroup");
961 osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
963 terrainGroup->addChild(node);
965 if (matlib && (use_random_objects || use_random_buildings)) {
966 tileGeometryBin.computeRandomObjectsAndBuildings(matlib,
969 use_random_buildings);
972 if (tileGeometryBin.randomModels.getNumModels() > 0) {
973 // Generate a repeatable random seed
975 mt_init(&seed, unsigned(123));
977 std::vector<ModelLOD> models;
978 for (unsigned int i = 0;
979 i < tileGeometryBin.randomModels.getNumModels(); i++) {
980 SGMatModelBin::MatModel obj
981 = tileGeometryBin.randomModels.getMatModel(i);
983 SGPropertyNode* root = options->getPropertyNode()->getRootNode();
984 osg::Node* node = obj.model->get_random_model(root, &seed);
986 // Create a matrix to place the object in the correct
987 // location, and then apply the rotation matrix created
988 // above, with an additional random (or taken from
989 // the object mask) heading rotation if appropriate.
990 osg::Matrix transformMat;
991 transformMat = osg::Matrix::translate(toOsg(obj.position));
992 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
993 // Rotate the object around the z axis.
994 double hdg = mt_rand(&seed) * M_PI * 2;
995 transformMat.preMult(osg::Matrix::rotate(hdg,
996 osg::Vec3d(0.0, 0.0, 1.0)));
999 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1000 // Rotate the object around the z axis.
1001 double hdg = - obj.rotation * M_PI * 2;
1002 transformMat.preMult(osg::Matrix::rotate(hdg,
1003 osg::Vec3d(0.0, 0.0, 1.0)));
1006 osg::MatrixTransform* position =
1007 new osg::MatrixTransform(transformMat);
1008 position->setName("positionRandomeModel");
1009 position->addChild(node);
1010 models.push_back(ModelLOD(position, obj.lod));
1012 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1013 quadtree.buildQuadTree(models.begin(), models.end());
1014 randomObjects = quadtree.getRoot();
1015 randomObjects->setName("Random objects");
1018 if (! tileGeometryBin.randomBuildings.empty()) {
1019 buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1021 buildingNode->setName("Random buildings");
1024 if (use_random_vegetation && matlib) {
1025 // Now add some random forest.
1026 tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1028 if (! tileGeometryBin.randomForest.empty()) {
1029 forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1031 forestNode->setName("Random trees");
1035 // FIXME: ugly, has a side effect
1037 tileGeometryBin.computeRandomSurfaceLights(matlib);
1039 if (tileGeometryBin.tileLights.getNumLights() > 0
1040 || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1041 osg::Group* groundLights0 = new osg::Group;
1042 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1043 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1044 osg::Geode* geode = new osg::Geode;
1045 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1046 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1047 groundLights0->addChild(geode);
1048 lightGroup->addChild(groundLights0);
1051 if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1052 osg::Group* groundLights1 = new osg::Group;
1053 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1054 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1055 osg::Group* groundLights2 = new osg::Group;
1056 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1057 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1058 osg::Geode* geode = new osg::Geode;
1059 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1060 groundLights1->addChild(geode);
1061 lightGroup->addChild(groundLights1);
1062 geode = new osg::Geode;
1063 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1064 groundLights2->addChild(geode);
1065 lightGroup->addChild(groundLights2);
1068 if (!tileGeometryBin.vasiLights.empty()) {
1069 EffectGeode* vasiGeode = new EffectGeode;
1071 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1072 vasiGeode->setEffect(vasiEffect);
1073 SGVec4f red(1, 0, 0, 1);
1074 SGMaterial* mat = 0;
1076 mat = matlib->find("RWY_RED_LIGHTS");
1078 red = mat->get_light_color();
1079 SGVec4f white(1, 1, 1, 1);
1082 mat = matlib->find("RWY_WHITE_LIGHTS");
1084 white = mat->get_light_color();
1085 SGDirectionalLightListBin::const_iterator i;
1086 for (i = tileGeometryBin.vasiLights.begin();
1087 i != tileGeometryBin.vasiLights.end(); ++i) {
1088 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1090 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1091 lightGroup->addChild(vasiGeode);
1094 Effect* runwayEffect = 0;
1095 if (tileGeometryBin.runwayLights.getNumLights() > 0
1096 || !tileGeometryBin.rabitLights.empty()
1097 || !tileGeometryBin.reilLights.empty()
1098 || !tileGeometryBin.odalLights.empty()
1099 || tileGeometryBin.taxiLights.getNumLights() > 0)
1100 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1101 if (tileGeometryBin.runwayLights.getNumLights() > 0
1102 || !tileGeometryBin.rabitLights.empty()
1103 || !tileGeometryBin.reilLights.empty()
1104 || !tileGeometryBin.odalLights.empty()
1105 || !tileGeometryBin.holdshortLights.empty()
1106 || !tileGeometryBin.guardLights.empty()) {
1107 osg::Group* rwyLights = new osg::Group;
1108 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1109 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1110 if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1111 EffectGeode* geode = new EffectGeode;
1112 geode->setEffect(runwayEffect);
1113 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1115 rwyLights->addChild(geode);
1117 SGDirectionalLightListBin::const_iterator i;
1118 for (i = tileGeometryBin.rabitLights.begin();
1119 i != tileGeometryBin.rabitLights.end(); ++i) {
1120 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1122 for (i = tileGeometryBin.reilLights.begin();
1123 i != tileGeometryBin.reilLights.end(); ++i) {
1124 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1126 for (i = tileGeometryBin.holdshortLights.begin();
1127 i != tileGeometryBin.holdshortLights.end(); ++i) {
1128 rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1130 for (i = tileGeometryBin.guardLights.begin();
1131 i != tileGeometryBin.guardLights.end(); ++i) {
1132 rwyLights->addChild(SGLightFactory::getGuard(*i));
1134 SGLightListBin::const_iterator j;
1135 for (j = tileGeometryBin.odalLights.begin();
1136 j != tileGeometryBin.odalLights.end(); ++j) {
1137 rwyLights->addChild(SGLightFactory::getOdal(*j));
1139 lightGroup->addChild(rwyLights);
1142 if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1143 osg::Group* taxiLights = new osg::Group;
1144 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1145 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1146 EffectGeode* geode = new EffectGeode;
1147 geode->setEffect(runwayEffect);
1148 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1149 taxiLights->addChild(geode);
1150 lightGroup->addChild(taxiLights);
1153 // The toplevel transform for that tile.
1154 osg::MatrixTransform* transform = new osg::MatrixTransform;
1155 transform->setName(path);
1156 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1157 osg::Matrix::translate(toOsg(center)));
1158 transform->addChild(terrainGroup);
1159 if (lightGroup->getNumChildren() > 0) {
1160 osg::LOD* lightLOD = new osg::LOD;
1161 lightLOD->addChild(lightGroup.get(), 0, 60000);
1162 // VASI is always on, so doesn't use light bits.
1163 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1164 transform->addChild(lightLOD);
1167 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1169 // Add a LoD node, so we don't try to display anything when the tile center
1170 // is more than 20km away.
1171 osg::LOD* objectLOD = new osg::LOD;
1173 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1174 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1175 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1177 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1178 objectLOD->setNodeMask(nodeMask);
1179 transform->addChild(objectLOD);
1181 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );