]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Random buildings - initial commit.
[simgear.git] / simgear / scene / tgdb / obj.cxx
1 // obj.cxx -- routines to handle loading scenery and building the plib
2 //            scene graph.
3 //
4 // Written by Curtis Olson, started October 1997.
5 //
6 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
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.
12 //
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.
17 //
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.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <simgear_config.h>
27 #endif
28
29 #include "obj.hxx"
30
31 #include <simgear/compiler.h>
32
33 #include <osg/Fog>
34 #include <osg/Geode>
35 #include <osg/Geometry>
36 #include <osg/Group>
37 #include <osg/LOD>
38 #include <osg/MatrixTransform>
39 #include <osg/Point>
40 #include <osg/StateSet>
41 #include <osg/Switch>
42
43 #include <boost/foreach.hpp>
44
45 #include <algorithm>
46
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/scene/material/Effect.hxx>
52 #include <simgear/scene/material/EffectGeode.hxx>
53 #include <simgear/scene/material/mat.hxx>
54 #include <simgear/scene/material/matlib.hxx>
55 #include <simgear/scene/model/SGOffsetTransform.hxx>
56 #include <simgear/scene/util/SGUpdateVisitor.hxx>
57 #include <simgear/scene/util/SGNodeMasks.hxx>
58 #include <simgear/scene/util/QuadTreeBuilder.hxx>
59
60 #include "SGTexturedTriangleBin.hxx"
61 #include "SGLightBin.hxx"
62 #include "SGModelBin.hxx"
63 #include "SGBuildingBin.hxx"
64 #include "TreeBin.hxx"
65 #include "SGDirectionalLightBin.hxx"
66 #include "GroundLightManager.hxx"
67
68
69 #include "pt_lights.hxx"
70
71 using namespace simgear;
72
73 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
74 typedef std::list<SGLightBin> SGLightListBin;
75 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
76
77 struct SGTileGeometryBin {
78   SGMaterialTriangleMap materialTriangleMap;
79   SGLightBin tileLights;
80   SGLightBin randomTileLights;
81   SGTreeBinList randomForest;
82   SGDirectionalLightBin runwayLights;
83   SGDirectionalLightBin taxiLights;
84   SGDirectionalLightListBin vasiLights;
85   SGDirectionalLightListBin rabitLights;
86   SGLightListBin odalLights;
87   SGDirectionalLightListBin reilLights;
88   SGMatModelBin randomModels;
89   SGBuildingBinList randomBuildings;
90
91   static SGVec4f
92   getMaterialLightColor(const SGMaterial* material)
93   {
94     if (!material)
95       return SGVec4f(1, 1, 1, 0.8);
96     return material->get_light_color();
97   }
98
99   static void
100   addPointGeometry(SGLightBin& lights,
101                    const std::vector<SGVec3d>& vertices,
102                    const SGVec4f& color,
103                    const int_list& pts_v)
104   {
105     for (unsigned i = 0; i < pts_v.size(); ++i)
106       lights.insert(toVec3f(vertices[pts_v[i]]), color);
107   }
108
109   static void
110   addPointGeometry(SGDirectionalLightBin& lights,
111                    const std::vector<SGVec3d>& vertices,
112                    const std::vector<SGVec3f>& normals,
113                    const SGVec4f& color,
114                    const int_list& pts_v,
115                    const int_list& pts_n)
116   {
117     // If the normal indices match the vertex indices, use seperate
118     // normal indices. Else reuse the vertex indices for the normals.
119     if (pts_v.size() == pts_n.size()) {
120       for (unsigned i = 0; i < pts_v.size(); ++i)
121         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
122     } else {
123       for (unsigned i = 0; i < pts_v.size(); ++i)
124         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
125     }
126   }
127
128   bool
129   insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
130   {
131     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
132       SG_LOG(SG_TERRAIN, SG_ALERT,
133              "Group list sizes for points do not match!");
134       return false;
135     }
136
137     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
138       std::string materialName = obj.get_pt_materials()[grp];
139       SGMaterial* material = 0;
140       if (matlib)
141           material = matlib->find(materialName);
142       SGVec4f color = getMaterialLightColor(material);
143
144       if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
145         // Just plain lights. Not something for the runway.
146         addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
147                          obj.get_pts_v()[grp]);
148       } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
149                  || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
150         addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
151                          color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
152       } else if (materialName == "RWY_VASI_LIGHTS") {
153         vasiLights.push_back(SGDirectionalLightBin());
154         addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
155                          obj.get_normals(), color, obj.get_pts_v()[grp],
156                          obj.get_pts_n()[grp]);
157       } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
158         rabitLights.push_back(SGDirectionalLightBin());
159         addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
160                          obj.get_normals(), color, obj.get_pts_v()[grp],
161                          obj.get_pts_n()[grp]);
162       } else if (materialName == "RWY_ODALS_LIGHTS") {
163         odalLights.push_back(SGLightBin());
164         addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
165                          color, obj.get_pts_v()[grp]);
166       } else if (materialName == "RWY_REIL_LIGHTS") {
167         reilLights.push_back(SGDirectionalLightBin());
168         addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
169                          obj.get_normals(), color, obj.get_pts_v()[grp],
170                          obj.get_pts_n()[grp]);
171       } else {
172         // what is left must be runway lights
173         addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
174                          obj.get_normals(), color, obj.get_pts_v()[grp],
175                          obj.get_pts_n()[grp]);
176       }
177     }
178
179     return true;
180   }
181
182
183   static SGVec2f
184   getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
185               const SGVec2f& tcScale, unsigned i)
186   {
187     if (tc.empty())
188       return tcScale;
189     else if (tc.size() == 1)
190       return mult(texCoords[tc[0]], tcScale);
191     else
192       return mult(texCoords[tc[i]], tcScale);
193   }
194
195   static void
196   addTriangleGeometry(SGTexturedTriangleBin& triangles,
197                       const std::vector<SGVec3d>& vertices,
198                       const std::vector<SGVec3f>& normals,
199                       const std::vector<SGVec2f>& texCoords,
200                       const int_list& tris_v,
201                       const int_list& tris_n,
202                       const int_list& tris_tc,
203                       const SGVec2f& tcScale)
204   {
205     if (tris_v.size() != tris_n.size()) {
206       // If the normal indices do not match, they should be inmplicitly
207       // the same than the vertex indices. So just call ourselves again
208       // with the matching index vector.
209       addTriangleGeometry(triangles, vertices, normals, texCoords,
210                           tris_v, tris_v, tris_tc, tcScale);
211       return;
212     }
213
214     for (unsigned i = 2; i < tris_v.size(); i += 3) {
215       SGVertNormTex v0;
216       v0.vertex = toVec3f(vertices[tris_v[i-2]]);
217       v0.normal = normals[tris_n[i-2]];
218       v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
219       SGVertNormTex v1;
220       v1.vertex = toVec3f(vertices[tris_v[i-1]]);
221       v1.normal = normals[tris_n[i-1]];
222       v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
223       SGVertNormTex v2;
224       v2.vertex = toVec3f(vertices[tris_v[i]]);
225       v2.normal = normals[tris_n[i]];
226       v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
227       triangles.insert(v0, v1, v2);
228     }
229   }
230
231   static void
232   addStripGeometry(SGTexturedTriangleBin& triangles,
233                    const std::vector<SGVec3d>& vertices,
234                    const std::vector<SGVec3f>& normals,
235                    const std::vector<SGVec2f>& texCoords,
236                    const int_list& strips_v,
237                    const int_list& strips_n,
238                    const int_list& strips_tc,
239                    const SGVec2f& tcScale)
240   {
241     if (strips_v.size() != strips_n.size()) {
242       // If the normal indices do not match, they should be inmplicitly
243       // the same than the vertex indices. So just call ourselves again
244       // with the matching index vector.
245       addStripGeometry(triangles, vertices, normals, texCoords,
246                        strips_v, strips_v, strips_tc, tcScale);
247       return;
248     }
249
250     for (unsigned i = 2; i < strips_v.size(); ++i) {
251       SGVertNormTex v0;
252       v0.vertex = toVec3f(vertices[strips_v[i-2]]);
253       v0.normal = normals[strips_n[i-2]];
254       v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
255       SGVertNormTex v1;
256       v1.vertex = toVec3f(vertices[strips_v[i-1]]);
257       v1.normal = normals[strips_n[i-1]];
258       v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
259       SGVertNormTex v2;
260       v2.vertex = toVec3f(vertices[strips_v[i]]);
261       v2.normal = normals[strips_n[i]];
262       v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
263       if (i%2)
264         triangles.insert(v1, v0, v2);
265       else
266         triangles.insert(v0, v1, v2);
267     }
268   }
269   
270   static void
271   addFanGeometry(SGTexturedTriangleBin& triangles,
272                  const std::vector<SGVec3d>& vertices,
273                  const std::vector<SGVec3f>& normals,
274                  const std::vector<SGVec2f>& texCoords,
275                  const int_list& fans_v,
276                  const int_list& fans_n,
277                  const int_list& fans_tc,
278                  const SGVec2f& tcScale)
279   {
280     if (fans_v.size() != fans_n.size()) {
281       // If the normal indices do not match, they should be implicitly
282       // the same than the vertex indices. So just call ourselves again
283       // with the matching index vector.
284       addFanGeometry(triangles, vertices, normals, texCoords,
285                      fans_v, fans_v, fans_tc, tcScale);
286       return;
287     }
288
289     SGVertNormTex v0;
290     v0.vertex = toVec3f(vertices[fans_v[0]]);
291     v0.normal = normals[fans_n[0]];
292     v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
293     SGVertNormTex v1;
294     v1.vertex = toVec3f(vertices[fans_v[1]]);
295     v1.normal = normals[fans_n[1]];
296     v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
297     for (unsigned i = 2; i < fans_v.size(); ++i) {
298       SGVertNormTex v2;
299       v2.vertex = toVec3f(vertices[fans_v[i]]);
300       v2.normal = normals[fans_n[i]];
301       v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
302       triangles.insert(v0, v1, v2);
303       v1 = v2;
304     }
305   }
306
307   SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
308   {
309     if (!matlib)
310       return SGVec2f(1, 1);
311     SGMaterial* material = matlib->find(name);
312     if (!material)
313       return SGVec2f(1, 1);
314
315     return material->get_tex_coord_scale();
316   }
317
318   bool
319   insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
320   {
321     if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
322         obj.get_tris_tc().size() < obj.get_tris_v().size()) {
323       SG_LOG(SG_TERRAIN, SG_ALERT,
324              "Group list sizes for triangles do not match!");
325       return false;
326     }
327
328     for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
329       std::string materialName = obj.get_tri_materials()[grp];
330       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
331       addTriangleGeometry(materialTriangleMap[materialName],
332                           obj.get_wgs84_nodes(), obj.get_normals(),
333                           obj.get_texcoords(), obj.get_tris_v()[grp],
334                           obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
335                           tcScale);
336     }
337
338     if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
339         obj.get_strips_tc().size() < obj.get_strips_v().size()) {
340       SG_LOG(SG_TERRAIN, SG_ALERT,
341              "Group list sizes for strips do not match!");
342       return false;
343     }
344     for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
345       std::string materialName = obj.get_strip_materials()[grp];
346       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
347       addStripGeometry(materialTriangleMap[materialName],
348                        obj.get_wgs84_nodes(), obj.get_normals(),
349                        obj.get_texcoords(), obj.get_strips_v()[grp],
350                        obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
351                        tcScale);
352     }
353
354     if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
355         obj.get_fans_tc().size() < obj.get_fans_v().size()) {
356       SG_LOG(SG_TERRAIN, SG_ALERT,
357              "Group list sizes for fans do not match!");
358       return false;
359     }
360     for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
361       std::string materialName = obj.get_fan_materials()[grp];
362       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
363       addFanGeometry(materialTriangleMap[materialName],
364                      obj.get_wgs84_nodes(), obj.get_normals(),
365                      obj.get_texcoords(), obj.get_fans_v()[grp],
366                      obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
367                      tcScale);
368     }
369     return true;
370   }
371
372   osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
373   {
374     if (materialTriangleMap.empty())
375       return 0;
376
377     EffectGeode* eg = 0;
378     osg::Group* group = (materialTriangleMap.size() > 1 ? new osg::Group : 0);
379     //osg::Geode* geode = new osg::Geode;
380     SGMaterialTriangleMap::const_iterator i;
381     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
382       osg::Geometry* geometry = i->second.buildGeometry();
383       SGMaterial *mat = 0;
384       if (matlib)
385         mat = matlib->find(i->first);
386       eg = new EffectGeode;
387       if (mat)
388         eg->setEffect(mat->get_effect(i->second));
389       eg->addDrawable(geometry);
390       eg->runGenerators(geometry);  // Generate extra data needed by effect
391       if (group)
392         group->addChild(eg);
393     }
394     if (group)
395         return group;
396     else
397         return eg;
398   }
399
400   void computeRandomSurfaceLights(SGMaterialLib* matlib)
401   {
402     SGMaterialTriangleMap::iterator i;
403         
404     // generate a repeatable random seed
405     mt seed;
406     mt_init(&seed, unsigned(123));
407     
408     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
409       SGMaterial *mat = matlib->find(i->first);
410       if (!mat)
411         continue;
412
413       float coverage = mat->get_light_coverage();
414       if (coverage <= 0)
415         continue;
416       if (coverage < 10000.0) {
417         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
418                << coverage << ", pushing up to 10000");
419         coverage = 10000;
420       }
421       
422       std::vector<SGVec3f> randomPoints;
423       i->second.addRandomSurfacePoints(coverage, 3, mat->get_object_mask(i->second), randomPoints);
424       std::vector<SGVec3f>::iterator j;
425       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
426         float zombie = mt_rand(&seed);
427         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
428         float factor = mt_rand(&seed);
429         factor *= factor;
430
431         float bright = 1;
432         SGVec4f color;
433         if ( zombie > 0.5 ) {
434           // 50% chance of yellowish
435           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
436         } else if (zombie > 0.15f) {
437           // 35% chance of whitish
438           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
439         } else if (zombie > 0.05f) {
440           // 10% chance of orangish
441           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
442         } else {
443           // 5% chance of redish
444           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
445         }
446         randomTileLights.insert(*j, color);
447       }
448     }
449   }
450   
451   void computeRandomBuildings(SGMaterialLib* matlib, float building_density)
452   {
453     SGMaterialTriangleMap::iterator i;
454         
455     // generate a repeatable random seed
456     mt seed;
457     mt_init(&seed, unsigned(123));
458     
459     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
460       SGMaterial *mat = matlib->find(i->first);
461       SGTexturedTriangleBin triangleBin = i->second;
462       
463       if (!mat)
464         continue;
465
466       osg::Texture2D* object_mask = mat->get_object_mask(triangleBin);
467
468       float coverage = mat->get_building_coverage();
469       
470       // Minimum spacing needs to include the maximum footprint of a building.
471       // As the 0,0,0 point is the center of the front of the building, we need
472       // to consider the full depth, but only half the possible width.          
473       float min_spacing = mat->get_building_spacing();
474
475       if (coverage <= 0)
476         continue;        
477         
478       bool found = false;
479       SGBuildingBin* bin = NULL;
480       
481       BOOST_FOREACH(bin, randomBuildings)
482       {
483         if (bin->texture == mat->get_building_texture()) {
484             found = true;
485             break;
486         }
487       }
488       
489       if (!found) {
490         bin = new SGBuildingBin();
491         bin->texture = mat->get_building_texture();
492         SG_LOG(SG_INPUT, SG_DEBUG, "Building texture " << bin->texture);
493         randomBuildings.push_back(bin);
494       }       
495       
496       std::vector<std::pair<SGVec3f, float> > randomPoints;
497       
498       unsigned num = i->second.getNumTriangles();
499       int triangle_dropped = 0;
500       int building_dropped = 0;
501       int random_dropped = 0;
502
503       for (unsigned i = 0; i < num; ++i) {
504         SGBuildingBin::BuildingList triangle_buildings;
505         SGTexturedTriangleBin::triangle_ref triangleRef = triangleBin.getTriangleRef(i);
506         
507         SGVec3f v0 = triangleBin.getVertex(triangleRef[0]).vertex;
508         SGVec3f v1 = triangleBin.getVertex(triangleRef[1]).vertex;
509         SGVec3f v2 = triangleBin.getVertex(triangleRef[2]).vertex;
510         SGVec2f t0 = triangleBin.getVertex(triangleRef[0]).texCoord;
511         SGVec2f t1 = triangleBin.getVertex(triangleRef[1]).texCoord;
512         SGVec2f t2 = triangleBin.getVertex(triangleRef[2]).texCoord;
513         SGVec3f normal = cross(v1 - v0, v2 - v0);
514         
515         // Compute the area
516         float area = 0.5f*length(normal);
517         if (area <= SGLimitsf::min())
518           continue;
519
520         // for partial units of area, use a zombie door method to
521         // create the proper random chance of an object being created
522         // for this triangle.
523         double num = area / coverage + mt_rand(&seed);
524         
525         // Apply density.
526         num = num * building_density;
527
528         // place an object each unit of area
529         while ( num > 1.0 ) {
530           float a = mt_rand(&seed);
531           float b = mt_rand(&seed);
532           if ( a + b > 1 ) {
533             a = 1 - a;
534             b = 1 - b;
535           }
536           
537           float c = 1 - a - b;
538           SGVec3f randomPoint = a*v0 + b*v1 + c*v2;
539           float rotation = mt_rand(&seed);
540           
541           if (object_mask != NULL) {
542             SGVec2f texCoord = a*t0 + b*t1 + c*t2;
543             osg::Image* img = object_mask->getImage();            
544             unsigned int x = (int) (img->s() * texCoord.x()) % img->s();
545             unsigned int y = (int) (img->t() * texCoord.y()) % img->t();
546             
547             if (mt_rand(&seed) < img->getColor(x, y).b()) {  
548               // Object passes mask. Rotation is taken from the red channel
549               rotation = img->getColor(x,y).r();
550             } else {
551               // Fails mask test - try again.
552               num -= 1.0;
553               continue;
554             }  
555           }
556           
557           // Now create the building, so we have an idea of its footprint
558           // and therefore appropriate spacing.
559           SGBuildingBin::BuildingType buildingtype;
560           float width;
561           float depth;
562           int floors;
563           float height;
564           bool pitched;
565                                   
566           // Determine the building type, and hence dimensions.
567           float type = mt_rand(&seed);
568           
569           if (type < mat->get_building_small_fraction()) {
570             // Small building
571             buildingtype = SGBuildingBin::SMALL;
572             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());
573             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());
574             floors = round(mat->get_building_small_min_floors() + mt_rand(&seed) * (mat->get_building_small_max_floors() - mat->get_building_small_min_floors()));
575             height = floors * (2.8 + mt_rand(&seed));
576             
577             if (depth > width) { depth = width; }
578             
579             pitched = (mt_rand(&seed) < mat->get_building_small_pitch());
580           } else if (type < (mat->get_building_small_fraction() + mat->get_building_medium_fraction())) {
581             buildingtype = SGBuildingBin::MEDIUM;
582             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());
583             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());
584             floors = round(mat->get_building_medium_min_floors() + mt_rand(&seed) * (mat->get_building_medium_max_floors() - mat->get_building_medium_min_floors()));
585             height = floors * (2.8 + mt_rand(&seed));
586             pitched = (mt_rand(&seed) < mat->get_building_medium_pitch());         
587           } else {
588             buildingtype = SGBuildingBin::LARGE;
589             width = mat->get_building_large_min_width() + mt_rand(&seed) * (mat->get_building_large_max_width() - mat->get_building_large_min_width());
590             depth = mat->get_building_large_min_depth() + mt_rand(&seed) * (mat->get_building_large_max_depth() - mat->get_building_large_min_depth());
591             floors = round(mat->get_building_large_min_floors() + mt_rand(&seed) * (mat->get_building_large_max_floors() - mat->get_building_large_min_floors())); 
592             height = floors * (2.8 + mt_rand(&seed));
593             pitched = (mt_rand(&seed) < mat->get_building_large_pitch());                   
594           }
595           
596           // Determine an appropriate minimum spacing for the object.  Note that the
597           // origin of the building model is the center of the front face, hence we
598           // consider the full depth.  We choose _not_ to use the diagonal distance
599           // to one of the rear corners, as we assume that terrain masking will
600           // make the buildings place in some sort of grid.
601           float radius = std::max(depth, 0.5f*width);
602
603           // Check that the point is sufficiently far from
604           // the edge of the triangle by measuring the distance
605           // from the three lines that make up the triangle.        
606           if (((length(cross(randomPoint - v0, randomPoint - v1)) / length(v1 - v0)) < radius) ||
607               ((length(cross(randomPoint - v1, randomPoint - v2)) / length(v2 - v1)) < radius) ||
608               ((length(cross(randomPoint - v2, randomPoint - v0)) / length(v0 - v2)) < radius)   )
609           {
610             triangle_dropped++;
611             num -= 1.0;
612             continue;
613           }
614
615           // Check against the generic random objects.  TODO - make this more efficient by
616           // masking ahead of time objects outside of the triangle.
617           bool too_close = false;
618           for (unsigned int i = 0; i < randomModels.getNumModels(); ++i) {
619             float min_dist = randomModels.getMatModel(i).model->get_spacing_m() + radius + min_spacing;
620             min_dist = min_dist * min_dist;
621             
622             if (distSqr(randomModels.getMatModel(i).position, randomPoint) < min_dist) {
623               too_close = true;
624               random_dropped++;
625               continue;
626             }          
627           }
628           
629           if (too_close) {
630             // Too close to a random model - drop and try again
631             num -= 1.0;
632             continue;            
633           }
634           
635           SGBuildingBin::BuildingList::iterator l;       
636           
637           // Check that the building is sufficiently far from any other building within the triangle.
638           for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
639             
640             float min_dist = l->radius + radius + min_spacing;
641             min_dist = min_dist * min_dist;
642             
643             if (distSqr(randomPoint, l->position) < min_dist) {
644               building_dropped++;
645               too_close = true;
646               continue;
647             }
648           }
649           
650           if (too_close) {
651             // Too close to another building - drop and try again
652             num -= 1.0;
653             continue;            
654           }
655           
656           // If we've passed all of the above tests we have a valid
657           // building, so create it!          
658           SGBuildingBin::Building building = 
659                     SGBuildingBin::Building(buildingtype, 
660                                             randomPoint, 
661                                             width, 
662                                             depth, 
663                                             height, 
664                                             floors,
665                                             rotation,
666                                             pitched);                                                            
667           triangle_buildings.push_back(building);
668           num -= 1.0;
669         }
670         
671         // Add the buildings from this triangle to the overall list.
672         SGBuildingBin::BuildingList::iterator l;  
673
674         for (l = triangle_buildings.begin(); l != triangle_buildings.end(); ++l) {
675           bin->insert(*l);
676         }
677       }
678
679       SG_LOG(SG_INPUT, SG_DEBUG, "Random Buildings: " << bin->getNumBuildings());
680       SG_LOG(SG_INPUT, SG_DEBUG, "  Dropped due to triangle edge: " << triangle_dropped);
681       SG_LOG(SG_INPUT, SG_DEBUG, "  Dropped due to random object: " << random_dropped);
682       SG_LOG(SG_INPUT, SG_DEBUG, "  Dropped due to other building: " << building_dropped);
683     }
684   }
685   
686   void computeRandomForest(SGMaterialLib* matlib, float vegetation_density)
687   {
688     SGMaterialTriangleMap::iterator i;
689
690     // generate a repeatable random seed
691     mt seed;
692     mt_init(&seed, unsigned(586));
693
694     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
695       SGMaterial *mat = matlib->find(i->first);
696       if (!mat)
697         continue;
698
699       float wood_coverage = mat->get_wood_coverage();
700       if (wood_coverage <= 0)
701         continue;
702               
703       // Attributes that don't vary by tree but do vary by material
704       bool found = false;
705       TreeBin* bin = NULL;
706       
707       BOOST_FOREACH(bin, randomForest)
708       {
709         if ((bin->texture           == mat->get_tree_texture()  ) &&
710             (bin->texture_varieties == mat->get_tree_varieties()) &&
711             (bin->range             == mat->get_tree_range()    ) &&
712             (bin->width             == mat->get_tree_width()    ) &&
713             (bin->height            == mat->get_tree_height()   )   ) {
714             found = true;
715             break;
716         }
717       }
718       
719       if (!found) {
720         bin = new TreeBin();
721         bin->texture = mat->get_tree_texture();
722           SG_LOG(SG_INPUT, SG_DEBUG, "Tree texture " << bin->texture);
723         bin->range   = mat->get_tree_range();
724         bin->width   = mat->get_tree_width();
725         bin->height  = mat->get_tree_height();
726         bin->texture_varieties = mat->get_tree_varieties();
727         randomForest.push_back(bin);
728       }
729
730       std::vector<SGVec3f> randomPoints;
731       i->second.addRandomTreePoints(wood_coverage,
732                                     mat->get_object_mask(i->second),
733                                     vegetation_density,
734                                     randomPoints);
735       
736       std::vector<SGVec3f>::iterator k;
737       for (k = randomPoints.begin(); k != randomPoints.end(); ++k) {
738         bin->insert(*k);
739       }
740     }
741   }
742
743   void computeRandomObjects(SGMaterialLib* matlib)
744   {
745     SGMaterialTriangleMap::iterator i;
746
747     // generate a repeatable random seed
748     mt seed;
749     mt_init(&seed, unsigned(123));
750
751     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
752       SGMaterial *mat = matlib->find(i->first);
753       if (!mat)
754         continue;
755
756       int group_count = mat->get_object_group_count();
757
758       if (group_count > 0)
759       {
760         for (int j = 0; j < group_count; j++)
761         {
762           SGMatModelGroup *object_group =  mat->get_object_group(j);
763           int nObjects = object_group->get_object_count();
764
765           if (nObjects > 0)
766           {
767             // For each of the random models in the group, determine an appropriate
768             // number of random placements and insert them.
769             for (int k = 0; k < nObjects; k++) {
770               SGMatModel * object = object_group->get_object(k);
771
772               std::vector<std::pair<SGVec3f, float> > randomPoints;
773
774               i->second.addRandomPoints(object->get_coverage_m2(), 
775                                         object->get_spacing_m(),
776                                         mat->get_object_mask(i->second), 
777                                         randomPoints);
778                                         
779               std::vector<std::pair<SGVec3f, float> >::iterator l;
780               for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
781                 // Only add the model if it is sufficiently far from the
782                 // other models
783                 bool close = false;                
784                 
785                 for (unsigned i = 0; i < randomModels.getNumModels(); i++) {
786                   float spacing = randomModels.getMatModel(i).model->get_spacing_m() + object->get_spacing_m();
787                   spacing = spacing * spacing;
788                   
789                   if (distSqr(randomModels.getMatModel(i).position, l->first) < spacing) {
790                     close = true;                
791                     continue;
792                   }              
793                 }            
794                 
795                 if (!close) { 
796                   randomModels.insert(l->first, object, (int)object->get_randomized_range_m(&seed), l->second);
797                 }
798               }
799             }
800           }
801         }
802       }
803     }
804   }
805
806   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
807   {
808     if (!insertPtGeometry(obj, matlib))
809       return false;
810     if (!insertSurfaceGeometry(obj, matlib))
811       return false;
812     return true;
813   }
814 };
815
816 typedef std::pair<osg::Node*, int> ModelLOD;
817 struct MakeQuadLeaf {
818     osg::LOD* operator() () const { return new osg::LOD; }
819 };
820 struct AddModelLOD {
821     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
822     {
823         leaf->addChild(mlod.first, 0, mlod.second);
824     }
825 };
826 struct GetModelLODCoord {
827     GetModelLODCoord() {}
828     GetModelLODCoord(const GetModelLODCoord& rhs)
829     {}
830     osg::Vec3 operator() (const ModelLOD& mlod) const
831     {
832         return mlod.first->getBound().center();
833     }
834 };
835
836 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
837                         GetModelLODCoord>  RandomObjectsQuadtree;
838
839 osg::Node*
840 SGLoadBTG(const std::string& path, const simgear::SGReaderWriterOptions* options)
841 {
842   SGBinObject tile;
843   if (!tile.read_bin(path))
844     return NULL;
845
846   SGMaterialLib* matlib = 0;
847   bool use_random_objects = false;
848   bool use_random_vegetation = false;
849   bool use_random_buildings = false;
850   float vegetation_density = 1.0f;  
851   float building_density = 1.0f;
852   if (options) {
853     matlib = options->getMaterialLib();
854     SGPropertyNode* propertyNode = options->getPropertyNode().get();
855     if (propertyNode) {
856         use_random_objects
857             = propertyNode->getBoolValue("/sim/rendering/random-objects",
858                                          use_random_objects);
859         use_random_vegetation
860             = propertyNode->getBoolValue("/sim/rendering/random-vegetation",
861                                          use_random_vegetation);        
862         vegetation_density
863             = propertyNode->getFloatValue("/sim/rendering/vegetation-density",
864                                           vegetation_density);
865         use_random_buildings
866             = propertyNode->getBoolValue("/sim/rendering/random-buildings",
867                                          use_random_buildings);        
868         building_density
869             = propertyNode->getFloatValue("/sim/rendering/building-density",
870                                           building_density);
871     }
872   }
873
874   SGVec3d center = tile.get_gbs_center();
875   SGGeod geodPos = SGGeod::fromCart(center);
876   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
877
878   // rotate the tiles so that the bounding boxes get nearly axis aligned.
879   // this will help the collision tree's bounding boxes a bit ...
880   std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
881   for (unsigned i = 0; i < nodes.size(); ++i)
882     nodes[i] = hlOr.transform(nodes[i]);
883   tile.set_wgs84_nodes(nodes);
884
885   SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
886   std::vector<SGVec3f> normals = tile.get_normals();
887   for (unsigned i = 0; i < normals.size(); ++i)
888     normals[i] = hlOrf.transform(normals[i]);
889   tile.set_normals(normals);
890
891   SGTileGeometryBin tileGeometryBin;
892   if (!tileGeometryBin.insertBinObj(tile, matlib))
893     return NULL;
894
895   SGVec3f up(0, 0, 1);
896   GroundLightManager* lightManager = GroundLightManager::instance();
897
898   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
899   osg::ref_ptr<osg::Group> randomObjects;
900   osg::ref_ptr<osg::Group> forestNode;
901   osg::ref_ptr<osg::Group> buildingNode;  
902   osg::Group* terrainGroup = new osg::Group;
903
904   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
905   if (node)
906     terrainGroup->addChild(node);
907
908   if (use_random_objects && matlib) {
909     tileGeometryBin.computeRandomObjects(matlib);
910
911     if (tileGeometryBin.randomModels.getNumModels() > 0) {
912       // Generate a repeatable random seed
913       mt seed;
914       mt_init(&seed, unsigned(123));
915
916       std::vector<ModelLOD> models;
917       for (unsigned int i = 0;
918            i < tileGeometryBin.randomModels.getNumModels(); i++) {
919         SGMatModelBin::MatModel obj
920           = tileGeometryBin.randomModels.getMatModel(i);          
921
922         SGPropertyNode* root = options->getPropertyNode()->getRootNode();
923         osg::Node* node = obj.model->get_random_model(root, &seed);
924       
925         // Create a matrix to place the object in the correct
926         // location, and then apply the rotation matrix created
927         // above, with an additional random (or taken from
928         // the object mask) heading rotation if appropriate.
929         osg::Matrix transformMat;
930         transformMat = osg::Matrix::translate(toOsg(obj.position));
931         if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
932           // Rotate the object around the z axis.
933           double hdg = mt_rand(&seed) * M_PI * 2;
934           transformMat.preMult(osg::Matrix::rotate(hdg,
935                                                    osg::Vec3d(0.0, 0.0, 1.0)));
936         }
937
938         if (obj.model->get_heading_type() == SGMatModel::HEADING_MASK) {
939           // Rotate the object around the z axis.
940           double hdg =  - obj.rotation * M_PI * 2;
941           transformMat.preMult(osg::Matrix::rotate(hdg,
942                                                    osg::Vec3d(0.0, 0.0, 1.0)));
943         }
944         
945         osg::MatrixTransform* position =
946           new osg::MatrixTransform(transformMat);
947         position->addChild(node);
948         models.push_back(ModelLOD(position, obj.lod));
949       }
950       RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
951       quadtree.buildQuadTree(models.begin(), models.end());
952       randomObjects = quadtree.getRoot();
953       randomObjects->setName("random objects");
954     }
955   }
956
957   if (use_random_vegetation && matlib) {
958     // Now add some random forest.
959     tileGeometryBin.computeRandomForest(matlib, vegetation_density);
960     
961     if (tileGeometryBin.randomForest.size() > 0) {
962       forestNode = createForest(tileGeometryBin.randomForest, osg::Matrix::identity(),
963                                 options);
964       forestNode->setName("Random trees");
965     }
966   } 
967
968   if (use_random_buildings && matlib) {
969     tileGeometryBin.computeRandomBuildings(matlib, building_density);
970     if (tileGeometryBin.randomBuildings.size() > 0) {
971       buildingNode = createRandomBuildings(tileGeometryBin.randomBuildings, osg::Matrix::identity(),
972                                   options);                                
973       buildingNode->setName("Random buildings");
974     }
975   }  
976
977   // FIXME: ugly, has a side effect
978   if (matlib)
979     tileGeometryBin.computeRandomSurfaceLights(matlib);
980
981   if (tileGeometryBin.tileLights.getNumLights() > 0
982       || tileGeometryBin.randomTileLights.getNumLights() > 0) {
983     osg::Group* groundLights0 = new osg::Group;
984     groundLights0->setStateSet(lightManager->getGroundLightStateSet());
985     groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
986     osg::Geode* geode = new osg::Geode;
987     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
988     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
989     groundLights0->addChild(geode);
990     lightGroup->addChild(groundLights0);
991   }
992   
993   if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
994     osg::Group* groundLights1 = new osg::Group;
995     groundLights1->setStateSet(lightManager->getGroundLightStateSet());
996     groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
997     osg::Group* groundLights2 = new osg::Group;
998     groundLights2->setStateSet(lightManager->getGroundLightStateSet());
999     groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
1000     osg::Geode* geode = new osg::Geode;
1001     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
1002     groundLights1->addChild(geode);
1003     lightGroup->addChild(groundLights1);
1004     geode = new osg::Geode;
1005     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
1006     groundLights2->addChild(geode);
1007     lightGroup->addChild(groundLights2);
1008   }
1009
1010   if (!tileGeometryBin.vasiLights.empty()) {
1011     EffectGeode* vasiGeode = new EffectGeode;
1012     Effect* vasiEffect
1013         = getLightEffect(24, osg::Vec3(1, 0.0001, 0.000001), 1, 24, true);
1014     vasiGeode->setEffect(vasiEffect);
1015     SGVec4f red(1, 0, 0, 1);
1016     SGMaterial* mat = 0;
1017     if (matlib)
1018       mat = matlib->find("RWY_RED_LIGHTS");
1019     if (mat)
1020       red = mat->get_light_color();
1021     SGVec4f white(1, 1, 1, 1);
1022     mat = 0;
1023     if (matlib)
1024       mat = matlib->find("RWY_WHITE_LIGHTS");
1025     if (mat)
1026       white = mat->get_light_color();
1027     SGDirectionalLightListBin::const_iterator i;
1028     for (i = tileGeometryBin.vasiLights.begin();
1029          i != tileGeometryBin.vasiLights.end(); ++i) {
1030       vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
1031     }
1032     vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
1033     lightGroup->addChild(vasiGeode);
1034   }
1035   
1036   Effect* runwayEffect = 0;
1037   if (tileGeometryBin.runwayLights.getNumLights() > 0
1038       || !tileGeometryBin.rabitLights.empty()
1039       || !tileGeometryBin.reilLights.empty()
1040       || !tileGeometryBin.odalLights.empty()
1041       || tileGeometryBin.taxiLights.getNumLights() > 0)
1042       runwayEffect = getLightEffect(16, osg::Vec3(1, 0.001, 0.0002), 1, 16, true);
1043   if (tileGeometryBin.runwayLights.getNumLights() > 0
1044       || !tileGeometryBin.rabitLights.empty()
1045       || !tileGeometryBin.reilLights.empty()
1046       || !tileGeometryBin.odalLights.empty()) {
1047     osg::Group* rwyLights = new osg::Group;
1048     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
1049     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
1050     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
1051       EffectGeode* geode = new EffectGeode;
1052       geode->setEffect(runwayEffect);
1053       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
1054                                                    .runwayLights));
1055       rwyLights->addChild(geode);
1056     }
1057     SGDirectionalLightListBin::const_iterator i;
1058     for (i = tileGeometryBin.rabitLights.begin();
1059          i != tileGeometryBin.rabitLights.end(); ++i) {
1060       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1061     }
1062     for (i = tileGeometryBin.reilLights.begin();
1063          i != tileGeometryBin.reilLights.end(); ++i) {
1064       rwyLights->addChild(SGLightFactory::getSequenced(*i));
1065     }
1066     SGLightListBin::const_iterator j;
1067     for (j = tileGeometryBin.odalLights.begin();
1068          j != tileGeometryBin.odalLights.end(); ++j) {
1069       rwyLights->addChild(SGLightFactory::getOdal(*j));
1070     }
1071     lightGroup->addChild(rwyLights);
1072   }
1073
1074   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
1075     osg::Group* taxiLights = new osg::Group;
1076     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
1077     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
1078     EffectGeode* geode = new EffectGeode;
1079     geode->setEffect(runwayEffect);
1080     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
1081     taxiLights->addChild(geode);
1082     lightGroup->addChild(taxiLights);
1083   }
1084
1085   // The toplevel transform for that tile.
1086   osg::MatrixTransform* transform = new osg::MatrixTransform;
1087   transform->setName(path);
1088   transform->setMatrix(osg::Matrix::rotate(toOsg(hlOr))*
1089                        osg::Matrix::translate(toOsg(center)));
1090   transform->addChild(terrainGroup);
1091   if (lightGroup->getNumChildren() > 0) {
1092     osg::LOD* lightLOD = new osg::LOD;
1093     lightLOD->addChild(lightGroup.get(), 0, 30000);
1094     // VASI is always on, so doesn't use light bits.
1095     lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT); 
1096     transform->addChild(lightLOD);
1097   }
1098   
1099   if (randomObjects.valid() || forestNode.valid() || buildingNode.valid()) {
1100   
1101     // Add a LoD node, so we don't try to display anything when the tile center
1102     // is more than 20km away.
1103     osg::LOD* objectLOD = new osg::LOD;
1104     
1105     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
1106     if (forestNode.valid())  objectLOD->addChild(forestNode.get(), 0, 20000);
1107     if (buildingNode.valid()) objectLOD->addChild(buildingNode.get(), 0, 20000);
1108     
1109     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
1110     objectLOD->setNodeMask(nodeMask);
1111     transform->addChild(objectLOD);
1112   }
1113   
1114   return transform;
1115 }