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/Referenced>
41 #include <osg/StateSet>
44 #include <osgUtil/Simplifier>
46 #include <boost/foreach.hpp>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/io/sg_binobj.hxx>
52 #include <simgear/math/sg_geodesy.hxx>
53 #include <simgear/math/sg_random.h>
54 #include <simgear/math/SGMisc.hxx>
55 #include <simgear/scene/material/Effect.hxx>
56 #include <simgear/scene/material/EffectGeode.hxx>
57 #include <simgear/scene/material/mat.hxx>
58 #include <simgear/scene/material/matmodel.hxx>
59 #include <simgear/scene/material/matlib.hxx>
60 #include <simgear/scene/model/SGOffsetTransform.hxx>
61 #include <simgear/scene/util/SGUpdateVisitor.hxx>
62 #include <simgear/scene/util/SGNodeMasks.hxx>
63 #include <simgear/scene/util/QuadTreeBuilder.hxx>
64 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
65 #include <simgear/scene/util/OptionsReadFileCallback.hxx>
67 #include "SGTexturedTriangleBin.hxx"
68 #include "SGLightBin.hxx"
69 #include "SGModelBin.hxx"
70 #include "SGBuildingBin.hxx"
71 #include "TreeBin.hxx"
72 #include "SGDirectionalLightBin.hxx"
73 #include "GroundLightManager.hxx"
75 #include "pt_lights.hxx"
77 #define SG_SIMPLIFIER_RATIO 0.001
78 #define SG_SIMPLIFIER_MAX_LENGTH 1000.0
79 #define SG_SIMPLIFIER_MAX_ERROR 2000.0
80 #define SG_OBJECT_RANGE 9000.0
81 #define SG_TILE_RADIUS 14000.0
83 using namespace simgear;
85 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
86 typedef std::list<SGLightBin> SGLightListBin;
87 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
89 class SGTileGeometryBin : public osg::Referenced {
91 SGMaterialTriangleMap materialTriangleMap;
92 SGLightBin tileLights;
93 SGLightBin randomTileLights;
94 SGTreeBinList randomForest;
95 SGDirectionalLightBin runwayLights;
96 SGDirectionalLightBin taxiLights;
97 SGDirectionalLightListBin vasiLights;
98 SGDirectionalLightListBin rabitLights;
99 SGLightListBin odalLights;
100 SGDirectionalLightListBin holdshortLights;
101 SGDirectionalLightListBin guardLights;
102 SGDirectionalLightListBin reilLights;
103 SGMatModelBin randomModels;
104 SGBuildingBinList randomBuildings;
107 getMaterialLightColor(const SGMaterial* material)
110 return SGVec4f(1, 1, 1, 0.8);
111 return material->get_light_color();
115 addPointGeometry(SGLightBin& lights,
116 const std::vector<SGVec3d>& vertices,
117 const SGVec4f& color,
118 const int_list& pts_v)
120 for (unsigned i = 0; i < pts_v.size(); ++i)
121 lights.insert(toVec3f(vertices[pts_v[i]]), color);
125 addPointGeometry(SGDirectionalLightBin& lights,
126 const std::vector<SGVec3d>& vertices,
127 const std::vector<SGVec3f>& normals,
128 const SGVec4f& color,
129 const int_list& pts_v,
130 const int_list& pts_n)
132 // If the normal indices match the vertex indices, use seperate
133 // normal indices. Else reuse the vertex indices for the normals.
134 if (pts_v.size() == pts_n.size()) {
135 for (unsigned i = 0; i < pts_v.size(); ++i)
136 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
138 for (unsigned i = 0; i < pts_v.size(); ++i)
139 lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
144 insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
146 if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
147 SG_LOG(SG_TERRAIN, SG_ALERT,
148 "Group list sizes for points do not match!");
152 for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
153 std::string materialName = obj.get_pt_materials()[grp];
154 SGMaterial* material = 0;
156 material = matlib->findCached(materialName);
157 SGVec4f color = getMaterialLightColor(material);
159 if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
160 // Just plain lights. Not something for the runway.
161 addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
162 obj.get_pts_v()[grp]);
163 } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
164 || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
165 addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
166 color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
167 } else if (materialName == "RWY_VASI_LIGHTS") {
168 vasiLights.push_back(SGDirectionalLightBin());
169 addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
170 obj.get_normals(), color, obj.get_pts_v()[grp],
171 obj.get_pts_n()[grp]);
172 } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
173 rabitLights.push_back(SGDirectionalLightBin());
174 addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
175 obj.get_normals(), color, obj.get_pts_v()[grp],
176 obj.get_pts_n()[grp]);
177 } else if (materialName == "RWY_ODALS_LIGHTS") {
178 odalLights.push_back(SGLightBin());
179 addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
180 color, obj.get_pts_v()[grp]);
181 } else if (materialName == "RWY_YELLOW_PULSE_LIGHTS") {
182 holdshortLights.push_back(SGDirectionalLightBin());
183 addPointGeometry(holdshortLights.back(), obj.get_wgs84_nodes(),
184 obj.get_normals(), color, obj.get_pts_v()[grp],
185 obj.get_pts_n()[grp]);
186 } else if (materialName == "RWY_GUARD_LIGHTS") {
187 guardLights.push_back(SGDirectionalLightBin());
188 addPointGeometry(guardLights.back(), obj.get_wgs84_nodes(),
189 obj.get_normals(), color, obj.get_pts_v()[grp],
190 obj.get_pts_n()[grp]);
191 } else if (materialName == "RWY_REIL_LIGHTS") {
192 reilLights.push_back(SGDirectionalLightBin());
193 addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
194 obj.get_normals(), color, obj.get_pts_v()[grp],
195 obj.get_pts_n()[grp]);
197 // what is left must be runway lights
198 addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
199 obj.get_normals(), color, obj.get_pts_v()[grp],
200 obj.get_pts_n()[grp]);
209 getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
210 const SGVec2f& tcScale, unsigned i)
214 else if (tc.size() == 1)
215 return mult(texCoords[tc[0]], tcScale);
217 return mult(texCoords[tc[i]], tcScale);
221 addTriangleGeometry(SGTexturedTriangleBin& triangles,
222 const std::vector<SGVec3d>& vertices,
223 const std::vector<SGVec3f>& normals,
224 const std::vector<SGVec2f>& texCoords,
225 const int_list& tris_v,
226 const int_list& tris_n,
227 const int_list& tris_tc,
228 const SGVec2f& tcScale)
230 if (tris_v.size() != tris_n.size()) {
231 // If the normal indices do not match, they should be inmplicitly
232 // the same than the vertex indices. So just call ourselves again
233 // with the matching index vector.
234 addTriangleGeometry(triangles, vertices, normals, texCoords,
235 tris_v, tris_v, tris_tc, tcScale);
239 for (unsigned i = 2; i < tris_v.size(); i += 3) {
241 v0.vertex = toVec3f(vertices[tris_v[i-2]]);
242 v0.normal = normals[tris_n[i-2]];
243 v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
245 v1.vertex = toVec3f(vertices[tris_v[i-1]]);
246 v1.normal = normals[tris_n[i-1]];
247 v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
249 v2.vertex = toVec3f(vertices[tris_v[i]]);
250 v2.normal = normals[tris_n[i]];
251 v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
252 triangles.insert(v0, v1, v2);
257 addStripGeometry(SGTexturedTriangleBin& triangles,
258 const std::vector<SGVec3d>& vertices,
259 const std::vector<SGVec3f>& normals,
260 const std::vector<SGVec2f>& texCoords,
261 const int_list& strips_v,
262 const int_list& strips_n,
263 const int_list& strips_tc,
264 const SGVec2f& tcScale)
266 if (strips_v.size() != strips_n.size()) {
267 // If the normal indices do not match, they should be inmplicitly
268 // the same than the vertex indices. So just call ourselves again
269 // with the matching index vector.
270 addStripGeometry(triangles, vertices, normals, texCoords,
271 strips_v, strips_v, strips_tc, tcScale);
275 for (unsigned i = 2; i < strips_v.size(); ++i) {
277 v0.vertex = toVec3f(vertices[strips_v[i-2]]);
278 v0.normal = normals[strips_n[i-2]];
279 v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
281 v1.vertex = toVec3f(vertices[strips_v[i-1]]);
282 v1.normal = normals[strips_n[i-1]];
283 v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
285 v2.vertex = toVec3f(vertices[strips_v[i]]);
286 v2.normal = normals[strips_n[i]];
287 v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
289 triangles.insert(v1, v0, v2);
291 triangles.insert(v0, v1, v2);
296 addFanGeometry(SGTexturedTriangleBin& triangles,
297 const std::vector<SGVec3d>& vertices,
298 const std::vector<SGVec3f>& normals,
299 const std::vector<SGVec2f>& texCoords,
300 const int_list& fans_v,
301 const int_list& fans_n,
302 const int_list& fans_tc,
303 const SGVec2f& tcScale)
305 if (fans_v.size() != fans_n.size()) {
306 // If the normal indices do not match, they should be implicitly
307 // the same than the vertex indices. So just call ourselves again
308 // with the matching index vector.
309 addFanGeometry(triangles, vertices, normals, texCoords,
310 fans_v, fans_v, fans_tc, tcScale);
315 v0.vertex = toVec3f(vertices[fans_v[0]]);
316 v0.normal = normals[fans_n[0]];
317 v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
319 v1.vertex = toVec3f(vertices[fans_v[1]]);
320 v1.normal = normals[fans_n[1]];
321 v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
322 for (unsigned i = 2; i < fans_v.size(); ++i) {
324 v2.vertex = toVec3f(vertices[fans_v[i]]);
325 v2.normal = normals[fans_n[i]];
326 v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
327 triangles.insert(v0, v1, v2);
332 SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
335 return SGVec2f(1, 1);
336 SGMaterial* material = matlib->findCached(name);
338 return SGVec2f(1, 1);
340 return material->get_tex_coord_scale();
344 insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
346 if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
347 obj.get_tris_tc().size() < obj.get_tris_v().size()) {
348 SG_LOG(SG_TERRAIN, SG_ALERT,
349 "Group list sizes for triangles do not match!");
353 for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
354 std::string materialName = obj.get_tri_materials()[grp];
355 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
356 addTriangleGeometry(materialTriangleMap[materialName],
357 obj.get_wgs84_nodes(), obj.get_normals(),
358 obj.get_texcoords(), obj.get_tris_v()[grp],
359 obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
363 if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
364 obj.get_strips_tc().size() < obj.get_strips_v().size()) {
365 SG_LOG(SG_TERRAIN, SG_ALERT,
366 "Group list sizes for strips do not match!");
369 for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
370 std::string materialName = obj.get_strip_materials()[grp];
371 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
372 addStripGeometry(materialTriangleMap[materialName],
373 obj.get_wgs84_nodes(), obj.get_normals(),
374 obj.get_texcoords(), obj.get_strips_v()[grp],
375 obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
379 if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
380 obj.get_fans_tc().size() < obj.get_fans_v().size()) {
381 SG_LOG(SG_TERRAIN, SG_ALERT,
382 "Group list sizes for fans do not match!");
385 for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
386 std::string materialName = obj.get_fan_materials()[grp];
387 SGVec2f tcScale = getTexCoordScale(materialName, matlib);
388 addFanGeometry(materialTriangleMap[materialName],
389 obj.get_wgs84_nodes(), obj.get_normals(),
390 obj.get_texcoords(), obj.get_fans_v()[grp],
391 obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
397 osg::Node* getSurfaceGeometry(SGMaterialLib* matlib, bool useVBOs) const
399 if (materialTriangleMap.empty())
403 osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
404 //osg::Geode* geode = new osg::Geode;
405 SGMaterialTriangleMap::const_iterator i;
406 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
407 osg::Geometry* geometry = i->second.buildGeometry(useVBOs);
410 mat = matlib->findCached(i->first);
411 eg = new EffectGeode;
412 eg->setName("EffectGeode");
414 eg->setEffect(mat->get_effect(i->second));
415 eg->addDrawable(geometry);
416 eg->runGenerators(geometry); // Generate extra data needed by effect
418 group->setName("surfaceGeometryGroup");
428 void computeRandomSurfaceLights(SGMaterialLib* matlib)
430 SGMaterialTriangleMap::iterator i;
432 // generate a repeatable random seed
434 mt_init(&seed, unsigned(123));
436 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
437 SGMaterial *mat = matlib->findCached(i->first);
441 float coverage = mat->get_light_coverage();
444 if (coverage < 10000.0) {
445 SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
446 << coverage << ", pushing up to 10000");
450 std::vector<SGVec3f> randomPoints;
451 i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
452 std::vector<SGVec3f>::iterator j;
453 for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
454 float zombie = mt_rand(&seed);
455 // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
456 float factor = mt_rand(&seed);
461 if ( zombie > 0.5 ) {
462 // 50% chance of yellowish
463 color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
464 } else if (zombie > 0.15f) {
465 // 35% chance of whitish
466 color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
467 } else if (zombie > 0.05f) {
468 // 10% chance of orangish
469 color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
471 // 5% chance of redish
472 color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
474 randomTileLights.insert(*j, color);
479 void computeRandomObjectsAndBuildings(
480 SGMaterialLib* matlib,
481 float building_density,
482 bool use_random_objects,
483 bool use_random_buildings)
485 SGMaterialTriangleMap::iterator i;
487 // generate a repeatable random seed
489 mt_init(&seed, unsigned(123));
491 for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
492 SGMaterial *mat = matlib->findCached(i->first);
493 SGTexturedTriangleBin triangleBin = i->second;
498 osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
500 int group_count = mat->get_object_group_count();
501 float building_coverage = mat->get_building_coverage();
502 float cos_zero_density_angle = mat->get_cos_object_zero_density_slope_angle();
503 float cos_max_density_angle = mat->get_cos_object_max_density_slope_angle();
505 if (building_coverage == 0)
508 SGBuildingBin* bin = NULL;
510 if (building_coverage > 0) {
511 bin = new SGBuildingBin(mat);
512 randomBuildings.push_back(bin);
515 unsigned num = i->second.getNumTriangles();
516 int random_dropped = 0;
517 int mask_dropped = 0;
518 int building_dropped = 0;
519 int triangle_dropped = 0;
521 for (unsigned i = 0; i < num; ++i) {
522 SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
524 SGVec3f vorigin = triangleBin.getVertex(triangleRef[0]).vertex;
525 SGVec3f v0 = triangleBin.getVertex(triangleRef[1]).vertex - vorigin;
526 SGVec3f v1 = triangleBin.getVertex(triangleRef[2]).vertex - vorigin;
527 SGVec2f torigin = triangleBin.getVertex(triangleRef[0]).texCoord;
528 SGVec2f t0 = triangleBin.getVertex(triangleRef[1]).texCoord - torigin;
529 SGVec2f t1 = triangleBin.getVertex(triangleRef[2]).texCoord - torigin;
530 SGVec3f normal = cross(v0, v1);
532 // Ensure the slope isn't too steep by checking the
533 // cos of the angle between the slope normal and the
534 // vertical (conveniently the z-component of the normalized
535 // normal) and values passed in.
536 float cos = normalize(normal).z();
537 float slope_density = 1.0;
538 if (cos < cos_zero_density_angle) continue; // Too steep for any objects
539 if (cos < cos_max_density_angle) {
541 (cos - cos_zero_density_angle) /
542 (cos_max_density_angle - cos_zero_density_angle);
545 // Containers to hold the random buildings and objects generated
546 // for this triangle for collision detection purposes.
547 std::vector< std::pair< SGVec3f, float> > triangleObjectsList;
548 std::vector< std::pair< SGVec3f, float> > triangleBuildingList;
551 float area = 0.5f*length(normal);
552 if (area <= SGLimitsf::min())
555 // Generate any random objects
556 if (use_random_objects && (group_count > 0))
558 for (int j = 0; j < group_count; j++)
560 SGMatModelGroup *object_group = mat->get_object_group(j);
561 int nObjects = object_group->get_object_count();
563 if (nObjects == 0) continue;
565 // For each of the random models in the group, determine an appropriate
566 // number of random placements and insert them.
567 for (int k = 0; k < nObjects; k++) {
568 SGMatModel * object = object_group->get_object(k);
570 // Determine the number of objecst to place, taking into account
571 // the slope density factor.
572 double n = slope_density * area / object->get_coverage_m2();
574 // Use the zombie door method to determine fractional object placement.
575 n = n + mt_rand(&seed);
577 // place an object each unit of area
579 float a = mt_rand(&seed);
580 float b = mt_rand(&seed);
586 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
587 float rotation = static_cast<float>(mt_rand(&seed));
589 // Check that the point is sufficiently far from
590 // the edge of the triangle by measuring the distance
591 // from the three lines that make up the triangle.
592 float spacing = object->get_spacing_m();
594 SGVec3f p = randomPoint - vorigin;
595 float edges[] = { length(cross(p , p - v0)) / length(v0),
596 length(cross(p - v0, p - v1)) / length(v1 - v0),
597 length(cross(p - v1, p )) / length(v1) };
598 float edge_dist = *std::min_element(edges, edges + 3);
600 if (edge_dist < spacing) {
605 if (object_mask != NULL) {
606 SGVec2f texCoord = torigin + a*t0 + b*t1;
608 // Check this random point against the object mask
609 // blue (for buildings) channel.
610 osg::Image* img = object_mask->getImage();
611 unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
612 unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
614 if (mt_rand(&seed) > img->getColor(x, y).b()) {
615 // Failed object mask check
620 rotation = img->getColor(x,y).r();
625 // Check it isn't too close to any other random objects in the triangle
626 std::vector<std::pair<SGVec3f, float> >::iterator l;
627 for (l = triangleObjectsList.begin(); l != triangleObjectsList.end(); ++l) {
628 float min_dist2 = (l->second + object->get_spacing_m()) *
629 (l->second + object->get_spacing_m());
631 if (distSqr(l->first, randomPoint) > min_dist2) {
638 triangleObjectsList.push_back(std::make_pair(randomPoint, object->get_spacing_m()));
639 randomModels.insert(randomPoint,
641 (int)object->get_randomized_range_m(&seed),
649 // Random objects now generated. Now generate the random buildings (if any);
650 if (use_random_buildings && (building_coverage > 0) && (building_density > 0)) {
652 // Calculate the number of buildings, taking into account building density (which is linear)
653 // and the slope density factor.
654 double num = building_density * building_density * slope_density * area / building_coverage;
656 // For partial units of area, use a zombie door method to
657 // create the proper random chance of an object being created
658 // for this triangle.
659 num = num + mt_rand(&seed);
665 // Cosine of the angle between the two vectors.
666 float cosine = (dot(v0, v1) / (length(v0) * length(v1)));
668 // Determine a grid spacing in each vector such that the correct
669 // coverage will result.
670 float stepv0 = (sqrtf(building_coverage) / building_density) / length(v0) / sqrtf(1 - cosine * cosine);
671 float stepv1 = (sqrtf(building_coverage) / building_density) / length(v1);
673 stepv0 = std::min(stepv0, 1.0f);
674 stepv1 = std::min(stepv1, 1.0f);
676 // Start at a random point. a will be immediately incremented below.
677 float a = -mt_rand(&seed) * stepv0;
678 float b = mt_rand(&seed) * stepv1;
680 // Place an object each unit of area
684 // Set the next location to place a building
687 if ((a + b) > 1.0f) {
688 // Reached the end of the scan-line on v0. Reset and increment
690 a = mt_rand(&seed) * stepv0;
695 // In a degenerate case of a single point, we might be outside the
696 // scanline. Note that we need to still ensure that a+b < 1.
697 b = mt_rand(&seed) * stepv1 * (1.0f - a);
700 if ((a + b) > 1.0f ) {
701 // Truly degenerate case - simply choose a random point guaranteed
702 // to fulfil the constraing of a+b < 1.
704 b = mt_rand(&seed) * (1.0f - a);
707 SGVec3f randomPoint = vorigin + a*v0 + b*v1;
708 float rotation = mt_rand(&seed);
710 if (object_mask != NULL) {
711 SGVec2f texCoord = torigin + a*t0 + b*t1;
712 osg::Image* img = object_mask->getImage();
713 int x = (int) (img->s() * texCoord.x()) % img->s();
714 int y = (int) (img->t() * texCoord.y()) % img->t();
716 // In some degenerate cases x or y can be < 1, in which case the mod operand fails
717 while (x < 0) x += img->s();
718 while (y < 0) y += img->t();
720 if (mt_rand(&seed) < img->getColor(x, y).b()) {
721 // Object passes mask. Rotation is taken from the red channel
722 rotation = img->getColor(x,y).r();
724 // Fails mask test - try again.
730 // Check building isn't too close to the triangle edge.
731 float type_roll = mt_rand(&seed);
732 SGBuildingBin::BuildingType buildingtype = bin->getBuildingType(type_roll);
733 float radius = bin->getBuildingMaxRadius(buildingtype);
735 // Determine the actual center of the building, by shifting from the
736 // center of the front face to the true center.
737 osg::Matrix rotationMat = osg::Matrix::rotate(- rotation * M_PI * 2,
738 osg::Vec3f(0.0, 0.0, 1.0));
739 SGVec3f buildingCenter = randomPoint + toSG(osg::Vec3f(-0.5 * bin->getBuildingMaxDepth(buildingtype), 0.0, 0.0) * rotationMat);
741 SGVec3f p = buildingCenter - vorigin;
742 float edges[] = { length(cross(p , p - v0)) / length(v0),
743 length(cross(p - v0, p - v1)) / length(v1 - v0),
744 length(cross(p - v1, p )) / length(v1) };
745 float edge_dist = *std::min_element(edges, edges + 3);
747 if (edge_dist < radius) {
752 // Check building isn't too close to random objects and other buildings.
754 std::vector<std::pair<SGVec3f, float> >::iterator iter;
756 for (iter = triangleBuildingList.begin(); iter != triangleBuildingList.end(); ++iter) {
757 float min_dist = iter->second + radius;
758 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
769 for (iter = triangleObjectsList.begin(); iter != triangleObjectsList.end(); ++iter) {
770 float min_dist = iter->second + radius;
771 if (distSqr(iter->first, buildingCenter) < min_dist * min_dist) {
782 std::pair<SGVec3f, float> pt = std::make_pair(buildingCenter, radius);
783 triangleBuildingList.push_back(pt);
784 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->findCached(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;
892 class RandomObjectCallback : public OptionsReadFileCallback {
894 virtual osgDB::ReaderWriter::ReadResult
895 readNode(const std::string&, const osgDB::Options*)
897 osg::ref_ptr<osg::Group> group = new osg::Group;
898 group->setName("Random Object and Lighting Group");
899 group->setDataVariance(osg::Object::STATIC);
901 osg::Node* node = loadTerrain();
903 group->addChild(node);
905 osg::LOD* lightLOD = generateLightingTileObjects();
907 group->addChild(lightLOD);
909 osg::LOD* objectLOD = generateRandomTileObjects();
911 group->addChild(objectLOD);
913 return group.release();
916 // Load terrain if required
917 osg::Node* loadTerrain()
923 if (!tile.read_bin(_path))
926 SGMaterialLibPtr matlib;
927 bool useVBOs = false;
928 bool simplifyNear = false;
929 double ratio = SG_SIMPLIFIER_RATIO;
930 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
931 double maxError = SG_SIMPLIFIER_MAX_ERROR;
934 matlib = _options->getMaterialLib();
935 useVBOs = (_options->getPluginStringData("SimGear::USE_VBOS") == "ON");
936 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
937 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
938 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
939 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
940 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
943 SGVec3d center = tile.get_gbs_center();
944 SGGeod geodPos = SGGeod::fromCart(center);
945 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
947 // rotate the tiles so that the bounding boxes get nearly axis aligned.
948 // this will help the collision tree's bounding boxes a bit ...
949 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
950 for (unsigned i = 0; i < nodes.size(); ++i)
951 nodes[i] = hlOr.transform(nodes[i]);
952 tile.set_wgs84_nodes(nodes);
954 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
955 std::vector<SGVec3f> normals = tile.get_normals();
956 for (unsigned i = 0; i < normals.size(); ++i)
957 normals[i] = hlOrf.transform(normals[i]);
958 tile.set_normals(normals);
960 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
962 if (!tileGeometryBin->insertBinObj(tile, matlib))
965 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
966 if (node && simplifyNear) {
967 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
968 node->accept(simplifier);
974 // Generate all the lighting objects for the tile.
975 osg::LOD* generateLightingTileObjects()
977 SGMaterialLibPtr matlib;
980 matlib = _options->getMaterialLib();
982 // FIXME: ugly, has a side effect
984 _tileGeometryBin->computeRandomSurfaceLights(matlib);
986 GroundLightManager* lightManager = GroundLightManager::instance();
987 osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
990 if (_tileGeometryBin->tileLights.getNumLights() > 0
991 || _tileGeometryBin->randomTileLights.getNumLights() > 0) {
992 osg::Group* groundLights0 = new osg::Group;
993 groundLights0->setStateSet(lightManager->getGroundLightStateSet());
994 groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
995 osg::Geode* geode = new osg::Geode;
996 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->tileLights));
997 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 4, -0.3f));
998 groundLights0->addChild(geode);
999 lightGroup->addChild(groundLights0);
1002 if (_tileGeometryBin->randomTileLights.getNumLights() > 0) {
1003 osg::Group* groundLights1 = new osg::Group;
1004 groundLights1->setStateSet(lightManager->getGroundLightStateSet());
1005 groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
1006 osg::Group* groundLights2 = new osg::Group;
1007 groundLights2->setStateSet(lightManager->getGroundLightStateSet());
1008 groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1009 osg::Geode* geode = new osg::Geode;
1010 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights, 2, -0.15f));
1011 groundLights1->addChild(geode);
1012 lightGroup->addChild(groundLights1);
1013 geode = new osg::Geode;
1014 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->randomTileLights));
1015 groundLights2->addChild(geode);
1016 lightGroup->addChild(groundLights2);
1019 if (!_tileGeometryBin->vasiLights.empty()) {
1020 EffectGeode* vasiGeode = new EffectGeode;
1022 = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true, _options);
1023 vasiGeode->setEffect(vasiEffect);
1024 SGVec4f red(1, 0, 0, 1);
1025 SGMaterial* mat = 0;
1027 mat = matlib->findCached("RWY_RED_LIGHTS");
1029 red = mat->get_light_color();
1030 SGVec4f white(1, 1, 1, 1);
1033 mat = matlib->findCached("RWY_WHITE_LIGHTS");
1035 white = mat->get_light_color();
1036 SGDirectionalLightListBin::const_iterator i;
1037 for (i = _tileGeometryBin->vasiLights.begin();
1038 i != _tileGeometryBin->vasiLights.end(); ++i) {
1039 vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1041 vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1042 lightGroup->addChild(vasiGeode);
1045 Effect* runwayEffect = 0;
1046 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1047 || !_tileGeometryBin->rabitLights.empty()
1048 || !_tileGeometryBin->reilLights.empty()
1049 || !_tileGeometryBin->odalLights.empty()
1050 || _tileGeometryBin->taxiLights.getNumLights() > 0)
1051 runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true, _options);
1052 if (_tileGeometryBin->runwayLights.getNumLights() > 0
1053 || !_tileGeometryBin->rabitLights.empty()
1054 || !_tileGeometryBin->reilLights.empty()
1055 || !_tileGeometryBin->odalLights.empty()
1056 || !_tileGeometryBin->holdshortLights.empty()
1057 || !_tileGeometryBin->guardLights.empty()) {
1058 osg::Group* rwyLights = new osg::Group;
1059 rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1060 rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1061 if (_tileGeometryBin->runwayLights.getNumLights() != 0) {
1062 EffectGeode* geode = new EffectGeode;
1063 geode->setEffect(runwayEffect);
1064 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->runwayLights));
1065 rwyLights->addChild(geode);
1067 SGDirectionalLightListBin::const_iterator i;
1068 for (i = _tileGeometryBin->rabitLights.begin();
1069 i != _tileGeometryBin->rabitLights.end(); ++i) {
1070 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1072 for (i = _tileGeometryBin->reilLights.begin();
1073 i != _tileGeometryBin->reilLights.end(); ++i) {
1074 rwyLights->addChild(SGLightFactory::getSequenced(*i, _options));
1076 for (i = _tileGeometryBin->holdshortLights.begin();
1077 i != _tileGeometryBin->holdshortLights.end(); ++i) {
1078 rwyLights->addChild(SGLightFactory::getHoldShort(*i, _options));
1080 for (i = _tileGeometryBin->guardLights.begin();
1081 i != _tileGeometryBin->guardLights.end(); ++i) {
1082 rwyLights->addChild(SGLightFactory::getGuard(*i, _options));
1084 SGLightListBin::const_iterator j;
1085 for (j = _tileGeometryBin->odalLights.begin();
1086 j != _tileGeometryBin->odalLights.end(); ++j) {
1087 rwyLights->addChild(SGLightFactory::getOdal(*j, _options));
1089 lightGroup->addChild(rwyLights);
1092 if (_tileGeometryBin->taxiLights.getNumLights() > 0) {
1093 osg::Group* taxiLights = new osg::Group;
1094 taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1095 taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1096 EffectGeode* geode = new EffectGeode;
1097 geode->setEffect(runwayEffect);
1098 geode->addDrawable(SGLightFactory::getLights(_tileGeometryBin->taxiLights));
1099 taxiLights->addChild(geode);
1100 lightGroup->addChild(taxiLights);
1103 osg::LOD* lightLOD = NULL;
1105 if (lightGroup->getNumChildren() > 0) {
1106 lightLOD = new osg::LOD;
1107 lightLOD->addChild(lightGroup.get(), 0, 60000);
1108 // VASI is always on, so doesn't use light bits.
1109 lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT | PERMANENTLIGHT_BIT);
1115 // Generate all the random forest, objects and buildings for the tile
1116 osg::LOD* generateRandomTileObjects()
1118 SGMaterialLibPtr matlib;
1119 bool use_random_objects = false;
1120 bool use_random_vegetation = false;
1121 bool use_random_buildings = false;
1122 float vegetation_density = 1.0f;
1123 float building_density = 1.0f;
1125 osg::ref_ptr<osg::Group> randomObjects;
1126 osg::ref_ptr<osg::Group> forestNode;
1127 osg::ref_ptr<osg::Group> buildingNode;
1130 matlib = _options->getMaterialLib();
1131 SGPropertyNode* propertyNode = _options->getPropertyNode().get();
1134 = propertyNode->getBoolValue("/sim/rendering/random-objects",
1135 use_random_objects);
1136 use_random_vegetation
1137 = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
1138 use_random_vegetation);
1140 = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
1141 vegetation_density);
1142 use_random_buildings
1143 = propertyNode->getBoolValue("/sim/rendering/random-buildings",
1144 use_random_buildings);
1146 = propertyNode->getFloatValue("/sim/rendering/building-density",
1153 if (matlib && (use_random_objects || use_random_buildings)) {
1154 _tileGeometryBin->computeRandomObjectsAndBuildings(matlib,
1157 use_random_buildings);
1161 if (_tileGeometryBin->randomModels.getNumModels() > 0) {
1162 // Generate a repeatable random seed
1164 mt_init(&seed, unsigned(123));
1166 std::vector<ModelLOD> models;
1167 for (unsigned int i = 0;
1168 i < _tileGeometryBin->randomModels.getNumModels(); i++) {
1169 SGMatModelBin::MatModel obj
1170 = _tileGeometryBin->randomModels.getMatModel(i);
1172 SGPropertyNode* root = _options->getPropertyNode()->getRootNode();
1173 osg::Node* node = obj.model->get_random_model(root, &seed);
1175 // Create a matrix to place the object in the correct
1176 // location, and then apply the rotation matrix created
1177 // above, with an additional random (or taken from
1178 // the object mask) heading rotation if appropriate.
1179 osg::Matrix transformMat;
1180 transformMat = osg::Matrix::translate(toOsg(obj.position));
1181 if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
1182 // Rotate the object around the z axis.
1183 double hdg = mt_rand(&seed) * M_PI * 2;
1184 transformMat.preMult(osg::Matrix::rotate(hdg,
1185 osg::Vec3d(0.0, 0.0, 1.0)));
1188 if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
1189 // Rotate the object around the z axis.
1190 double hdg = - obj.rotation * M_PI * 2;
1191 transformMat.preMult(osg::Matrix::rotate(hdg,
1192 osg::Vec3d(0.0, 0.0, 1.0)));
1195 osg::MatrixTransform* position =
1196 new osg::MatrixTransform(transformMat);
1197 position->setName("positionRandomModel");
1198 position->addChild(node);
1199 models.push_back(ModelLOD(position, obj.lod));
1201 RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
1202 quadtree.buildQuadTree(models.begin(), models.end());
1203 randomObjects = quadtree.getRoot();
1204 randomObjects->setName("Random objects");
1207 if (! _tileGeometryBin->randomBuildings.empty()) {
1208 buildingNode = createRandomBuildings(_tileGeometryBin->randomBuildings, osg::Matrix::identity(),
1210 buildingNode->setName("Random buildings");
1211 _tileGeometryBin->randomBuildings.clear();
1214 if (use_random_vegetation && matlib) {
1215 // Now add some random forest.
1216 _tileGeometryBin->computeRandomForest(matlib, vegetation_density);
1218 if (! _tileGeometryBin->randomForest.empty()) {
1219 forestNode = createForest(_tileGeometryBin->randomForest, osg::Matrix::identity(),
1221 forestNode->setName("Random trees");
1225 osg::LOD* objectLOD = NULL;
1227 if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1228 objectLOD = new osg::LOD;
1230 if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1231 if (forestNode.valid()) objectLOD->addChild(forestNode.get(), 0, 20000);
1232 if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1234 unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECEIVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1235 objectLOD->setNodeMask(nodeMask);
1241 /// The original options to use for this bunch of models
1242 osg::ref_ptr<SGReaderWriterOptions> _options;
1243 osg::ref_ptr<SGTileGeometryBin> _tileGeometryBin;
1249 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
1252 if (!tile.read_bin(path))
1255 SGMaterialLibPtr matlib;
1256 bool useVBOs = false;
1257 bool simplifyDistant = false;
1258 bool simplifyNear = false;
1259 double ratio = SG_SIMPLIFIER_RATIO;
1260 double maxLength = SG_SIMPLIFIER_MAX_LENGTH;
1261 double maxError = SG_SIMPLIFIER_MAX_ERROR;
1262 double object_range = SG_OBJECT_RANGE;
1265 matlib = options->getMaterialLib();
1266 useVBOs = (options->getPluginStringData("SimGear::USE_VBOS") == "ON");
1267 SGPropertyNode* propertyNode = options->getPropertyNode().get();
1269 // We control whether we simplify the nearby terrain and distant terrain separatey.
1270 // However, we don't allow only simplifying the near terrain!
1271 simplifyNear = propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-near", simplifyNear);
1272 simplifyDistant = simplifyNear || propertyNode->getBoolValue("/sim/rendering/terrain/simplifier/enabled-far", simplifyDistant);
1273 ratio = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/ratio", ratio);
1274 maxLength = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-length", maxLength);
1275 maxError = propertyNode->getDoubleValue("/sim/rendering/terrain/simplifier/max-error", maxError);
1276 object_range = propertyNode->getDoubleValue("/sim/rendering/static-lod/rough", object_range);
1279 SGVec3d center = tile.get_gbs_center();
1280 SGGeod geodPos = SGGeod::fromCart(center);
1281 SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
1283 // rotate the tiles so that the bounding boxes get nearly axis aligned.
1284 // this will help the collision tree's bounding boxes a bit ...
1285 std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
1286 for (unsigned i = 0; i < nodes.size(); ++i)
1287 nodes[i] = hlOr.transform(nodes[i]);
1288 tile.set_wgs84_nodes(nodes);
1290 SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
1291 std::vector<SGVec3f> normals = tile.get_normals();
1292 for (unsigned i = 0; i < normals.size(); ++i)
1293 normals[i] = hlOrf.transform(normals[i]);
1294 tile.set_normals(normals);
1296 osg::ref_ptr<SGTileGeometryBin> tileGeometryBin = new SGTileGeometryBin;
1298 if (!tileGeometryBin->insertBinObj(tile, matlib))
1302 osg::Node* node = tileGeometryBin->getSurfaceGeometry(matlib, useVBOs);
1303 if (node && simplifyDistant) {
1304 osgUtil::Simplifier simplifier(ratio, maxError, maxLength);
1305 node->accept(simplifier);
1308 // The toplevel transform for that tile.
1309 osg::MatrixTransform* transform = new osg::MatrixTransform;
1310 transform->setName(path);
1311 transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1312 osg::Matrix::translate(toOsg(center)));
1314 // PagedLOD for the random objects so we don't need to generate
1315 // them all on tile loading.
1316 osg::PagedLOD* pagedLOD = new osg::PagedLOD;
1317 pagedLOD->setCenterMode(osg::PagedLOD::USE_BOUNDING_SPHERE_CENTER);
1318 pagedLOD->setName("pagedObjectLOD");
1321 if (simplifyNear == simplifyDistant) {
1322 // Same terrain type is used for both near and far distances,
1323 // so add it to the main group.
1324 osg::Group* terrainGroup = new osg::Group;
1325 terrainGroup->setName("BTGTerrainGroup");
1326 terrainGroup->addChild(node);
1327 transform->addChild(terrainGroup);
1328 } else if (simplifyDistant) {
1329 // Simplified terrain is only used in the distance, the
1330 // call-back below will re-generate the closer version
1331 pagedLOD->addChild(node, object_range + SG_TILE_RADIUS, FLT_MAX);
1335 // we just need to know about the read file callback that itself holds the data
1336 osg::ref_ptr<RandomObjectCallback> randomObjectCallback = new RandomObjectCallback;
1337 randomObjectCallback->_options = SGReaderWriterOptions::copyOrCreate(options);
1338 randomObjectCallback->_tileGeometryBin = tileGeometryBin;
1339 randomObjectCallback->_path = std::string(path);
1340 randomObjectCallback->_loadterrain = ! (simplifyNear == simplifyDistant);
1342 osg::ref_ptr<osgDB::Options> callbackOptions = new osgDB::Options;
1343 callbackOptions->setReadFileCallback(randomObjectCallback.get());
1344 pagedLOD->setDatabaseOptions(callbackOptions.get());
1346 pagedLOD->setFileName(pagedLOD->getNumChildren(), "Dummy name - use the stored data in the read file callback");
1347 pagedLOD->setRange(pagedLOD->getNumChildren(), 0, object_range + SG_TILE_RADIUS);
1348 transform->addChild(pagedLOD);
1349 transform->setNodeMask( ~simgear::MODELLIGHT_BIT );