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 reilLights;
92 SGMatModelBin randomModels;
93 SGBuildingBinList randomBuildings;
96 getMaterialLightColor(const SGMaterial* material)
99 return SGVec4f(1, 1, 1, 0.8);
100 return material->get_light_color();
104 addPointGeometry(SGLightBin& lights,
105 const std::vector<SGVec3d>& vertices,
106 const SGVec4f& color,
107 const int_list& pts_v)
109 for (unsigned i = 0; i < pts_v.size(); ++i)
110 lights.insert(toVec3f(vertices[pts_v[i]]), color);
114 addPointGeometry(SGDirectionalLightBin& lights,
115 const std::vector<SGVec3d>& vertices,
116 const std::vector<SGVec3f>& normals,
117 const SGVec4f& color,
118 const int_list& pts_v,
119 const int_list& pts_n)
121 // If the normal indices match the vertex indices, use seperate
122 // normal indices. Else reuse the vertex indices for the normals.
123 if (pts_v.size() == pts_n.size()) {
124 for (unsigned i = 0; i < pts_v.size(); ++i)
125 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
127 for (unsigned i = 0; i < pts_v.size(); ++i)
128 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
133 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
135 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
136 SG_LOG(SG_TERRAIN, SG_ALERT,
137 "Group list sizes for points do not match!");
141 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
142 std::string materialName = obj.get_pt_materials()[grp];
143 SGMaterial* material = 0;
145 material = matlib->find(materialName);
146 SGVec4f color = getMaterialLightColor(material);
148 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
149 // Just plain lights. Not something for the runway.
150 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
151 obj.get_pts_v()[grp]);
152 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
153 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
154 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
155 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
156 } else if (materialName == "RWY_VASI_LIGHTS") {
157 vasiLights.push_back(SGDirectionalLightBin());
158 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
159 obj.get_normals(), color, obj.get_pts_v()[grp],
160 obj.get_pts_n()[grp]);
161 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
162 rabitLights.push_back(SGDirectionalLightBin());
163 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
164 obj.get_normals(), color, obj.get_pts_v()[grp],
165 obj.get_pts_n()[grp]);
166 } else if (materialName == "RWY_ODALS_LIGHTS") {
167 odalLights.push_back(SGLightBin());
168 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
169 color, obj.get_pts_v()[grp]);
170 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
171 holdshortLights.push_back(SGDirectionalLightBin());
172 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
173 obj.get_normals(), color, obj.get_pts_v()[grp],
174 obj.get_pts_n()[grp]);
175 } else if (materialName == "RWY_REIL_LIGHTS") {
176 reilLights.push_back(SGDirectionalLightBin());
177 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
178 obj.get_normals(), color, obj.get_pts_v()[grp],
179 obj.get_pts_n()[grp]);
181 // what is left must be runway lights
182 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
183 obj.get_normals(), color, obj.get_pts_v()[grp],
184 obj.get_pts_n()[grp]);
193 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
194 const SGVec2f& tcScale, unsigned i)
198 else if (tc.size() == 1)
199 return mult(texCoords[tc[0]], tcScale);
201 return mult(texCoords[tc[i]], tcScale);
205 addTriangleGeometry(SGTexturedTriangleBin& triangles,
206 const std::vector<SGVec3d>& vertices,
207 const std::vector<SGVec3f>& normals,
208 const std::vector<SGVec2f>& texCoords,
209 const int_list& tris_v,
210 const int_list& tris_n,
211 const int_list& tris_tc,
212 const SGVec2f& tcScale)
214 if (tris_v.size() != tris_n.size()) {
215 // If the normal indices do not match, they should be inmplicitly
216 // the same than the vertex indices. So just call ourselves again
217 // with the matching index vector.
218 addTriangleGeometry(triangles, vertices, normals, texCoords,
219 tris_v, tris_v, tris_tc, tcScale);
223 for (unsigned i = 2; i < tris_v.size(); i += 3) {
225 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
226 v0.normal = normals[tris_n[i-2]];
227 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
229 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
230 v1.normal = normals[tris_n[i-1]];
231 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
233 v2.vertex = toVec3f(vertices[tris_v[i]]);
234 v2.normal = normals[tris_n[i]];
235 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
236 triangles.insert(v0, v1, v2);
241 addStripGeometry(SGTexturedTriangleBin& triangles,
242 const std::vector<SGVec3d>& vertices,
243 const std::vector<SGVec3f>& normals,
244 const std::vector<SGVec2f>& texCoords,
245 const int_list& strips_v,
246 const int_list& strips_n,
247 const int_list& strips_tc,
248 const SGVec2f& tcScale)
250 if (strips_v.size() != strips_n.size()) {
251 // If the normal indices do not match, they should be inmplicitly
252 // the same than the vertex indices. So just call ourselves again
253 // with the matching index vector.
254 addStripGeometry(triangles, vertices, normals, texCoords,
255 strips_v, strips_v, strips_tc, tcScale);
259 for (unsigned i = 2; i < strips_v.size(); ++i) {
261 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
262 v0.normal = normals[strips_n[i-2]];
263 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
265 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
266 v1.normal = normals[strips_n[i-1]];
267 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
269 v2.vertex = toVec3f(vertices[strips_v[i]]);
270 v2.normal = normals[strips_n[i]];
271 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
273 triangles.insert(v1, v0, v2);
275 triangles.insert(v0, v1, v2);
280 addFanGeometry(SGTexturedTriangleBin& triangles,
281 const std::vector<SGVec3d>& vertices,
282 const std::vector<SGVec3f>& normals,
283 const std::vector<SGVec2f>& texCoords,
284 const int_list& fans_v,
285 const int_list& fans_n,
286 const int_list& fans_tc,
287 const SGVec2f& tcScale)
289 if (fans_v.size() != fans_n.size()) {
290 // If the normal indices do not match, they should be implicitly
291 // the same than the vertex indices. So just call ourselves again
292 // with the matching index vector.
293 addFanGeometry(triangles, vertices, normals, texCoords,
294 fans_v, fans_v, fans_tc, tcScale);
299 v0.vertex = toVec3f(vertices[fans_v[0]]);
300 v0.normal = normals[fans_n[0]];
301 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
303 v1.vertex = toVec3f(vertices[fans_v[1]]);
304 v1.normal = normals[fans_n[1]];
305 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
306 for (unsigned i = 2; i < fans_v.size(); ++i) {
308 v2.vertex = toVec3f(vertices[fans_v[i]]);
309 v2.normal = normals[fans_n[i]];
310 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
311 triangles.insert(v0, v1, v2);
316 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
319 return SGVec2f(1, 1);
320 SGMaterial* material = matlib->find(name);
322 return SGVec2f(1, 1);
324 return material->get_tex_coord_scale();
328 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
330 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
331 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
332 SG_LOG(SG_TERRAIN, SG_ALERT,
333 "Group list sizes for triangles do not match!");
337 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
338 std::string materialName = obj.get_tri_materials()[grp];
339 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
340 addTriangleGeometry(materialTriangleMap[materialName],
341 obj.get_wgs84_nodes(), obj.get_normals(),
342 obj.get_texcoords(), obj.get_tris_v()[grp],
343 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
347 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
348 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
349 SG_LOG(SG_TERRAIN, SG_ALERT,
350 "Group list sizes for strips do not match!");
353 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
354 std::string materialName = obj.get_strip_materials()[grp];
355 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
356 addStripGeometry(materialTriangleMap[materialName],
357 obj.get_wgs84_nodes(), obj.get_normals(),
358 obj.get_texcoords(), obj.get_strips_v()[grp],
359 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
363 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
364 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
365 SG_LOG(SG_TERRAIN, SG_ALERT,
366 "Group list sizes for fans do not match!");
369 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
370 std::string materialName = obj.get_fan_materials()[grp];
371 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
372 addFanGeometry(materialTriangleMap[materialName],
373 obj.get_wgs84_nodes(), obj.get_normals(),
374 obj.get_texcoords(), obj.get_fans_v()[grp],
375 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
381 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
383 if (materialTriangleMap.empty())
387 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
388 //osg::Geode* geode = new osg::Geode;
389 SGMaterialTriangleMap::const_iterator i;
390 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
391 osg::Geometry* geometry = i->second.buildGeometry();
394 mat = matlib->find(i->first);
395 eg = new EffectGeode;
397 eg->setEffect(mat->get_effect(i->second));
398 eg->addDrawable(geometry);
399 eg->runGenerators(geometry); // Generate extra data needed by effect
409 void computeRandomSurfaceLights(SGMaterialLib* matlib)
411 SGMaterialTriangleMap::iterator i;
413 // generate a repeatable random seed
415 mt_init(&seed, unsigned(123));
417 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
418 SGMaterial *mat = matlib->find(i->first);
422 float coverage = mat->get_light_coverage();
425 if (coverage < 10000.0) {
426 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
427 << coverage << ", pushing up to 10000");
431 std::vector<SGVec3f> randomPoints;
432 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
433 std::vector<SGVec3f>::iterator j;
434 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
435 float zombie = mt_rand(&seed);
436 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
437 float factor = mt_rand(&seed);
442 if ( zombie > 0.5 ) {
443 // 50% chance of yellowish
444 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
445 } else if (zombie > 0.15f) {
446 // 35% chance of whitish
447 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
448 } else if (zombie > 0.05f) {
449 // 10% chance of orangish
450 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
452 // 5% chance of redish
453 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
455 randomTileLights.insert(*j, color);
460 void computeRandomObjectsAndBuildings(
461 SGMaterialLib* matlib,
462 float building_density,
463 bool use_random_objects,
464 bool use_random_buildings)
466 SGMaterialTriangleMap::iterator i;
468 // generate a repeatable random seed
470 mt_init(&seed, unsigned(123));
472 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
473 SGMaterial *mat = matlib->find(i->first);
474 SGTexturedTriangleBin triangleBin = i->second;
479 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
480 int group_count = mat->get_object_group_count();
481 float building_coverage = mat->get_building_coverage();
482 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
483 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
486 SGBuildingBin* bin = NULL;
488 if (building_coverage > 0) {
489 BOOST_FOREACH(bin, randomBuildings)
491 if (bin->getMaterialName() == mat->get_names()[0]) {
498 bin = new SGBuildingBin(mat);
499 randomBuildings.push_back(bin);
503 unsigned num = i->second.getNumTriangles();
504 int random_dropped = 0;
505 int mask_dropped = 0;
506 int building_dropped = 0;
507 int triangle_dropped = 0;
509 for (unsigned i = 0; i < num; ++i) {
510 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
512 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
513 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
514 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
515 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
516 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
517 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
518 SGVec3f normal = cross(v0, v1);
520 // Ensure the slope isn't too steep by checking the
521 // cos of the angle between the slope normal and the
522 // vertical (conveniently the z-component of the normalized
523 // normal) and values passed in.
524 float cos = normalize(normal).z();
525 float slope_density = 1.0;
526 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
527 if (cos < cos_max_density_angle) {
529 (cos - cos_zero_density_angle) /
530 (cos_max_density_angle - cos_zero_density_angle);
533 // Containers to hold the random buildings and objects generated
534 // for this triangle for collision detection purposes.
535 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
536 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
539 float area = 0.5f*length(normal);
540 if (area <= SGLimitsf::min())
543 // Generate any random objects
544 if (use_random_objects && (group_count > 0))
546 for (int j = 0; j < group_count; j++)
548 SGMatModelGroup *object_group = mat->get_object_group(j);
549 int nObjects = object_group->get_object_count();
551 if (nObjects == 0) continue;
553 // For each of the random models in the group, determine an appropriate
554 // number of random placements and insert them.
555 for (int k = 0; k < nObjects; k++) {
556 SGMatModel * object = object_group->get_object(k);
558 // Determine the number of objecst to place, taking into account
559 // the slope density factor.
560 double n = slope_density * area / object->get_coverage_m2();
562 // Use the zombie door method to determine fractional object placement.
563 n = n + mt_rand(&seed);
565 // place an object each unit of area
567 float a = mt_rand(&seed);
568 float b = mt_rand(&seed);
574 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
575 float rotation = static_cast<float>(mt_rand(&seed));
577 // Check that the point is sufficiently far from
578 // the edge of the triangle by measuring the distance
579 // from the three lines that make up the triangle.
580 float spacing = object->get_spacing_m();
582 SGVec3f p = randomPoint - vorigin;
583 float edges[] = { length(cross(p , p - v0)) / length(v0),
584 length(cross(p - v0, p - v1)) / length(v1 - v0),
585 length(cross(p - v1, p )) / length(v1) };
586 float edge_dist = *std::min_element(edges, edges + 3);
588 if (edge_dist < spacing) {
593 if (object_mask != NULL) {
594 SGVec2f texCoord = torigin + a*t0 + b*t1;
596 // Check this random point against the object mask
597 // blue (for buildings) channel.
598 osg::Image* img = object_mask->getImage();
599 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
600 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
602 if (mt_rand(&seed) > img->getColor(x, y).b()) {
603 // Failed object mask check
608 rotation = img->getColor(x,y).r();
613 // Check it isn't too close to any other random objects in the triangle
614 std::vector<std::pair<SGVec3f, float> >::iterator l;
615 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
616 float min_dist2 = (l->second + object->get_spacing_m()) *
617 (l->second + object->get_spacing_m());
619 if (distSqr(l->first, randomPoint) > min_dist2) {
626 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
627 randomModels.insert(randomPoint,
629 (int)object->get_randomized_range_m(&seed),
639 // Random objects now generated. Now generate the random buildings (if any);
640 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
642 // Calculate the number of buildings, taking into account building density (which is linear)
643 // and the slope density factor.
644 double num = building_density * building_density * slope_density * area / building_coverage;
646 // For partial units of area, use a zombie door method to
647 // create the proper random chance of an object being created
648 // for this triangle.
649 num = num + mt_rand(&seed);
655 // Cosine of the angle between the two vectors.
656 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
658 // Determine a grid spacing in each vector such that the correct
659 // coverage will result.
660 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
661 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
663 stepv0 = std::min(stepv0, 1.0f);
664 stepv1 = std::min(stepv1, 1.0f);
666 // Start at a random point. a will be immediately incremented below.
667 float a = -mt_rand(&seed) * stepv0;
668 float b = mt_rand(&seed) * stepv1;
670 // Place an object each unit of area
673 // Set the next location to place a building
676 if ((a + b) > 1.0f) {
677 // Reached the end of the scan-line on v0. Reset and increment
679 a = mt_rand(&seed) * stepv0;
684 // In a degenerate case of a single point, we might be outside the
685 // scanline. Note that we need to still ensure that a+b < 1.
686 b = mt_rand(&seed) * stepv1 * (1.0f - a);
689 if ((a + b) > 1.0f ) {
690 // Truly degenerate case - simply choose a random point guaranteed
691 // to fulfil the constraing of a+b < 1.
693 b = mt_rand(&seed) * (1.0f - a);
696 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
697 float rotation = mt_rand(&seed);
699 if (object_mask != NULL) {
700 SGVec2f texCoord = torigin + a*t0 + b*t1;
701 osg::Image* img = object_mask->getImage();
702 int x = (int) (img->s() * texCoord.x()) % img->s();
703 int y = (int) (img->t() * texCoord.y()) % img->t();
705 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
706 while (x < 0) x += img->s();
707 while (y < 0) y += img->t();
709 if (mt_rand(&seed) < img->getColor(x, y).b()) {
710 // Object passes mask. Rotation is taken from the red channel
711 rotation = img->getColor(x,y).r();
713 // Fails mask test - try again.
720 // Check building isn't too close to the triangle edge.
721 float type_roll = mt_rand(&seed);
722 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
723 float radius = bin->getBuildingMaxRadius(buildingtype);
725 // Determine the actual center of the building, by shifting from the
726 // center of the front face to the true center.
727 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
728 osg::Vec3f(0.0, 0.0, 1.0));
729 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
731 SGVec3f p = buildingCenter - vorigin;
732 float edges[] = { length(cross(p , p - v0)) / length(v0),
733 length(cross(p - v0, p - v1)) / length(v1 - v0),
734 length(cross(p - v1, p )) / length(v1) };
735 float edge_dist = *std::min_element(edges, edges + 3);
737 if (edge_dist < radius) {
743 // Check building isn't too close to random objects and other buildings.
745 std::vector<std::pair<SGVec3f, float> >::iterator iter;
747 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
748 float min_dist = iter->second + radius;
749 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
761 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
762 float min_dist = iter->second + radius;
763 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
775 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
776 triangleBuildingList.push_back(pt);
777 bin->insert(randomPoint, rotation, buildingtype);
782 triangleObjectsList.clear();
783 triangleBuildingList.clear();
786 SG_LOG(SG_TERRAIN, SG_DEBUG, "Random Buildings: " << bin->getNumBuildings());
787 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
788 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to random object: " << random_dropped);
789 SG_LOG(SG_TERRAIN, SG_DEBUG, " Dropped due to other buildings: " << building_dropped);
793 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
795 SGMaterialTriangleMap::iterator i;
797 // generate a repeatable random seed
800 mt_init(&seed, unsigned(586));
802 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
803 SGMaterial *mat = matlib->find(i->first);
807 float wood_coverage = mat->get_wood_coverage();
808 if ((wood_coverage <= 0) || (vegetation_density <= 0))
811 // Attributes that don't vary by tree but do vary by material
815 BOOST_FOREACH(bin, randomForest)
817 if ((bin->texture == mat->get_tree_texture() ) &&
818 (bin->texture_varieties == mat->get_tree_varieties()) &&
819 (bin->range == mat->get_tree_range() ) &&
820 (bin->width == mat->get_tree_width() ) &&
821 (bin->height == mat->get_tree_height() ) ) {
829 bin->texture = mat->get_tree_texture();
830 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
831 bin->range = mat->get_tree_range();
832 bin->width = mat->get_tree_width();
833 bin->height = mat->get_tree_height();
834 bin->texture_varieties = mat->get_tree_varieties();
835 randomForest.push_back(bin);
838 std::vector<SGVec3f> randomPoints;
839 i->second.addRandomTreePoints(wood_coverage,
840 mat->get_object_mask(i->second),
842 mat->get_cos_tree_max_density_slope_angle(),
843 mat->get_cos_tree_zero_density_slope_angle(),
846 std::vector<SGVec3f>::iterator k;
847 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
853 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
855 if (!insertPtGeometry(obj, matlib))
857 if (!insertSurfaceGeometry(obj, matlib))
863 typedef std::pair<osg::Node*, int> ModelLOD;
864 struct MakeQuadLeaf {
865 osg::LOD* operator() () const { return new osg::LOD; }
868 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
870 leaf->addChild(mlod.first, 0, mlod.second);
873 struct GetModelLODCoord {
874 GetModelLODCoord() {}
875 GetModelLODCoord(const GetModelLODCoord& rhs)
877 osg::Vec3 operator() (const ModelLOD& mlod) const
879 return mlod.first->getBound().center();
883 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
884 GetModelLODCoord> RandomObjectsQuadtree;
887 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
890 if (!tile.read_bin(path))
893 SGMaterialLib* matlib = 0;
894 bool use_random_objects = false;
895 bool use_random_vegetation = false;
896 bool use_random_buildings = false;
897 float vegetation_density = 1.0f;
898 float building_density = 1.0f;
900 matlib = options->getMaterialLib();
901 SGPropertyNode* propertyNode = options->getPropertyNode().get();
904 = propertyNode->getBoolValue("/sim/rendering/random-objects",
906 use_random_vegetation
907 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
908 use_random_vegetation);
910 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
913 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
914 use_random_buildings);
916 = propertyNode->getFloatValue("/sim/rendering/building-density",
921 SGVec3d center = tile.get_gbs_center();
922 SGGeod geodPos = SGGeod::fromCart(center);
923 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
925 // rotate the tiles so that the bounding boxes get nearly axis aligned.
926 // this will help the collision tree's bounding boxes a bit ...
927 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
928 for (unsigned i = 0; i < nodes.size(); ++i)
929 nodes[i] = hlOr.transform(nodes[i]);
930 tile.set_wgs84_nodes(nodes);
932 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
933 std::vector<SGVec3f> normals = tile.get_normals();
934 for (unsigned i = 0; i < normals.size(); ++i)
935 normals[i] = hlOrf.transform(normals[i]);
936 tile.set_normals(normals);
938 SGTileGeometryBin tileGeometryBin;
939 if (!tileGeometryBin.insertBinObj(tile, matlib))
943 GroundLightManager* lightManager = GroundLightManager::instance();
945 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
946 osg::ref_ptr<osg::Group> randomObjects;
947 osg::ref_ptr<osg::Group> forestNode;
948 osg::ref_ptr<osg::Group> buildingNode;
949 osg::Group* terrainGroup = new osg::Group;
951 osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
953 terrainGroup->addChild(node);
955 if (matlib && (use_random_objects || use_random_buildings)) {
956 tileGeometryBin.computeRandomObjectsAndBuildings(matlib,
959 use_random_buildings);
962 if (tileGeometryBin.randomModels.getNumModels() > 0) {
963 // Generate a repeatable random seed
965 mt_init(&seed, unsigned(123));
967 std::vector<ModelLOD> models;
968 for (unsigned int i = 0;
969 i < tileGeometryBin.randomModels.getNumModels(); i++) {
970 SGMatModelBin::MatModel obj
971 = tileGeometryBin.randomModels.getMatModel(i);
973 SGPropertyNode* root = options->getPropertyNode()->getRootNode();
974 osg::Node* node = obj.model->get_random_model(root, &seed);
976 // Create a matrix to place the object in the correct
977 // location, and then apply the rotation matrix created
978 // above, with an additional random (or taken from
979 // the object mask) heading rotation if appropriate.
980 osg::Matrix transformMat;
981 transformMat = osg::Matrix::translate(toOsg(obj.position));
982 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
983 // Rotate the object around the z axis.
984 double hdg = mt_rand(&seed) * M_PI * 2;
985 transformMat.preMult(osg::Matrix::rotate(hdg,
986 osg::Vec3d(0.0, 0.0, 1.0)));
989 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
990 // Rotate the object around the z axis.
991 double hdg = - obj.rotation * M_PI * 2;
992 transformMat.preMult(osg::Matrix::rotate(hdg,
993 osg::Vec3d(0.0, 0.0, 1.0)));
996 osg::MatrixTransform* position =
997 new osg::MatrixTransform(transformMat);
998 position->addChild(node);
999 models.push_back(ModelLOD(position, obj.lod));
1001 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1002 quadtree.buildQuadTree(models.begin(), models.end());
1003 randomObjects = quadtree.getRoot();
1004 randomObjects->setName("Random objects");
1007 if (tileGeometryBin.randomBuildings.size() > 0) {
1008 buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1010 buildingNode->setName("Random buildings");
1013 if (use_random_vegetation && matlib) {
1014 // Now add some random forest.
1015 tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1017 if (tileGeometryBin.randomForest.size() > 0) {
1018 forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1020 forestNode->setName("Random trees");
1024 // FIXME: ugly, has a side effect
1026 tileGeometryBin.computeRandomSurfaceLights(matlib);
1028 if (tileGeometryBin.tileLights.getNumLights() > 0
1029 || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1030 osg::Group* groundLights0 = new osg::Group;
1031 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1032 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1033 osg::Geode* geode = new osg::Geode;
1034 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1035 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1036 groundLights0->addChild(geode);
1037 lightGroup->addChild(groundLights0);
1040 if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1041 osg::Group* groundLights1 = new osg::Group;
1042 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1043 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1044 osg::Group* groundLights2 = new osg::Group;
1045 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1046 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1047 osg::Geode* geode = new osg::Geode;
1048 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1049 groundLights1->addChild(geode);
1050 lightGroup->addChild(groundLights1);
1051 geode = new osg::Geode;
1052 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1053 groundLights2->addChild(geode);
1054 lightGroup->addChild(groundLights2);
1057 if (!tileGeometryBin.vasiLights.empty()) {
1058 EffectGeode* vasiGeode = new EffectGeode;
1060 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1061 vasiGeode->setEffect(vasiEffect);
1062 SGVec4f red(1, 0, 0, 1);
1063 SGMaterial* mat = 0;
1065 mat = matlib->find("RWY_RED_LIGHTS");
1067 red = mat->get_light_color();
1068 SGVec4f white(1, 1, 1, 1);
1071 mat = matlib->find("RWY_WHITE_LIGHTS");
1073 white = mat->get_light_color();
1074 SGDirectionalLightListBin::const_iterator i;
1075 for (i = tileGeometryBin.vasiLights.begin();
1076 i != tileGeometryBin.vasiLights.end(); ++i) {
1077 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1079 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1080 lightGroup->addChild(vasiGeode);
1083 Effect* runwayEffect = 0;
1084 if (tileGeometryBin.runwayLights.getNumLights() > 0
1085 || !tileGeometryBin.rabitLights.empty()
1086 || !tileGeometryBin.reilLights.empty()
1087 || !tileGeometryBin.odalLights.empty()
1088 || tileGeometryBin.taxiLights.getNumLights() > 0)
1089 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1090 if (tileGeometryBin.runwayLights.getNumLights() > 0
1091 || !tileGeometryBin.rabitLights.empty()
1092 || !tileGeometryBin.reilLights.empty()
1093 || !tileGeometryBin.odalLights.empty()
1094 || !tileGeometryBin.holdshortLights.empty()) {
1095 osg::Group* rwyLights = new osg::Group;
1096 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1097 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1098 if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1099 EffectGeode* geode = new EffectGeode;
1100 geode->setEffect(runwayEffect);
1101 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1103 rwyLights->addChild(geode);
1105 SGDirectionalLightListBin::const_iterator i;
1106 for (i = tileGeometryBin.rabitLights.begin();
1107 i != tileGeometryBin.rabitLights.end(); ++i) {
1108 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1110 for (i = tileGeometryBin.reilLights.begin();
1111 i != tileGeometryBin.reilLights.end(); ++i) {
1112 rwyLights->addChild(SGLightFactory::getSequenced(*i));
1114 for (i = tileGeometryBin.holdshortLights.begin();
1115 i != tileGeometryBin.holdshortLights.end(); ++i) {
1116 rwyLights->addChild(SGLightFactory::getHoldShort(*i));
1118 SGLightListBin::const_iterator j;
1119 for (j = tileGeometryBin.odalLights.begin();
1120 j != tileGeometryBin.odalLights.end(); ++j) {
1121 rwyLights->addChild(SGLightFactory::getOdal(*j));
1123 lightGroup->addChild(rwyLights);
1126 if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1127 osg::Group* taxiLights = new osg::Group;
1128 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1129 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1130 EffectGeode* geode = new EffectGeode;
1131 geode->setEffect(runwayEffect);
1132 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1133 taxiLights->addChild(geode);
1134 lightGroup->addChild(taxiLights);
1137 // The toplevel transform for that tile.
1138 osg::MatrixTransform* transform = new osg::MatrixTransform;
1139 transform->setName(path);
1140 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1141 osg::Matrix::translate(toOsg(center)));
1142 transform->addChild(terrainGroup);
1143 if (lightGroup->getNumChildren() > 0) {
1144 osg::LOD* lightLOD = new osg::LOD;
1145 lightLOD->addChild(lightGroup.get(), 0, 60000);
1146 // VASI is always on, so doesn't use light bits.
1147 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1148 transform->addChild(lightLOD);
1151 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1153 // Add a LoD node, so we don't try to display anything when the tile center
1154 // is more than 20km away.
1155 osg::LOD* objectLOD = new osg::LOD;
1157 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1158 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1159 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1161 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1162 objectLOD->setNodeMask(nodeMask);
1163 transform->addChild(objectLOD);
1165 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );