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/matlib.hxx>
56 #include <simgear/scene/model/SGOffsetTransform.hxx>
57 #include <simgear/scene/util/SGUpdateVisitor.hxx>
58 #include <simgear/scene/util/SGNodeMasks.hxx>
59 #include <simgear/scene/util/QuadTreeBuilder.hxx>
61 #include "SGTexturedTriangleBin.hxx"
62 #include "SGLightBin.hxx"
63 #include "SGModelBin.hxx"
64 #include "SGBuildingBin.hxx"
65 #include "TreeBin.hxx"
66 #include "SGDirectionalLightBin.hxx"
67 #include "GroundLightManager.hxx"
70 #include "pt_lights.hxx"
72 using namespace simgear;
74 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
75 typedef std::list<SGLightBin> SGLightListBin;
76 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
78 struct SGTileGeometryBin {
79 SGMaterialTriangleMap materialTriangleMap;
80 SGLightBin tileLights;
81 SGLightBin randomTileLights;
82 SGTreeBinList randomForest;
83 SGDirectionalLightBin runwayLights;
84 SGDirectionalLightBin taxiLights;
85 SGDirectionalLightListBin vasiLights;
86 SGDirectionalLightListBin rabitLights;
87 SGLightListBin odalLights;
88 SGDirectionalLightListBin holdshortLights;
89 SGDirectionalLightListBin reilLights;
90 SGMatModelBin randomModels;
91 SGBuildingBinList randomBuildings;
94 getMaterialLightColor(const SGMaterial* material)
97 return SGVec4f(1, 1, 1, 0.8);
98 return material->get_light_color();
102 addPointGeometry(SGLightBin& lights,
103 const std::vector<SGVec3d>& vertices,
104 const SGVec4f& color,
105 const int_list& pts_v)
107 for (unsigned i = 0; i < pts_v.size(); ++i)
108 lights.insert(toVec3f(vertices[pts_v[i]]), color);
112 addPointGeometry(SGDirectionalLightBin& lights,
113 const std::vector<SGVec3d>& vertices,
114 const std::vector<SGVec3f>& normals,
115 const SGVec4f& color,
116 const int_list& pts_v,
117 const int_list& pts_n)
119 // If the normal indices match the vertex indices, use seperate
120 // normal indices. Else reuse the vertex indices for the normals.
121 if (pts_v.size() == pts_n.size()) {
122 for (unsigned i = 0; i < pts_v.size(); ++i)
123 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
125 for (unsigned i = 0; i < pts_v.size(); ++i)
126 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
131 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
133 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
134 SG_LOG(SG_TERRAIN, SG_ALERT,
135 "Group list sizes for points do not match!");
139 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
140 std::string materialName = obj.get_pt_materials()[grp];
141 SGMaterial* material = 0;
143 material = matlib->find(materialName);
144 SGVec4f color = getMaterialLightColor(material);
146 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
147 // Just plain lights. Not something for the runway.
148 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
149 obj.get_pts_v()[grp]);
150 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
151 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
152 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
153 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
154 } else if (materialName == "RWY_VASI_LIGHTS") {
155 vasiLights.push_back(SGDirectionalLightBin());
156 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
157 obj.get_normals(), color, obj.get_pts_v()[grp],
158 obj.get_pts_n()[grp]);
159 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
160 rabitLights.push_back(SGDirectionalLightBin());
161 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
162 obj.get_normals(), color, obj.get_pts_v()[grp],
163 obj.get_pts_n()[grp]);
164 } else if (materialName == "RWY_ODALS_LIGHTS") {
165 odalLights.push_back(SGLightBin());
166 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
167 color, obj.get_pts_v()[grp]);
168 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
169 holdshortLights.push_back(SGDirectionalLightBin());
170 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
171 obj.get_normals(), color, obj.get_pts_v()[grp],
172 obj.get_pts_n()[grp]);
173 } else if (materialName == "RWY_REIL_LIGHTS") {
174 reilLights.push_back(SGDirectionalLightBin());
175 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
176 obj.get_normals(), color, obj.get_pts_v()[grp],
177 obj.get_pts_n()[grp]);
179 // what is left must be runway lights
180 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
181 obj.get_normals(), color, obj.get_pts_v()[grp],
182 obj.get_pts_n()[grp]);
191 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
192 const SGVec2f& tcScale, unsigned i)
196 else if (tc.size() == 1)
197 return mult(texCoords[tc[0]], tcScale);
199 return mult(texCoords[tc[i]], tcScale);
203 addTriangleGeometry(SGTexturedTriangleBin& triangles,
204 const std::vector<SGVec3d>& vertices,
205 const std::vector<SGVec3f>& normals,
206 const std::vector<SGVec2f>& texCoords,
207 const int_list& tris_v,
208 const int_list& tris_n,
209 const int_list& tris_tc,
210 const SGVec2f& tcScale)
212 if (tris_v.size() != tris_n.size()) {
213 // If the normal indices do not match, they should be inmplicitly
214 // the same than the vertex indices. So just call ourselves again
215 // with the matching index vector.
216 addTriangleGeometry(triangles, vertices, normals, texCoords,
217 tris_v, tris_v, tris_tc, tcScale);
221 for (unsigned i = 2; i < tris_v.size(); i += 3) {
223 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
224 v0.normal = normals[tris_n[i-2]];
225 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
227 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
228 v1.normal = normals[tris_n[i-1]];
229 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
231 v2.vertex = toVec3f(vertices[tris_v[i]]);
232 v2.normal = normals[tris_n[i]];
233 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
234 triangles.insert(v0, v1, v2);
239 addStripGeometry(SGTexturedTriangleBin& triangles,
240 const std::vector<SGVec3d>& vertices,
241 const std::vector<SGVec3f>& normals,
242 const std::vector<SGVec2f>& texCoords,
243 const int_list& strips_v,
244 const int_list& strips_n,
245 const int_list& strips_tc,
246 const SGVec2f& tcScale)
248 if (strips_v.size() != strips_n.size()) {
249 // If the normal indices do not match, they should be inmplicitly
250 // the same than the vertex indices. So just call ourselves again
251 // with the matching index vector.
252 addStripGeometry(triangles, vertices, normals, texCoords,
253 strips_v, strips_v, strips_tc, tcScale);
257 for (unsigned i = 2; i < strips_v.size(); ++i) {
259 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
260 v0.normal = normals[strips_n[i-2]];
261 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
263 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
264 v1.normal = normals[strips_n[i-1]];
265 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
267 v2.vertex = toVec3f(vertices[strips_v[i]]);
268 v2.normal = normals[strips_n[i]];
269 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
271 triangles.insert(v1, v0, v2);
273 triangles.insert(v0, v1, v2);
278 addFanGeometry(SGTexturedTriangleBin& triangles,
279 const std::vector<SGVec3d>& vertices,
280 const std::vector<SGVec3f>& normals,
281 const std::vector<SGVec2f>& texCoords,
282 const int_list& fans_v,
283 const int_list& fans_n,
284 const int_list& fans_tc,
285 const SGVec2f& tcScale)
287 if (fans_v.size() != fans_n.size()) {
288 // If the normal indices do not match, they should be implicitly
289 // the same than the vertex indices. So just call ourselves again
290 // with the matching index vector.
291 addFanGeometry(triangles, vertices, normals, texCoords,
292 fans_v, fans_v, fans_tc, tcScale);
297 v0.vertex = toVec3f(vertices[fans_v[0]]);
298 v0.normal = normals[fans_n[0]];
299 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
301 v1.vertex = toVec3f(vertices[fans_v[1]]);
302 v1.normal = normals[fans_n[1]];
303 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
304 for (unsigned i = 2; i < fans_v.size(); ++i) {
306 v2.vertex = toVec3f(vertices[fans_v[i]]);
307 v2.normal = normals[fans_n[i]];
308 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
309 triangles.insert(v0, v1, v2);
314 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
317 return SGVec2f(1, 1);
318 SGMaterial* material = matlib->find(name);
320 return SGVec2f(1, 1);
322 return material->get_tex_coord_scale();
326 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
328 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
329 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
330 SG_LOG(SG_TERRAIN, SG_ALERT,
331 "Group list sizes for triangles do not match!");
335 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
336 std::string materialName = obj.get_tri_materials()[grp];
337 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
338 addTriangleGeometry(materialTriangleMap[materialName],
339 obj.get_wgs84_nodes(), obj.get_normals(),
340 obj.get_texcoords(), obj.get_tris_v()[grp],
341 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
345 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
346 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
347 SG_LOG(SG_TERRAIN, SG_ALERT,
348 "Group list sizes for strips do not match!");
351 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
352 std::string materialName = obj.get_strip_materials()[grp];
353 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
354 addStripGeometry(materialTriangleMap[materialName],
355 obj.get_wgs84_nodes(), obj.get_normals(),
356 obj.get_texcoords(), obj.get_strips_v()[grp],
357 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
361 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
362 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
363 SG_LOG(SG_TERRAIN, SG_ALERT,
364 "Group list sizes for fans do not match!");
367 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
368 std::string materialName = obj.get_fan_materials()[grp];
369 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
370 addFanGeometry(materialTriangleMap[materialName],
371 obj.get_wgs84_nodes(), obj.get_normals(),
372 obj.get_texcoords(), obj.get_fans_v()[grp],
373 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
379 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
381 if (materialTriangleMap.empty())
385 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
386 //osg::Geode* geode = new osg::Geode;
387 SGMaterialTriangleMap::const_iterator i;
388 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
389 osg::Geometry* geometry = i->second.buildGeometry();
392 mat = matlib->find(i->first);
393 eg = new EffectGeode;
395 eg->setEffect(mat->get_effect(i->second));
396 eg->addDrawable(geometry);
397 eg->runGenerators(geometry); // Generate extra data needed by effect
407 void computeRandomSurfaceLights(SGMaterialLib* matlib)
409 SGMaterialTriangleMap::iterator i;
411 // generate a repeatable random seed
413 mt_init(&seed, unsigned(123));
415 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
416 SGMaterial *mat = matlib->find(i->first);
420 float coverage = mat->get_light_coverage();
423 if (coverage < 10000.0) {
424 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
425 << coverage << ", pushing up to 10000");
429 std::vector<SGVec3f> randomPoints;
430 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
431 std::vector<SGVec3f>::iterator j;
432 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
433 float zombie = mt_rand(&seed);
434 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
435 float factor = mt_rand(&seed);
440 if ( zombie > 0.5 ) {
441 // 50% chance of yellowish
442 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
443 } else if (zombie > 0.15f) {
444 // 35% chance of whitish
445 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
446 } else if (zombie > 0.05f) {
447 // 10% chance of orangish
448 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
450 // 5% chance of redish
451 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
453 randomTileLights.insert(*j, color);
458 void computeRandomBuildings(SGMaterialLib* matlib, float building_density)
460 SGMaterialTriangleMap::iterator i;
462 // generate a repeatable random seed
464 mt_init(&seed, unsigned(123));
466 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
467 SGMaterial *mat = matlib->find(i->first);
468 SGTexturedTriangleBin triangleBin = i->second;
473 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
475 float coverage = mat->get_building_coverage();
477 // Minimum spacing needs to include the maximum footprint of a building.
478 // As the 0,0,0 point is the center of the front of the building, we need
479 // to consider the full depth, but only half the possible width.
480 float min_spacing = mat->get_building_spacing();
486 SGBuildingBin* bin = NULL;
488 BOOST_FOREACH(bin, randomBuildings)
490 if (bin->texture == mat->get_building_texture()) {
497 bin = new SGBuildingBin();
498 bin->texture = mat->get_building_texture();
499 bin->lightMap = mat->get_building_lightmap();
500 SG_LOG(SG_INPUT, SG_DEBUG, "Building texture " << bin->texture);
501 randomBuildings.push_back(bin);
504 std::vector<std::pair<SGVec3f, float> > randomPoints;
506 unsigned num = i->second.getNumTriangles();
507 int triangle_dropped = 0;
508 int building_dropped = 0;
509 int random_dropped = 0;
510 int mask_dropped = 0;
512 for (unsigned i = 0; i < num; ++i) {
513 SGBuildingBin::BuildingList triangle_buildings;
514 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
516 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
517 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
518 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
519 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
520 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
521 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
522 SGVec3f normal = cross(v0, v1);
525 float area = 0.5f*length(normal);
526 if (area <= SGLimitsf::min())
529 // for partial units of area, use a zombie door method to
530 // create the proper random chance of an object being created
531 // for this triangle.
532 double num = area / coverage + mt_rand(&seed);
537 // Apply density, which is linear, while we're dealing in areas
538 num = num * building_density * building_density;
540 // Cosine of the angle between the two vectors.
541 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
543 // Determine a grid spacing in each vector such that the correct
544 // coverage will result.
545 float stepv0 = (sqrtf(coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
546 float stepv1 = (sqrtf(coverage) / building_density) / length(v1);
548 stepv0 = std::min(stepv0, 1.0f);
549 stepv1 = std::min(stepv1, 1.0f);
551 // Start at a random point. a will be immediately incremented below.
552 float a = -mt_rand(&seed) * stepv0;
553 float b = mt_rand(&seed) * stepv1;
555 // Place an object each unit of area
556 while ( num > 1.0 ) {
558 // Set the next location to place a building
561 if ( a + b > 1.0f ) {
562 // Reached the end of the scan-line on v0. Reset and increment
564 a = mt_rand(&seed) * stepv0;
569 // In a degenerate case of a single point, we might be outside the
571 b = mt_rand(&seed) * stepv1;
574 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
575 float rotation = mt_rand(&seed);
577 if (object_mask != NULL) {
578 SGVec2f texCoord = torigin + a*t0 + b*t1;
579 osg::Image* img = object_mask->getImage();
580 int x = (int) (img->s() * texCoord.x()) % img->s();
581 int y = (int) (img->t() * texCoord.y()) % img->t();
583 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
584 while (x < 0) x += img->s();
585 while (y < 0) y += img->t();
587 if (mt_rand(&seed) < img->getColor(x, y).b()) {
588 // Object passes mask. Rotation is taken from the red channel
589 rotation = img->getColor(x,y).r();
591 // Fails mask test - try again.
598 // Now create the building, so we have an idea of its footprint
599 // and therefore appropriate spacing.
600 SGBuildingBin::BuildingType buildingtype;
607 // Determine the building type, and hence dimensions.
608 float type = mt_rand(&seed);
610 if (type < mat->get_building_small_fraction()) {
612 buildingtype = SGBuildingBin::SMALL;
613 width = mat->get_building_small_min_width() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_small_max_width() - mat->get_building_small_min_width());
614 depth = mat->get_building_small_min_depth() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_small_max_depth() - mat->get_building_small_min_depth());
615 floors = SGMisc<double>::round(mat->get_building_small_min_floors() + mt_rand(&seed) * (mat->get_building_small_max_floors() - mat->get_building_small_min_floors()));
616 height = floors * (2.8 + mt_rand(&seed));
618 // Small buildings are never deeper than they are wide.
619 if (depth > width) { depth = width; }
621 pitched = (mt_rand(&seed) < mat->get_building_small_pitch());
622 } else if (type < (mat->get_building_small_fraction() + mat->get_building_medium_fraction())) {
623 buildingtype = SGBuildingBin::MEDIUM;
624 width = mat->get_building_medium_min_width() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_medium_max_width() - mat->get_building_medium_min_width());
625 depth = mat->get_building_medium_min_depth() + mt_rand(&seed) * mt_rand(&seed) * (mat->get_building_medium_max_depth() - mat->get_building_medium_min_depth());
626 floors = SGMisc<double>::round(mat->get_building_medium_min_floors() + mt_rand(&seed) * (mat->get_building_medium_max_floors() - mat->get_building_medium_min_floors()));
627 height = floors * (2.8 + mt_rand(&seed));
629 while ((height > width) && (floors > mat->get_building_medium_min_floors())) {
630 // Ensure that medium buildings aren't taller than they are wide
632 height = floors * (2.8 + mt_rand(&seed));
635 pitched = (mt_rand(&seed) < mat->get_building_medium_pitch());
637 buildingtype = SGBuildingBin::LARGE;
638 width = mat->get_building_large_min_width() + mt_rand(&seed) * (mat->get_building_large_max_width() - mat->get_building_large_min_width());
639 depth = mat->get_building_large_min_depth() + mt_rand(&seed) * (mat->get_building_large_max_depth() - mat->get_building_large_min_depth());
640 floors = SGMisc<double>::round(mat->get_building_large_min_floors() + mt_rand(&seed) * (mat->get_building_large_max_floors() - mat->get_building_large_min_floors()));
641 height = floors * (2.8 + mt_rand(&seed));
642 pitched = (mt_rand(&seed) < mat->get_building_large_pitch());
645 // Determine an appropriate minimum spacing for the object. Note that the
646 // origin of the building model is the center of the front face, hence we
647 // consider the full depth. We choose _not_ to use the diagonal distance
648 // to one of the rear corners, as we assume that terrain masking will
649 // make the buildings place in some sort of grid.
650 float radius = std::max(depth, 0.5f*width);
652 // Check that the point is sufficiently far from
653 // the edge of the triangle by measuring the distance
654 // from the three lines that make up the triangle.
655 SGVec3f p = randomPoint - vorigin;
657 if (((length(cross(p , p - v0)) / length(v0)) < radius) ||
658 ((length(cross(p - v0, p - v1)) / length(v1 - v0)) < radius) ||
659 ((length(cross(p - v1, p )) / length(v1)) < radius) )
666 // Check against the generic random objects. TODO - make this more efficient by
667 // masking ahead of time objects outside of the triangle.
668 bool too_close = false;
669 for (unsigned int i = 0; i < randomModels.getNumModels(); ++i) {
670 float min_dist = randomModels.getMatModel(i).model->get_spacing_m() + radius + min_spacing;
671 min_dist = min_dist * min_dist;
673 if (distSqr(randomModels.getMatModel(i).position, randomPoint) < min_dist) {
681 // Too close to a random model - drop and try again
686 SGBuildingBin::BuildingList::iterator l;
688 // Check that the building is sufficiently far from any other building within the triangle.
689 for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
691 float min_dist = l->radius + radius + min_spacing;
692 min_dist = min_dist * min_dist;
694 if (distSqr(randomPoint, l->position) < min_dist) {
702 // Too close to another building - drop and try again
707 // If we've passed all of the above tests we have a valid
708 // building, so create it!
709 SGBuildingBin::Building building =
710 SGBuildingBin::Building(buildingtype,
718 triangle_buildings.push_back(building);
723 // Add the buildings from this triangle to the overall list.
724 SGBuildingBin::BuildingList::iterator l;
726 for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
731 SG_LOG(SG_INPUT, SG_DEBUG, "Random Buildings: " << bin->getNumBuildings());
732 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to mask: " << mask_dropped);
733 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to triangle edge: " << triangle_dropped);
734 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to random object: " << random_dropped);
735 SG_LOG(SG_INPUT, SG_DEBUG, " Dropped due to other building: " << building_dropped);
739 void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
741 SGMaterialTriangleMap::iterator i;
743 // generate a repeatable random seed
746 mt_init(&seed, unsigned(586));
748 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
749 SGMaterial *mat = matlib->find(i->first);
753 float wood_coverage = mat->get_wood_coverage();
754 if (wood_coverage <= 0)
757 // Attributes that don't vary by tree but do vary by material
761 BOOST_FOREACH(bin, randomForest)
763 if ((bin->texture == mat->get_tree_texture() ) &&
764 (bin->texture_varieties == mat->get_tree_varieties()) &&
765 (bin->range == mat->get_tree_range() ) &&
766 (bin->width == mat->get_tree_width() ) &&
767 (bin->height == mat->get_tree_height() ) ) {
775 bin->texture = mat->get_tree_texture();
776 SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
777 bin->range = mat->get_tree_range();
778 bin->width = mat->get_tree_width();
779 bin->height = mat->get_tree_height();
780 bin->texture_varieties = mat->get_tree_varieties();
781 randomForest.push_back(bin);
784 std::vector<SGVec3f> randomPoints;
785 i->second.addRandomTreePoints(wood_coverage,
786 mat->get_object_mask(i->second),
790 std::vector<SGVec3f>::iterator k;
791 for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
797 void computeRandomObjects(SGMaterialLib* matlib)
799 SGMaterialTriangleMap::iterator i;
801 // generate a repeatable random seed
803 mt_init(&seed, unsigned(123));
805 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
806 SGMaterial *mat = matlib->find(i->first);
810 int group_count = mat->get_object_group_count();
814 for (int j = 0; j < group_count; j++)
816 SGMatModelGroup *object_group = mat->get_object_group(j);
817 int nObjects = object_group->get_object_count();
821 // For each of the random models in the group, determine an appropriate
822 // number of random placements and insert them.
823 for (int k = 0; k < nObjects; k++) {
824 SGMatModel * object = object_group->get_object(k);
826 std::vector<std::pair<SGVec3f, float> > randomPoints;
828 i->second.addRandomPoints(object->get_coverage_m2(),
829 object->get_spacing_m(),
830 mat->get_object_mask(i->second),
833 std::vector<std::pair<SGVec3f, float> >::iterator l;
834 for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
835 // Only add the model if it is sufficiently far from the
839 for (unsigned i = 0; i < randomModels.getNumModels(); i++) {
840 float spacing = randomModels.getMatModel(i).model->get_spacing_m() + object->get_spacing_m();
841 spacing = spacing * spacing;
843 if (distSqr(randomModels.getMatModel(i).position, l->first) < spacing) {
850 randomModels.insert(l->first, object, (int)object->get_randomized_range_m(&seed), l->second);
860 bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
862 if (!insertPtGeometry(obj, matlib))
864 if (!insertSurfaceGeometry(obj, matlib))
870 typedef std::pair<osg::Node*, int> ModelLOD;
871 struct MakeQuadLeaf {
872 osg::LOD* operator() () const { return new osg::LOD; }
875 void operator() (osg::LOD* leaf, ModelLOD& mlod) const
877 leaf->addChild(mlod.first, 0, mlod.second);
880 struct GetModelLODCoord {
881 GetModelLODCoord() {}
882 GetModelLODCoord(const GetModelLODCoord& rhs)
884 osg::Vec3 operator() (const ModelLOD& mlod) const
886 return mlod.first->getBound().center();
890 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
891 GetModelLODCoord> RandomObjectsQuadtree;
894 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
897 if (!tile.read_bin(path))
900 SGMaterialLib* matlib = 0;
901 bool use_random_objects = false;
902 bool use_random_vegetation = false;
903 bool use_random_buildings = false;
904 float vegetation_density = 1.0f;
905 float building_density = 1.0f;
907 matlib = options->getMaterialLib();
908 SGPropertyNode* propertyNode = options->getPropertyNode().get();
911 = propertyNode->getBoolValue("/sim/rendering/random-objects",
913 use_random_vegetation
914 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
915 use_random_vegetation);
917 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
920 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
921 use_random_buildings);
923 = propertyNode->getFloatValue("/sim/rendering/building-density",
928 SGVec3d center = tile.get_gbs_center();
929 SGGeod geodPos = SGGeod::fromCart(center);
930 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
932 // rotate the tiles so that the bounding boxes get nearly axis aligned.
933 // this will help the collision tree's bounding boxes a bit ...
934 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
935 for (unsigned i = 0; i < nodes.size(); ++i)
936 nodes[i] = hlOr.transform(nodes[i]);
937 tile.set_wgs84_nodes(nodes);
939 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
940 std::vector<SGVec3f> normals = tile.get_normals();
941 for (unsigned i = 0; i < normals.size(); ++i)
942 normals[i] = hlOrf.transform(normals[i]);
943 tile.set_normals(normals);
945 SGTileGeometryBin tileGeometryBin;
946 if (!tileGeometryBin.insertBinObj(tile, matlib))
950 GroundLightManager* lightManager = GroundLightManager::instance();
952 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
953 osg::ref_ptr<osg::Group> randomObjects;
954 osg::ref_ptr<osg::Group> forestNode;
955 osg::ref_ptr<osg::Group> buildingNode;
956 osg::Group* terrainGroup = new osg::Group;
958 osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
960 terrainGroup->addChild(node);
962 if (use_random_objects && matlib) {
963 tileGeometryBin.computeRandomObjects(matlib);
965 if (tileGeometryBin.randomModels.getNumModels() > 0) {
966 // Generate a repeatable random seed
968 mt_init(&seed, unsigned(123));
970 std::vector<ModelLOD> models;
971 for (unsigned int i = 0;
972 i < tileGeometryBin.randomModels.getNumModels(); i++) {
973 SGMatModelBin::MatModel obj
974 = tileGeometryBin.randomModels.getMatModel(i);
976 SGPropertyNode* root = options->getPropertyNode()->getRootNode();
977 osg::Node* node = obj.model->get_random_model(root, &seed);
979 // Create a matrix to place the object in the correct
980 // location, and then apply the rotation matrix created
981 // above, with an additional random (or taken from
982 // the object mask) heading rotation if appropriate.
983 osg::Matrix transformMat;
984 transformMat = osg::Matrix::translate(toOsg(obj.position));
985 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
986 // Rotate the object around the z axis.
987 double hdg = mt_rand(&seed) * M_PI * 2;
988 transformMat.preMult(osg::Matrix::rotate(hdg,
989 osg::Vec3d(0.0, 0.0, 1.0)));
992 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
993 // Rotate the object around the z axis.
994 double hdg = - obj.rotation * M_PI * 2;
995 transformMat.preMult(osg::Matrix::rotate(hdg,
996 osg::Vec3d(0.0, 0.0, 1.0)));
999 osg::MatrixTransform* position =
1000 new osg::MatrixTransform(transformMat);
1001 position->addChild(node);
1002 models.push_back(ModelLOD(position, obj.lod));
1004 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1005 quadtree.buildQuadTree(models.begin(), models.end());
1006 randomObjects = quadtree.getRoot();
1007 randomObjects->setName("random objects");
1011 if (use_random_vegetation && matlib) {
1012 // Now add some random forest.
1013 tileGeometryBin.computeRandomForest(matlib, vegetation_density);
1015 if (tileGeometryBin.randomForest.size() > 0) {
1016 forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
1018 forestNode->setName("Random trees");
1022 if (use_random_buildings && matlib) {
1023 tileGeometryBin.computeRandomBuildings(matlib, building_density);
1024 if (tileGeometryBin.randomBuildings.size() > 0) {
1025 buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
1027 buildingNode->setName("Random buildings");
1031 // FIXME: ugly, has a side effect
1033 tileGeometryBin.computeRandomSurfaceLights(matlib);
1035 if (tileGeometryBin.tileLights.getNumLights() > 0
1036 || tileGeometryBin.randomTileLights.getNumLights() > 0) {
1037 osg::Group* groundLights0 = new osg::Group;
1038 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
1039 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
1040 osg::Geode* geode = new osg::Geode;
1041 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
1042 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
1043 groundLights0->addChild(geode);
1044 lightGroup->addChild(groundLights0);
1047 if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
1048 osg::Group* groundLights1 = new osg::Group;
1049 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1050 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1051 osg::Group* groundLights2 = new osg::Group;
1052 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1053 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1054 osg::Geode* geode = new osg::Geode;
1055 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1056 groundLights1->addChild(geode);
1057 lightGroup->addChild(groundLights1);
1058 geode = new osg::Geode;
1059 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1060 groundLights2->addChild(geode);
1061 lightGroup->addChild(groundLights2);
1064 if (!tileGeometryBin.vasiLights.empty()) {
1065 EffectGeode* vasiGeode = new EffectGeode;
1067 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1068 vasiGeode->setEffect(vasiEffect);
1069 SGVec4f red(1, 0, 0, 1);
1070 SGMaterial* mat = 0;
1072 mat = matlib->find("RWY_RED_LIGHTS");
1074 red = mat->get_light_color();
1075 SGVec4f white(1, 1, 1, 1);
1078 mat = matlib->find("RWY_WHITE_LIGHTS");
1080 white = mat->get_light_color();
1081 SGDirectionalLightListBin::const_iterator i;
1082 for (i = tileGeometryBin.vasiLights.begin();
1083 i != tileGeometryBin.vasiLights.end(); ++i) {
1084 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1086 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1087 lightGroup->addChild(vasiGeode);
1090 Effect* runwayEffect = 0;
1091 if (tileGeometryBin.runwayLights.getNumLights() > 0
1092 || !tileGeometryBin.rabitLights.empty()
1093 || !tileGeometryBin.reilLights.empty()
1094 || !tileGeometryBin.odalLights.empty()
1095 || tileGeometryBin.taxiLights.getNumLights() > 0)
1096 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1097 if (tileGeometryBin.runwayLights.getNumLights() > 0
1098 || !tileGeometryBin.rabitLights.empty()
1099 || !tileGeometryBin.reilLights.empty()
1100 || !tileGeometryBin.odalLights.empty()
1101 || !tileGeometryBin.holdshortLights.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 SGLightListBin::const_iterator j;
1126 for (j = tileGeometryBin.odalLights.begin();
1127 j != tileGeometryBin.odalLights.end(); ++j) {
1128 rwyLights->addChild(SGLightFactory::getOdal(*j));
1130 lightGroup->addChild(rwyLights);
1133 if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1134 osg::Group* taxiLights = new osg::Group;
1135 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1136 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1137 EffectGeode* geode = new EffectGeode;
1138 geode->setEffect(runwayEffect);
1139 geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1140 taxiLights->addChild(geode);
1141 lightGroup->addChild(taxiLights);
1144 // The toplevel transform for that tile.
1145 osg::MatrixTransform* transform = new osg::MatrixTransform;
1146 transform->setName(path);
1147 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1148 osg::Matrix::translate(toOsg(center)));
1149 transform->addChild(terrainGroup);
1150 if (lightGroup->getNumChildren() > 0) {
1151 osg::LOD* lightLOD = new osg::LOD;
1152 lightLOD->addChild(lightGroup.get(), 0, 30000);
1153 // VASI is always on, so doesn't use light bits.
1154 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT);
1155 transform->addChild(lightLOD);
1158 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1160 // Add a LoD node, so we don't try to display anything when the tile center
1161 // is more than 20km away.
1162 osg::LOD* objectLOD = new osg::LOD;
1164 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1165 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1166 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1168 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1169 objectLOD->setNodeMask(nodeMask);
1170 transform->addChild(objectLOD);