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