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;
403 eg->setEffect(mat->get_effect(i->second));
404 eg->addDrawable(geometry);
405 eg->runGenerators(geometry); // Generate extra data needed by effect
415 void computeRandomSurfaceLights(SGMaterialLib* matlib)
417 SGMaterialTriangleMap::iterator i;
419 // generate a repeatable random seed
421 mt_init(&seed, unsigned(123));
423 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
424 SGMaterial *mat = matlib->find(i->first);
428 float coverage = mat->get_light_coverage();
431 if (coverage < 10000.0) {
432 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
433 << coverage << ", pushing up to 10000");
437 std::vector<SGVec3f> randomPoints;
438 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
439 std::vector<SGVec3f>::iterator j;
440 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
441 float zombie = mt_rand(&seed);
442 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
443 float factor = mt_rand(&seed);
448 if ( zombie > 0.5 ) {
449 // 50% chance of yellowish
450 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
451 } else if (zombie > 0.15f) {
452 // 35% chance of whitish
453 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
454 } else if (zombie > 0.05f) {
455 // 10% chance of orangish
456 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
458 // 5% chance of redish
459 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
461 randomTileLights.insert(*j, color);
466 void computeRandomObjectsAndBuildings(
467 SGMaterialLib* matlib,
468 float building_density,
469 bool use_random_objects,
470 bool use_random_buildings)
472 SGMaterialTriangleMap::iterator i;
474 // generate a repeatable random seed
476 mt_init(&seed, unsigned(123));
478 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
479 SGMaterial *mat = matlib->find(i->first);
480 SGTexturedTriangleBin triangleBin = i->second;
485 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
486 int group_count = mat->get_object_group_count();
487 float building_coverage = mat->get_building_coverage();
488 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
489 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
492 SGBuildingBin* bin = NULL;
494 if (building_coverage > 0) {
495 BOOST_FOREACH(bin, randomBuildings)
497 if (bin->getMaterialName() == mat->get_names()[0]) {
504 bin = new SGBuildingBin(mat);
505 randomBuildings.push_back(bin);
509 unsigned num = i->second.getNumTriangles();
510 int random_dropped = 0;
511 int mask_dropped = 0;
512 int building_dropped = 0;
513 int triangle_dropped = 0;
515 for (unsigned i = 0; i < num; ++i) {
516 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
518 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
519 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
520 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
521 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
522 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
523 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
524 SGVec3f normal = cross(v0, v1);
526 // Ensure the slope isn't too steep by checking the
527 // cos of the angle between the slope normal and the
528 // vertical (conveniently the z-component of the normalized
529 // normal) and values passed in.
530 float cos = normalize(normal).z();
531 float slope_density = 1.0;
532 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
533 if (cos < cos_max_density_angle) {
535 (cos - cos_zero_density_angle) /
536 (cos_max_density_angle - cos_zero_density_angle);
539 // Containers to hold the random buildings and objects generated
540 // for this triangle for collision detection purposes.
541 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
542 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
545 float area = 0.5f*length(normal);
546 if (area <= SGLimitsf::min())
549 // Generate any random objects
550 if (use_random_objects && (group_count > 0))
552 for (int j = 0; j < group_count; j++)
554 SGMatModelGroup *object_group = mat->get_object_group(j);
555 int nObjects = object_group->get_object_count();
557 if (nObjects == 0) continue;
559 // For each of the random models in the group, determine an appropriate
560 // number of random placements and insert them.
561 for (int k = 0; k < nObjects; k++) {
562 SGMatModel * object = object_group->get_object(k);
564 // Determine the number of objecst to place, taking into account
565 // the slope density factor.
566 double n = slope_density * area / object->get_coverage_m2();
568 // Use the zombie door method to determine fractional object placement.
569 n = n + mt_rand(&seed);
571 // place an object each unit of area
573 float a = mt_rand(&seed);
574 float b = mt_rand(&seed);
580 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
581 float rotation = static_cast<float>(mt_rand(&seed));
583 // Check that the point is sufficiently far from
584 // the edge of the triangle by measuring the distance
585 // from the three lines that make up the triangle.
586 float spacing = object->get_spacing_m();
588 SGVec3f p = randomPoint - vorigin;
589 float edges[] = { length(cross(p , p - v0)) / length(v0),
590 length(cross(p - v0, p - v1)) / length(v1 - v0),
591 length(cross(p - v1, p )) / length(v1) };
592 float edge_dist = *std::min_element(edges, edges + 3);
594 if (edge_dist < spacing) {
599 if (object_mask != NULL) {
600 SGVec2f texCoord = torigin + a*t0 + b*t1;
602 // Check this random point against the object mask
603 // blue (for buildings) channel.
604 osg::Image* img = object_mask->getImage();
605 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
606 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
608 if (mt_rand(&seed) > img->getColor(x, y).b()) {
609 // Failed object mask check
614 rotation = img->getColor(x,y).r();
619 // Check it isn't too close to any other random objects in the triangle
620 std::vector<std::pair<SGVec3f, float> >::iterator l;
621 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
622 float min_dist2 = (l->second + object->get_spacing_m()) *
623 (l->second + object->get_spacing_m());
625 if (distSqr(l->first, randomPoint) > min_dist2) {
632 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
633 randomModels.insert(randomPoint,
635 (int)object->get_randomized_range_m(&seed),
645 // Random objects now generated. Now generate the random buildings (if any);
646 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
648 // Calculate the number of buildings, taking into account building density (which is linear)
649 // and the slope density factor.
650 double num = building_density * building_density * slope_density * area / building_coverage;
652 // For partial units of area, use a zombie door method to
653 // create the proper random chance of an object being created
654 // for this triangle.
655 num = num + mt_rand(&seed);
661 // Cosine of the angle between the two vectors.
662 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
664 // Determine a grid spacing in each vector such that the correct
665 // coverage will result.
666 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
667 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
669 stepv0 = std::min(stepv0, 1.0f);
670 stepv1 = std::min(stepv1, 1.0f);
672 // Start at a random point. a will be immediately incremented below.
673 float a = -mt_rand(&seed) * stepv0;
674 float b = mt_rand(&seed) * stepv1;
676 // Place an object each unit of area
679 // Set the next location to place a building
682 if ((a + b) > 1.0f) {
683 // Reached the end of the scan-line on v0. Reset and increment
685 a = mt_rand(&seed) * stepv0;
690 // In a degenerate case of a single point, we might be outside the
691 // scanline. Note that we need to still ensure that a+b < 1.
692 b = mt_rand(&seed) * stepv1 * (1.0f - a);
695 if ((a + b) > 1.0f ) {
696 // Truly degenerate case - simply choose a random point guaranteed
697 // to fulfil the constraing of a+b < 1.
699 b = mt_rand(&seed) * (1.0f - a);
702 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
703 float rotation = mt_rand(&seed);
705 if (object_mask != NULL) {
706 SGVec2f texCoord = torigin + a*t0 + b*t1;
707 osg::Image* img = object_mask->getImage();
708 int x = (int) (img->s() * texCoord.x()) % img->s();
709 int y = (int) (img->t() * texCoord.y()) % img->t();
711 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
712 while (x < 0) x += img->s();
713 while (y < 0) y += img->t();
715 if (mt_rand(&seed) < img->getColor(x, y).b()) {
716 // Object passes mask. Rotation is taken from the red channel
717 rotation = img->getColor(x,y).r();
719 // Fails mask test - try again.
726 // Check building isn't too close to the triangle edge.
727 float type_roll = mt_rand(&seed);
728 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
729 float radius = bin->getBuildingMaxRadius(buildingtype);
731 // Determine the actual center of the building, by shifting from the
732 // center of the front face to the true center.
733 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
734 osg::Vec3f(0.0, 0.0, 1.0));
735 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
737 SGVec3f p = buildingCenter - vorigin;
738 float edges[] = { length(cross(p , p - v0)) / length(v0),
739 length(cross(p - v0, p - v1)) / length(v1 - v0),
740 length(cross(p - v1, p )) / length(v1) };
741 float edge_dist = *std::min_element(edges, edges + 3);
743 if (edge_dist < radius) {
749 // Check building isn't too close to random objects and other buildings.
751 std::vector<std::pair<SGVec3f, float> >::iterator iter;
753 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
754 float min_dist = iter->second + radius;
755 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
767 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
768 float min_dist = iter->second + radius;
769 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
781 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
782 triangleBuildingList.push_back(pt);
783 bin->insert(randomPoint, rotation, buildingtype);
788 triangleObjectsList.clear();
789 triangleBuildingList.clear();
792 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << ((bin) ? bin->getNumBuildings() : 0));
793 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
794 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
795 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
799 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
801 SGMaterialTriangleMap::iterator i;
803 // generate a repeatable random seed
806 mt_init(&seed, unsigned(586));
808 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
809 SGMaterial *mat = matlib->find(i->first);
813 float wood_coverage = mat->get_wood_coverage();
814 if ((wood_coverage <= 0) || (vegetation_density <= 0))
817 // Attributes that don't vary by tree but do vary by material
821 BOOST_FOREACH(bin, randomForest)
823 if ((bin->texture == mat->get_tree_texture() ) &&
824 (bin->texture_varieties == mat->get_tree_varieties()) &&
825 (bin->range == mat->get_tree_range() ) &&
826 (bin->width == mat->get_tree_width() ) &&
827 (bin->height == mat->get_tree_height() ) ) {
835 bin->texture = mat->get_tree_texture();
836 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
837 bin->range = mat->get_tree_range();
838 bin->width = mat->get_tree_width();
839 bin->height = mat->get_tree_height();
840 bin->texture_varieties = mat->get_tree_varieties();
841 randomForest.push_back(bin);
844 std::vector<SGVec3f> randomPoints;
845 i->second.addRandomTreePoints(wood_coverage,
846 mat->get_object_mask(i->second),
848 mat->get_cos_tree_max_density_slope_angle(),
849 mat->get_cos_tree_zero_density_slope_angle(),
852 std::vector<SGVec3f>::iterator k;
853 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
859 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
861 if (!insertPtGeometry(obj, matlib))
863 if (!insertSurfaceGeometry(obj, matlib))
869 typedef std::pair<osg::Node*, int> ModelLOD;
870 struct MakeQuadLeaf {
871 osg::LOD* operator() () const { return new osg::LOD; }
874 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
876 leaf->addChild(mlod.first, 0, mlod.second);
879 struct GetModelLODCoord {
880 GetModelLODCoord() {}
881 GetModelLODCoord(const GetModelLODCoord& rhs)
883 osg::Vec3 operator() (const ModelLOD& mlod) const
885 return mlod.first->getBound().center();
889 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
890 GetModelLODCoord> RandomObjectsQuadtree;
893 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
896 if (!tile.read_bin(path))
899 SGMaterialLib* matlib = 0;
900 bool use_random_objects = false;
901 bool use_random_vegetation = false;
902 bool use_random_buildings = false;
903 float vegetation_density = 1.0f;
904 float building_density = 1.0f;
906 matlib = options->getMaterialLib();
907 SGPropertyNode* propertyNode = options->getPropertyNode().get();
910 = propertyNode->getBoolValue("/sim/rendering/random-objects",
912 use_random_vegetation
913 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
914 use_random_vegetation);
916 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
919 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
920 use_random_buildings);
922 = propertyNode->getFloatValue("/sim/rendering/building-density",
927 SGVec3d center = tile.get_gbs_center();
928 SGGeod geodPos = SGGeod::fromCart(center);
929 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
931 // rotate the tiles so that the bounding boxes get nearly axis aligned.
932 // this will help the collision tree's bounding boxes a bit ...
933 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
934 for (unsigned i = 0; i < nodes.size(); ++i)
935 nodes[i] = hlOr.transform(nodes[i]);
936 tile.set_wgs84_nodes(nodes);
938 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
939 std::vector<SGVec3f> normals = tile.get_normals();
940 for (unsigned i = 0; i < normals.size(); ++i)
941 normals[i] = hlOrf.transform(normals[i]);
942 tile.set_normals(normals);
944 SGTileGeometryBin tileGeometryBin;
945 if (!tileGeometryBin.insertBinObj(tile, matlib))
949 GroundLightManager* lightManager = GroundLightManager::instance();
951 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
952 osg::ref_ptr<osg::Group> randomObjects;
953 osg::ref_ptr<osg::Group> forestNode;
954 osg::ref_ptr<osg::Group> buildingNode;
955 osg::Group* terrainGroup = new osg::Group;
957 osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
959 terrainGroup->addChild(node);
961 if (matlib && (use_random_objects || use_random_buildings)) {
962 tileGeometryBin.computeRandomObjectsAndBuildings(matlib,
965 use_random_buildings);
968 if (tileGeometryBin.randomModels.getNumModels() > 0) {
969 // Generate a repeatable random seed
971 mt_init(&seed, unsigned(123));
973 std::vector<ModelLOD> models;
974 for (unsigned int i = 0;
975 i < tileGeometryBin.randomModels.getNumModels(); i++) {
976 SGMatModelBin::MatModel obj
977 = tileGeometryBin.randomModels.getMatModel(i);
979 SGPropertyNode* root = options->getPropertyNode()->getRootNode();
980 osg::Node* node = obj.model->get_random_model(root, &seed);
982 // Create a matrix to place the object in the correct
983 // location, and then apply the rotation matrix created
984 // above, with an additional random (or taken from
985 // the object mask) heading rotation if appropriate.
986 osg::Matrix transformMat;
987 transformMat = osg::Matrix::translate(toOsg(obj.position));
988 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
989 // Rotate the object around the z axis.
990 double hdg = mt_rand(&seed) * M_PI * 2;
991 transformMat.preMult(osg::Matrix::rotate(hdg,
992 osg::Vec3d(0.0, 0.0, 1.0)));
995 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
996 // Rotate the object around the z axis.
997 double hdg = - obj.rotation * M_PI * 2;
998 transformMat.preMult(osg::Matrix::rotate(hdg,
999 osg::Vec3d(0.0, 0.0, 1.0)));
1002 osg::MatrixTransform* position =
1003 new osg::MatrixTransform(transformMat);
1004 position->addChild(node);
1005 models.push_back(ModelLOD(position, obj.lod));
1007 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1008 quadtree.buildQuadTree(models.begin(), models.end());
1009 randomObjects = quadtree.getRoot();
1010 randomObjects->setName("Random objects");
1013 if (tileGeometryBin.randomBuildings.size() > 0) {
1014 buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1016 buildingNode->setName("Random buildings");
1019 if (use_random_vegetation && matlib) {
1020 // Now add some random forest.
1021 tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1023 if (tileGeometryBin.randomForest.size() > 0) {
1024 forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1026 forestNode->setName("Random trees");
1030 // FIXME: ugly, has a side effect
1032 tileGeometryBin.computeRandomSurfaceLights(matlib);
1034 if (tileGeometryBin.tileLights.getNumLights() > 0
1035 || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1036 osg::Group* groundLights0 = new osg::Group;
1037 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1038 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1039 osg::Geode* geode = new osg::Geode;
1040 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1041 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1042 groundLights0->addChild(geode);
1043 lightGroup->addChild(groundLights0);
1046 if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1047 osg::Group* groundLights1 = new osg::Group;
1048 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1049 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1050 osg::Group* groundLights2 = new osg::Group;
1051 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1052 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1053 osg::Geode* geode = new osg::Geode;
1054 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1055 groundLights1->addChild(geode);
1056 lightGroup->addChild(groundLights1);
1057 geode = new osg::Geode;
1058 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1059 groundLights2->addChild(geode);
1060 lightGroup->addChild(groundLights2);
1063 if (!tileGeometryBin.vasiLights.empty()) {
1064 EffectGeode* vasiGeode = new EffectGeode;
1066 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1067 vasiGeode->setEffect(vasiEffect);
1068 SGVec4f red(1, 0, 0, 1);
1069 SGMaterial* mat = 0;
1071 mat = matlib->find("RWY_RED_LIGHTS");
1073 red = mat->get_light_color();
1074 SGVec4f white(1, 1, 1, 1);
1077 mat = matlib->find("RWY_WHITE_LIGHTS");
1079 white = mat->get_light_color();
1080 SGDirectionalLightListBin::const_iterator i;
1081 for (i = tileGeometryBin.vasiLights.begin();
1082 i != tileGeometryBin.vasiLights.end(); ++i) {
1083 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1085 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1086 lightGroup->addChild(vasiGeode);
1089 Effect* runwayEffect = 0;
1090 if (tileGeometryBin.runwayLights.getNumLights() > 0
1091 || !tileGeometryBin.rabitLights.empty()
1092 || !tileGeometryBin.reilLights.empty()
1093 || !tileGeometryBin.odalLights.empty()
1094 || tileGeometryBin.taxiLights.getNumLights() > 0)
1095 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1096 if (tileGeometryBin.runwayLights.getNumLights() > 0
1097 || !tileGeometryBin.rabitLights.empty()
1098 || !tileGeometryBin.reilLights.empty()
1099 || !tileGeometryBin.odalLights.empty()
1100 || !tileGeometryBin.holdshortLights.empty()
1101 || !tileGeometryBin.guardLights.empty()) {
1102 osg::Group* rwyLights = new osg::Group;
1103 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1104 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1105 if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1106 EffectGeode* geode = new EffectGeode;
1107 geode->setEffect(runwayEffect);
1108 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1110 rwyLights->addChild(geode);
1112 SGDirectionalLightListBin::const_iterator i;
1113 for (i = tileGeometryBin.rabitLights.begin();
1114 i != tileGeometryBin.rabitLights.end(); ++i) {
1115 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1117 for (i = tileGeometryBin.reilLights.begin();
1118 i != tileGeometryBin.reilLights.end(); ++i) {
1119 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1121 for (i = tileGeometryBin.holdshortLights.begin();
1122 i != tileGeometryBin.holdshortLights.end(); ++i) {
1123 rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1125 for (i = tileGeometryBin.guardLights.begin();
1126 i != tileGeometryBin.guardLights.end(); ++i) {
1127 rwyLights->addChild(SGLightFactory::getGuard(*i));
1129 SGLightListBin::const_iterator j;
1130 for (j = tileGeometryBin.odalLights.begin();
1131 j != tileGeometryBin.odalLights.end(); ++j) {
1132 rwyLights->addChild(SGLightFactory::getOdal(*j));
1134 lightGroup->addChild(rwyLights);
1137 if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1138 osg::Group* taxiLights = new osg::Group;
1139 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1140 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1141 EffectGeode* geode = new EffectGeode;
1142 geode->setEffect(runwayEffect);
1143 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1144 taxiLights->addChild(geode);
1145 lightGroup->addChild(taxiLights);
1148 // The toplevel transform for that tile.
1149 osg::MatrixTransform* transform = new osg::MatrixTransform;
1150 transform->setName(path);
1151 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1152 osg::Matrix::translate(toOsg(center)));
1153 transform->addChild(terrainGroup);
1154 if (lightGroup->getNumChildren() > 0) {
1155 osg::LOD* lightLOD = new osg::LOD;
1156 lightLOD->addChild(lightGroup.get(), 0, 60000);
1157 // VASI is always on, so doesn't use light bits.
1158 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1159 transform->addChild(lightLOD);
1162 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1164 // Add a LoD node, so we don't try to display anything when the tile center
1165 // is more than 20km away.
1166 osg::LOD* objectLOD = new osg::LOD;
1168 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1169 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1170 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1172 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1173 objectLOD->setNodeMask(nodeMask);
1174 transform->addChild(objectLOD);
1176 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );