]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Suppress warnings
[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 <simgear/debug/logstream.hxx>
44 #include <simgear/io/sg_binobj.hxx>
45 #include <simgear/math/sg_geodesy.hxx>
46 #include <simgear/math/sg_random.h>
47 #include <simgear/scene/material/mat.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/scene/model/SGOffsetTransform.hxx>
50 #include <simgear/scene/util/SGUpdateVisitor.hxx>
51 #include <simgear/scene/util/SGNodeMasks.hxx>
52 #include <simgear/scene/util/QuadTreeBuilder.hxx>
53
54 #include "SGTexturedTriangleBin.hxx"
55 #include "SGLightBin.hxx"
56 #include "SGModelBin.hxx"
57 #include "TreeBin.hxx"
58 #include "SGDirectionalLightBin.hxx"
59 #include "GroundLightManager.hxx"
60
61
62 #include "userdata.hxx"
63 #include "pt_lights.hxx"
64
65 using namespace simgear;
66
67 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
68 typedef std::list<SGLightBin> SGLightListBin;
69 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
70
71 struct SGTileGeometryBin {
72   SGMaterialTriangleMap materialTriangleMap;
73   SGLightBin tileLights;
74   SGLightBin randomTileLights;
75   TreeBin randomForest;
76   SGDirectionalLightBin runwayLights;
77   SGDirectionalLightBin taxiLights;
78   SGDirectionalLightListBin vasiLights;
79   SGDirectionalLightListBin rabitLights;
80   SGLightListBin odalLights;
81   SGDirectionalLightListBin reilLights;
82   SGMatModelBin randomModels;
83
84   static SGVec4f
85   getMaterialLightColor(const SGMaterial* material)
86   {
87     if (!material)
88       return SGVec4f(1, 1, 1, 0.8);
89     return material->get_light_color();
90   }
91
92   static void
93   addPointGeometry(SGLightBin& lights,
94                    const std::vector<SGVec3d>& vertices,
95                    const SGVec4f& color,
96                    const int_list& pts_v)
97   {
98     for (unsigned i = 0; i < pts_v.size(); ++i)
99       lights.insert(toVec3f(vertices[pts_v[i]]), color);
100   }
101
102   static void
103   addPointGeometry(SGDirectionalLightBin& lights,
104                    const std::vector<SGVec3d>& vertices,
105                    const std::vector<SGVec3f>& normals,
106                    const SGVec4f& color,
107                    const int_list& pts_v,
108                    const int_list& pts_n)
109   {
110     // If the normal indices match the vertex indices, use seperate
111     // normal indices. Else reuse the vertex indices for the normals.
112     if (pts_v.size() == pts_n.size()) {
113       for (unsigned i = 0; i < pts_v.size(); ++i)
114         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
115     } else {
116       for (unsigned i = 0; i < pts_v.size(); ++i)
117         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
118     }
119   }
120
121   bool
122   insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
123   {
124     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
125       SG_LOG(SG_TERRAIN, SG_ALERT,
126              "Group list sizes for points do not match!");
127       return false;
128     }
129
130     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
131       std::string materialName = obj.get_pt_materials()[grp];
132       SGMaterial* material = 0;
133       if (matlib)
134           material = matlib->find(materialName);
135       SGVec4f color = getMaterialLightColor(material);
136
137       if (3 <= materialName.size() && materialName.substr(0, 3) != "RWY") {
138         // Just plain lights. Not something for the runway.
139         addPointGeometry(tileLights, obj.get_wgs84_nodes(), color,
140                          obj.get_pts_v()[grp]);
141       } else if (materialName == "RWY_BLUE_TAXIWAY_LIGHTS"
142                  || materialName == "RWY_GREEN_TAXIWAY_LIGHTS") {
143         addPointGeometry(taxiLights, obj.get_wgs84_nodes(), obj.get_normals(),
144                          color, obj.get_pts_v()[grp], obj.get_pts_n()[grp]);
145       } else if (materialName == "RWY_VASI_LIGHTS") {
146         vasiLights.push_back(SGDirectionalLightBin());
147         addPointGeometry(vasiLights.back(), obj.get_wgs84_nodes(),
148                          obj.get_normals(), color, obj.get_pts_v()[grp],
149                          obj.get_pts_n()[grp]);
150       } else if (materialName == "RWY_SEQUENCED_LIGHTS") {
151         rabitLights.push_back(SGDirectionalLightBin());
152         addPointGeometry(rabitLights.back(), obj.get_wgs84_nodes(),
153                          obj.get_normals(), color, obj.get_pts_v()[grp],
154                          obj.get_pts_n()[grp]);
155       } else if (materialName == "RWY_ODALS_LIGHTS") {
156         odalLights.push_back(SGLightBin());
157         addPointGeometry(odalLights.back(), obj.get_wgs84_nodes(),
158                          color, obj.get_pts_v()[grp]);
159       } else if (materialName == "RWY_REIL_LIGHTS") {
160         reilLights.push_back(SGDirectionalLightBin());
161         addPointGeometry(reilLights.back(), obj.get_wgs84_nodes(),
162                          obj.get_normals(), color, obj.get_pts_v()[grp],
163                          obj.get_pts_n()[grp]);
164       } else {
165         // what is left must be runway lights
166         addPointGeometry(runwayLights, obj.get_wgs84_nodes(),
167                          obj.get_normals(), color, obj.get_pts_v()[grp],
168                          obj.get_pts_n()[grp]);
169       }
170     }
171
172     return true;
173   }
174
175
176   static SGVec2f
177   getTexCoord(const std::vector<SGVec2f>& texCoords, const int_list& tc,
178               const SGVec2f& tcScale, unsigned i)
179   {
180     if (tc.empty())
181       return tcScale;
182     else if (tc.size() == 1)
183       return mult(texCoords[tc[0]], tcScale);
184     else
185       return mult(texCoords[tc[i]], tcScale);
186   }
187
188   static void
189   addTriangleGeometry(SGTexturedTriangleBin& triangles,
190                       const std::vector<SGVec3d>& vertices,
191                       const std::vector<SGVec3f>& normals,
192                       const std::vector<SGVec2f>& texCoords,
193                       const int_list& tris_v,
194                       const int_list& tris_n,
195                       const int_list& tris_tc,
196                       const SGVec2f& tcScale)
197   {
198     if (tris_v.size() != tris_n.size()) {
199       // If the normal indices do not match, they should be inmplicitly
200       // the same than the vertex indices. So just call ourselves again
201       // with the matching index vector.
202       addTriangleGeometry(triangles, vertices, normals, texCoords,
203                           tris_v, tris_v, tris_tc, tcScale);
204       return;
205     }
206
207     for (unsigned i = 2; i < tris_v.size(); i += 3) {
208       SGVertNormTex v0;
209       v0.vertex = toVec3f(vertices[tris_v[i-2]]);
210       v0.normal = normals[tris_n[i-2]];
211       v0.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-2);
212       SGVertNormTex v1;
213       v1.vertex = toVec3f(vertices[tris_v[i-1]]);
214       v1.normal = normals[tris_n[i-1]];
215       v1.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i-1);
216       SGVertNormTex v2;
217       v2.vertex = toVec3f(vertices[tris_v[i]]);
218       v2.normal = normals[tris_n[i]];
219       v2.texCoord = getTexCoord(texCoords, tris_tc, tcScale, i);
220       triangles.insert(v0, v1, v2);
221     }
222   }
223
224   static void
225   addStripGeometry(SGTexturedTriangleBin& triangles,
226                    const std::vector<SGVec3d>& vertices,
227                    const std::vector<SGVec3f>& normals,
228                    const std::vector<SGVec2f>& texCoords,
229                    const int_list& strips_v,
230                    const int_list& strips_n,
231                    const int_list& strips_tc,
232                    const SGVec2f& tcScale)
233   {
234     if (strips_v.size() != strips_n.size()) {
235       // If the normal indices do not match, they should be inmplicitly
236       // the same than the vertex indices. So just call ourselves again
237       // with the matching index vector.
238       addStripGeometry(triangles, vertices, normals, texCoords,
239                        strips_v, strips_v, strips_tc, tcScale);
240       return;
241     }
242
243     for (unsigned i = 2; i < strips_v.size(); ++i) {
244       SGVertNormTex v0;
245       v0.vertex = toVec3f(vertices[strips_v[i-2]]);
246       v0.normal = normals[strips_n[i-2]];
247       v0.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-2);
248       SGVertNormTex v1;
249       v1.vertex = toVec3f(vertices[strips_v[i-1]]);
250       v1.normal = normals[strips_n[i-1]];
251       v1.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i-1);
252       SGVertNormTex v2;
253       v2.vertex = toVec3f(vertices[strips_v[i]]);
254       v2.normal = normals[strips_n[i]];
255       v2.texCoord = getTexCoord(texCoords, strips_tc, tcScale, i);
256       if (i%2)
257         triangles.insert(v1, v0, v2);
258       else
259         triangles.insert(v0, v1, v2);
260     }
261   }
262   
263   static void
264   addFanGeometry(SGTexturedTriangleBin& triangles,
265                  const std::vector<SGVec3d>& vertices,
266                  const std::vector<SGVec3f>& normals,
267                  const std::vector<SGVec2f>& texCoords,
268                  const int_list& fans_v,
269                  const int_list& fans_n,
270                  const int_list& fans_tc,
271                  const SGVec2f& tcScale)
272   {
273     if (fans_v.size() != fans_n.size()) {
274       // If the normal indices do not match, they should be implicitly
275       // the same than the vertex indices. So just call ourselves again
276       // with the matching index vector.
277       addFanGeometry(triangles, vertices, normals, texCoords,
278                      fans_v, fans_v, fans_tc, tcScale);
279       return;
280     }
281
282     SGVertNormTex v0;
283     v0.vertex = toVec3f(vertices[fans_v[0]]);
284     v0.normal = normals[fans_n[0]];
285     v0.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 0);
286     SGVertNormTex v1;
287     v1.vertex = toVec3f(vertices[fans_v[1]]);
288     v1.normal = normals[fans_n[1]];
289     v1.texCoord = getTexCoord(texCoords, fans_tc, tcScale, 1);
290     for (unsigned i = 2; i < fans_v.size(); ++i) {
291       SGVertNormTex v2;
292       v2.vertex = toVec3f(vertices[fans_v[i]]);
293       v2.normal = normals[fans_n[i]];
294       v2.texCoord = getTexCoord(texCoords, fans_tc, tcScale, i);
295       triangles.insert(v0, v1, v2);
296       v1 = v2;
297     }
298   }
299
300   SGVec2f getTexCoordScale(const std::string& name, SGMaterialLib* matlib)
301   {
302     if (!matlib)
303       return SGVec2f(1, 1);
304     SGMaterial* material = matlib->find(name);
305     if (!material)
306       return SGVec2f(1, 1);
307
308     return material->get_tex_coord_scale();
309   }
310
311   bool
312   insertSurfaceGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
313   {
314     if (obj.get_tris_n().size() < obj.get_tris_v().size() ||
315         obj.get_tris_tc().size() < obj.get_tris_v().size()) {
316       SG_LOG(SG_TERRAIN, SG_ALERT,
317              "Group list sizes for triangles do not match!");
318       return false;
319     }
320
321     for (unsigned grp = 0; grp < obj.get_tris_v().size(); ++grp) {
322       std::string materialName = obj.get_tri_materials()[grp];
323       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
324       addTriangleGeometry(materialTriangleMap[materialName],
325                           obj.get_wgs84_nodes(), obj.get_normals(),
326                           obj.get_texcoords(), obj.get_tris_v()[grp],
327                           obj.get_tris_n()[grp], obj.get_tris_tc()[grp],
328                           tcScale);
329     }
330
331     if (obj.get_strips_n().size() < obj.get_strips_v().size() ||
332         obj.get_strips_tc().size() < obj.get_strips_v().size()) {
333       SG_LOG(SG_TERRAIN, SG_ALERT,
334              "Group list sizes for strips do not match!");
335       return false;
336     }
337     for (unsigned grp = 0; grp < obj.get_strips_v().size(); ++grp) {
338       std::string materialName = obj.get_strip_materials()[grp];
339       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
340       addStripGeometry(materialTriangleMap[materialName],
341                        obj.get_wgs84_nodes(), obj.get_normals(),
342                        obj.get_texcoords(), obj.get_strips_v()[grp],
343                        obj.get_strips_n()[grp], obj.get_strips_tc()[grp],
344                        tcScale);
345     }
346
347     if (obj.get_fans_n().size() < obj.get_fans_v().size() ||
348         obj.get_fans_tc().size() < obj.get_fans_v().size()) {
349       SG_LOG(SG_TERRAIN, SG_ALERT,
350              "Group list sizes for fans do not match!");
351       return false;
352     }
353     for (unsigned grp = 0; grp < obj.get_fans_v().size(); ++grp) {
354       std::string materialName = obj.get_fan_materials()[grp];
355       SGVec2f tcScale = getTexCoordScale(materialName, matlib);
356       addFanGeometry(materialTriangleMap[materialName],
357                      obj.get_wgs84_nodes(), obj.get_normals(),
358                      obj.get_texcoords(), obj.get_fans_v()[grp],
359                      obj.get_fans_n()[grp], obj.get_fans_tc()[grp],
360                      tcScale);
361     }
362     return true;
363   }
364
365   osg::Node* getSurfaceGeometry(SGMaterialLib* matlib) const
366   {
367     if (materialTriangleMap.empty())
368       return 0;
369
370     osg::Geode* geode = new osg::Geode;
371     SGMaterialTriangleMap::const_iterator i;
372     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
373       osg::Geometry* geometry = i->second.buildGeometry();
374       SGMaterial *mat = 0;
375       if (matlib)
376         mat = matlib->find(i->first);
377       if (mat)
378         geometry->setStateSet(mat->get_state());
379       geode->addDrawable(geometry);
380     }
381     return geode;
382   }
383
384   void computeRandomSurfaceLights(SGMaterialLib* matlib)
385   {
386     SGMaterialTriangleMap::iterator i;
387         
388     // generate a repeatable random seed
389     mt seed;
390     mt_init(&seed, unsigned(123));
391     
392     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
393       SGMaterial *mat = matlib->find(i->first);
394       if (!mat)
395         continue;
396
397       float coverage = mat->get_light_coverage();
398       if (coverage <= 0)
399         continue;
400       if (coverage < 10000.0) {
401         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
402                << coverage << ", pushing up to 10000");
403         coverage = 10000;
404       }
405       
406       std::vector<SGVec3f> randomPoints;
407       i->second.addRandomSurfacePoints(coverage, 3, randomPoints);
408       std::vector<SGVec3f>::iterator j;
409       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
410         float zombie = mt_rand(&seed);
411         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
412         float factor = mt_rand(&seed);
413         factor *= factor;
414
415         float bright = 1;
416         SGVec4f color;
417         if ( zombie > 0.5 ) {
418           // 50% chance of yellowish
419           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
420         } else if (zombie > 0.15f) {
421           // 35% chance of whitish
422           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
423         } else if (zombie > 0.05f) {
424           // 10% chance of orangish
425           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
426         } else {
427           // 5% chance of redish
428           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
429         }
430         randomTileLights.insert(*j, color);
431       }
432     }
433   }
434
435   void computeRandomForest(SGMaterialLib* matlib)
436   {
437     SGMaterialTriangleMap::iterator i;
438
439     // generate a repeatable random seed
440     mt seed;
441     mt_init(&seed, unsigned(586));
442
443     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
444       SGMaterial *mat = matlib->find(i->first);
445       if (!mat)
446         continue;
447
448       float coverage = mat->get_tree_coverage();
449       if (coverage <= 0)
450         continue;
451
452       // Attributes that don't vary by tree
453       randomForest.texture = mat->get_tree_texture();
454       randomForest.range   = mat->get_tree_range();
455       randomForest.width   = mat->get_tree_width();
456       randomForest.height  = mat->get_tree_height();
457       randomForest.texture_varieties = mat->get_tree_varieties();
458
459       std::vector<SGVec3f> randomPoints;
460       i->second.addRandomSurfacePoints(coverage, 0, randomPoints);
461       std::vector<SGVec3f>::iterator j;
462       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
463
464         // Apply a random scaling factor and texture index.
465         float scale = (mt_rand(&seed) + mt_rand(&seed)) / 2.0f + 0.5f;
466         int v = (int) (mt_rand(&seed) * mat->get_tree_varieties());
467         if (v == mat->get_tree_varieties()) v--;         
468         randomForest.insert(*j, v, scale);
469       }
470     }
471   }
472
473   void computeRandomObjects(SGMaterialLib* matlib)
474   {
475     SGMaterialTriangleMap::iterator i;
476
477     // generate a repeatable random seed
478     mt seed;
479     mt_init(&seed, unsigned(123));
480
481     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
482       SGMaterial *mat = matlib->find(i->first);
483       if (!mat)
484         continue;
485
486       int group_count = mat->get_object_group_count();
487
488       if (group_count > 0)
489       {
490         for (int j = 0; j < group_count; j++)
491         {
492           SGMatModelGroup *object_group =  mat->get_object_group(j);
493           int nObjects = object_group->get_object_count();
494
495           if (nObjects > 0)
496           {
497             // For each of the random models in the group, determine an appropriate
498             // number of random placements and insert them.
499             for (int k = 0; k < nObjects; k++) {
500               SGMatModel * object = object_group->get_object(k);
501
502               std::vector<SGVec3f> randomPoints;
503
504               i->second.addRandomPoints(object->get_coverage_m2(), randomPoints);
505               std::vector<SGVec3f>::iterator l;
506               for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
507                 randomModels.insert(*l, object, (int)object->get_randomized_range_m(&seed));
508               }
509             }
510           }
511         }
512       }
513     }
514   }
515
516   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
517   {
518     if (!insertPtGeometry(obj, matlib))
519       return false;
520     if (!insertSurfaceGeometry(obj, matlib))
521       return false;
522     return true;
523   }
524 };
525
526 typedef std::pair<osg::Node*, int> ModelLOD;
527 struct MakeQuadLeaf {
528     osg::LOD* operator() () const { return new osg::LOD; }
529 };
530 struct AddModelLOD {
531     void operator() (osg::LOD* leaf, ModelLOD& mlod) const
532     {
533         leaf->addChild(mlod.first, 0, mlod.second);
534     }
535 };
536 struct GetModelLODCoord {
537     GetModelLODCoord() {}
538     GetModelLODCoord(const GetModelLODCoord& rhs)
539     {}
540     osg::Vec3 operator() (const ModelLOD& mlod) const
541     {
542         return mlod.first->getBound().center();
543     }
544 };
545
546 typedef QuadTreeBuilder<osg::LOD*, ModelLOD, MakeQuadLeaf, AddModelLOD,
547                         GetModelLODCoord>  RandomObjectsQuadtree;
548
549 osg::Node*
550 SGLoadBTG(const std::string& path, SGMaterialLib *matlib, bool calc_lights, bool use_random_objects, bool use_random_vegetation)
551 {
552   SGBinObject tile;
553   if (!tile.read_bin(path))
554     return false;
555
556   SGVec3d center = tile.get_gbs_center2();
557   SGGeod geodPos = SGGeod::fromCart(center);
558   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos)*SGQuatd::fromEulerDeg(0, 0, 180);
559
560   // rotate the tiles so that the bounding boxes get nearly axis aligned.
561   // this will help the collision tree's bounding boxes a bit ...
562   std::vector<SGVec3d> nodes = tile.get_wgs84_nodes();
563   for (unsigned i = 0; i < nodes.size(); ++i)
564     nodes[i] = hlOr.transform(nodes[i]);
565   tile.set_wgs84_nodes(nodes);
566
567   SGQuatf hlOrf(hlOr[0], hlOr[1], hlOr[2], hlOr[3]);
568   std::vector<SGVec3f> normals = tile.get_normals();
569   for (unsigned i = 0; i < normals.size(); ++i)
570     normals[i] = hlOrf.transform(normals[i]);
571   tile.set_normals(normals);
572
573   SGTileGeometryBin tileGeometryBin;
574   if (!tileGeometryBin.insertBinObj(tile, matlib))
575     return false;
576
577   SGVec3f up(0, 0, 1);
578   GroundLightManager* lightManager = GroundLightManager::instance();
579
580   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
581   osg::ref_ptr<osg::Group> randomObjects;
582   osg::ref_ptr<osg::Group> randomForest;
583   osg::Group* terrainGroup = new osg::Group;
584
585   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
586   if (node)
587     terrainGroup->addChild(node);
588
589   if (use_random_objects || use_random_vegetation) {
590     if (use_random_objects) {
591       if (matlib)
592         tileGeometryBin.computeRandomObjects(matlib);
593     
594       if (tileGeometryBin.randomModels.getNumModels() > 0) {
595         // Generate a repeatable random seed
596         mt seed;
597         mt_init(&seed, unsigned(123));
598
599         std::vector<ModelLOD> models;
600         for (unsigned int i = 0;
601              i < tileGeometryBin.randomModels.getNumModels(); i++) {
602           SGMatModelBin::MatModel obj
603             = tileGeometryBin.randomModels.getMatModel(i);
604           osg::Node* node = sgGetRandomModel(obj.model);
605         
606           // Create a matrix to place the object in the correct
607           // location, and then apply the rotation matrix created
608           // above, with an additional random heading rotation if appropriate.
609           osg::Matrix transformMat;
610           transformMat = osg::Matrix::translate(obj.position.osg());
611           if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
612             // Rotate the object around the z axis.
613             double hdg = mt_rand(&seed) * M_PI * 2;
614             transformMat.preMult(osg::Matrix::rotate(hdg,
615                                                      osg::Vec3d(0.0, 0.0, 1.0)));
616           }
617           osg::MatrixTransform* position =
618             new osg::MatrixTransform(transformMat);
619           position->addChild(node);
620           models.push_back(ModelLOD(position, obj.lod));
621         }
622         RandomObjectsQuadtree quadtree((GetModelLODCoord()), (AddModelLOD()));
623         quadtree.buildQuadTree(models.begin(), models.end());
624         randomObjects = quadtree.getRoot();
625         randomObjects->setName("random objects");
626       }
627     }
628
629     if (use_random_vegetation && matlib) {
630       // Now add some random forest.
631       tileGeometryBin.computeRandomForest(matlib);
632
633       if (tileGeometryBin.randomForest.getNumTrees() > 0) {
634         randomForest = createForest(tileGeometryBin.randomForest,
635                                     osg::Matrix::identity());
636         randomForest->setName("random trees");
637       }
638     } 
639   }
640
641   if (calc_lights) {
642     // FIXME: ugly, has a side effect
643     if (matlib)
644       tileGeometryBin.computeRandomSurfaceLights(matlib);
645
646     if (tileGeometryBin.tileLights.getNumLights() > 0
647         || tileGeometryBin.randomTileLights.getNumLights() > 0) {
648       osg::Group* groundLights0 = new osg::Group;
649       groundLights0->setStateSet(lightManager->getGroundLightStateSet());
650       groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
651       osg::Geode* geode = new osg::Geode;
652       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
653       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
654       groundLights0->addChild(geode);
655       lightGroup->addChild(groundLights0);
656     }
657     if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
658       osg::Group* groundLights1 = new osg::Group;
659       groundLights1->setStateSet(lightManager->getGroundLightStateSet());
660       groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
661       osg::Group* groundLights2 = new osg::Group;
662       groundLights2->setStateSet(lightManager->getGroundLightStateSet());
663       groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
664       osg::Geode* geode = new osg::Geode;
665       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
666       groundLights1->addChild(geode);
667       lightGroup->addChild(groundLights1);
668       geode = new osg::Geode;
669       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
670       groundLights2->addChild(geode);
671       lightGroup->addChild(groundLights2);
672     }
673   }
674
675   if (!tileGeometryBin.vasiLights.empty()) {
676     osg::Geode* vasiGeode = new osg::Geode;
677     SGVec4f red(1, 0, 0, 1);
678     SGMaterial* mat = 0;
679     if (matlib)
680       mat = matlib->find("RWY_RED_LIGHTS");
681     if (mat)
682       red = mat->get_light_color();
683     SGVec4f white(1, 1, 1, 1);
684     mat = 0;
685     if (matlib)
686       mat = matlib->find("RWY_WHITE_LIGHTS");
687     if (mat)
688       white = mat->get_light_color();
689
690     SGDirectionalLightListBin::const_iterator i;
691     for (i = tileGeometryBin.vasiLights.begin();
692          i != tileGeometryBin.vasiLights.end(); ++i) {
693       vasiGeode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
694     }
695     vasiGeode->setCullCallback(new SGPointSpriteLightCullCallback(osg::Vec3(1, 0.0001, 0.000001), 6));
696     vasiGeode->setStateSet(lightManager->getRunwayLightStateSet());
697     lightGroup->addChild(vasiGeode);
698   }
699
700   if (tileGeometryBin.runwayLights.getNumLights() > 0
701       || !tileGeometryBin.rabitLights.empty()
702       || !tileGeometryBin.reilLights.empty()
703       || !tileGeometryBin.odalLights.empty()) {
704     osg::Group* rwyLights = new osg::Group;
705     rwyLights->setCullCallback(new SGPointSpriteLightCullCallback);
706     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
707     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
708     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
709       osg::Geode* geode = new osg::Geode;
710       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
711                                                    .runwayLights));
712       rwyLights->addChild(geode);
713     }
714     SGDirectionalLightListBin::const_iterator i;
715     for (i = tileGeometryBin.rabitLights.begin();
716          i != tileGeometryBin.rabitLights.end(); ++i) {
717       rwyLights->addChild(SGLightFactory::getSequenced(*i));
718     }
719     for (i = tileGeometryBin.reilLights.begin();
720          i != tileGeometryBin.reilLights.end(); ++i) {
721       rwyLights->addChild(SGLightFactory::getSequenced(*i));
722     }
723     SGLightListBin::const_iterator j;
724     for (j = tileGeometryBin.odalLights.begin();
725          j != tileGeometryBin.odalLights.end(); ++j) {
726       rwyLights->addChild(SGLightFactory::getOdal(*j));
727     }
728     lightGroup->addChild(rwyLights);
729   }
730
731   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
732     osg::Group* taxiLights = new osg::Group;
733     taxiLights->setCullCallback(new SGPointSpriteLightCullCallback);
734     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
735     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
736     osg::Geode* geode = new osg::Geode;
737     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
738     taxiLights->addChild(geode);
739     lightGroup->addChild(taxiLights);
740   }
741
742   // The toplevel transform for that tile.
743   osg::MatrixTransform* transform = new osg::MatrixTransform;
744   transform->setName(path);
745   transform->setMatrix(osg::Matrix::rotate(hlOr.osg())*
746                        osg::Matrix::translate(center.osg()));
747   transform->addChild(terrainGroup);
748   if (lightGroup->getNumChildren() > 0) {
749     osg::LOD* lightLOD = new osg::LOD;
750     lightLOD->addChild(lightGroup.get(), 0, 30000);
751     // VASI is always on, so doesn't use light bits.
752     lightLOD->setNodeMask(LIGHTS_BITS | MODEL_BIT); 
753     transform->addChild(lightLOD);
754   }
755   
756   if (randomObjects.valid() || randomForest.valid()) {
757   
758     // Add a LoD node, so we don't try to display anything when the tile center
759     // is more than 20km away.
760     osg::LOD* objectLOD = new osg::LOD;
761     
762     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
763     if (randomForest.valid())  objectLOD->addChild(randomForest.get(), 0, 20000);
764     
765     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT | SG_NODEMASK_TERRAIN_BIT;
766     objectLOD->setNodeMask(nodeMask);
767     transform->addChild(objectLOD);
768   }
769   
770   return transform;
771 }