]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/obj.cxx
Random trees from Stuart Buchanan
[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 #include <simgear/threads/SGThread.hxx>
54 #include <simgear/threads/SGGuard.hxx>
55
56 #include "SGTexturedTriangleBin.hxx"
57 #include "SGLightBin.hxx"
58 #include "SGModelBin.hxx"
59 #include "TreeBin.hxx"
60 #include "SGDirectionalLightBin.hxx"
61 #include "GroundLightManager.hxx"
62
63
64 #include "userdata.hxx"
65 #include "pt_lights.hxx"
66
67 using namespace simgear;
68
69 typedef std::map<std::string,SGTexturedTriangleBin> SGMaterialTriangleMap;
70 typedef std::list<SGLightBin> SGLightListBin;
71 typedef std::list<SGDirectionalLightBin> SGDirectionalLightListBin;
72
73 struct SGTileGeometryBin {
74   SGMaterialTriangleMap materialTriangleMap;
75   SGLightBin tileLights;
76   SGLightBin randomTileLights;
77   TreeBin randomForest;
78   SGDirectionalLightBin runwayLights;
79   SGDirectionalLightBin taxiLights;
80   SGDirectionalLightListBin vasiLights;
81   SGDirectionalLightListBin rabitLights;
82   SGLightListBin odalLights;
83   SGDirectionalLightListBin reilLights;
84   SGMatModelBin randomModels;
85
86   static SGVec4f
87   getMaterialLightColor(const SGMaterial* material)
88   {
89     if (!material)
90       return SGVec4f(1, 1, 1, 0.8);
91     return material->get_light_color();
92   }
93
94   static void
95   addPointGeometry(SGLightBin& lights,
96                    const std::vector<SGVec3d>& vertices,
97                    const SGVec4f& color,
98                    const int_list& pts_v)
99   {
100     for (unsigned i = 0; i < pts_v.size(); ++i)
101       lights.insert(toVec3f(vertices[pts_v[i]]), color);
102   }
103
104   static void
105   addPointGeometry(SGDirectionalLightBin& lights,
106                    const std::vector<SGVec3d>& vertices,
107                    const std::vector<SGVec3f>& normals,
108                    const SGVec4f& color,
109                    const int_list& pts_v,
110                    const int_list& pts_n)
111   {
112     // If the normal indices match the vertex indices, use seperate
113     // normal indices. Else reuse the vertex indices for the normals.
114     if (pts_v.size() == pts_n.size()) {
115       for (unsigned i = 0; i < pts_v.size(); ++i)
116         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_n[i]], color);
117     } else {
118       for (unsigned i = 0; i < pts_v.size(); ++i)
119         lights.insert(toVec3f(vertices[pts_v[i]]), normals[pts_v[i]], color);
120     }
121   }
122
123   bool
124   insertPtGeometry(const SGBinObject& obj, SGMaterialLib* matlib)
125   {
126     if (obj.get_pts_v().size() != obj.get_pts_n().size()) {
127       SG_LOG(SG_TERRAIN, SG_ALERT,
128              "Group list sizes for points do not match!");
129       return false;
130     }
131
132     for (unsigned grp = 0; grp < obj.get_pts_v().size(); ++grp) {
133       std::string materialName = obj.get_pt_materials()[grp];
134       SGMaterial* 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       // CHUNCKED (sic) here splits up unconnected triangles parts of
374       // the mesh into different Geometry sets, presumably for better
375       // culling. I (timoore) believe it is more performant to build
376       // the biggest indexed sets possible at the expense of tight
377       // culling.
378 //#define CHUNCKED
379 #ifdef CHUNCKED
380       SGMaterial *mat = matlib->find(i->first);
381
382       std::list<SGTexturedTriangleBin::TriangleVector> connectSets;
383       i->second.getConnectedSets(connectSets);
384
385       std::list<SGTexturedTriangleBin::TriangleVector>::iterator j;
386       for (j = connectSets.begin(); j != connectSets.end(); ++j) {
387         osg::Geometry* geometry = i->second.buildGeometry(*j);
388         if (mat)
389           geometry->setStateSet(mat->get_state());
390         geode->addDrawable(geometry);
391       }
392 #else
393       osg::Geometry* geometry = i->second.buildGeometry();
394       SGMaterial *mat = matlib->find(i->first);
395       if (mat)
396         geometry->setStateSet(mat->get_state());
397       geode->addDrawable(geometry);
398 #endif
399     }
400     return geode;
401   }
402
403   void computeRandomSurfaceLights(SGMaterialLib* matlib)
404   {
405     SGMaterialTriangleMap::iterator i;
406         
407     // generate a repeatable random seed
408     mt seed;
409     mt_init(&seed, unsigned(123));
410     
411     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
412       SGMaterial *mat = matlib->find(i->first);
413       if (!mat)
414         continue;
415
416       float coverage = mat->get_light_coverage();
417       if (coverage <= 0)
418         continue;
419       if (coverage < 10000.0) {
420         SG_LOG(SG_INPUT, SG_ALERT, "Light coverage is "
421                << coverage << ", pushing up to 10000");
422         coverage = 10000;
423       }
424       
425       std::vector<SGVec3f> randomPoints;
426       i->second.addRandomSurfacePoints(coverage, 3, randomPoints);
427       std::vector<SGVec3f>::iterator j;
428       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {
429         float zombie = mt_rand(&seed);
430         // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
431         float factor = mt_rand(&seed);
432         factor *= factor;
433
434         float bright = 1;
435         SGVec4f color;
436         if ( zombie > 0.5 ) {
437           // 50% chance of yellowish
438           color = SGVec4f(0.9f, 0.9f, 0.3f, bright - factor * 0.2f);
439         } else if (zombie > 0.15f) {
440           // 35% chance of whitish
441           color = SGVec4f(0.9, 0.9f, 0.8f, bright - factor * 0.2f);
442         } else if (zombie > 0.05f) {
443           // 10% chance of orangish
444           color = SGVec4f(0.9f, 0.6f, 0.2f, bright - factor * 0.2f);
445         } else {
446           // 5% chance of redish
447           color = SGVec4f(0.9f, 0.2f, 0.2f, bright - factor * 0.2f);
448         }
449         randomTileLights.insert(*j, color);
450       }
451     }
452   }
453
454   void computeRandomForest(SGMaterialLib* matlib)
455   {
456     SGMaterialTriangleMap::iterator i;
457         
458     // generate a repeatable random seed
459     mt seed;
460     mt_init(&seed, unsigned(586));
461     
462     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
463       SGMaterial *mat = matlib->find(i->first);
464       if (!mat)
465         continue;
466
467       float coverage = mat->get_tree_coverage();
468       if (coverage <= 0)
469         continue;
470         
471       vector<string> textures = mat->get_tree_textures();
472       
473       std::vector<SGVec3f> randomPoints;
474       i->second.addRandomSurfacePoints(coverage, 0, randomPoints);
475       std::vector<SGVec3f>::iterator j;
476       for (j = randomPoints.begin(); j != randomPoints.end(); ++j) {      
477         int k = mt_rand(&seed) * textures.size();        
478         if (k == textures.size()) k--;         
479         randomForest.insert(*j, textures[k], mat->get_tree_height(), mat->get_tree_width(), mat->get_tree_range());
480       }
481     }
482   }
483   
484   void computeRandomObjects(SGMaterialLib* matlib)
485   {
486     SGMaterialTriangleMap::iterator i;
487     
488     // generate a repeatable random seed
489     mt seed;
490     mt_init(&seed, unsigned(123));
491
492     for (i = materialTriangleMap.begin(); i != materialTriangleMap.end(); ++i) {
493       SGMaterial *mat = matlib->find(i->first);
494       if (!mat)
495         continue;
496       
497       int group_count = mat->get_object_group_count();
498       
499       if (group_count > 0)
500       {      
501         for (int j = 0; j < group_count; j++)
502         {      
503           SGMatModelGroup *object_group =  mat->get_object_group(j);
504           int nObjects = object_group->get_object_count();
505           
506           if (nObjects > 0)
507           {
508             // For each of the random models in the group, determine an appropriate
509             // number of random placements and insert them.
510             for (int k = 0; k < nObjects; k++) {
511               SGMatModel * object = object_group->get_object(k);
512               
513               std::vector<SGVec3f> randomPoints;
514
515               i->second.addRandomPoints(object->get_coverage_m2(), randomPoints);
516               std::vector<SGVec3f>::iterator l;
517               for (l = randomPoints.begin(); l != randomPoints.end(); ++l) {
518                 randomModels.insert(*l, object, object->get_randomized_range_m(&seed));
519               }
520             }
521           }
522         }
523       }
524     }
525   }
526
527   bool insertBinObj(const SGBinObject& obj, SGMaterialLib* matlib)
528   {
529     if (!insertPtGeometry(obj, matlib))
530       return false;
531     if (!insertSurfaceGeometry(obj, matlib))
532       return false;
533     return true;
534   }
535 };
536
537 osg::Node*
538 SGLoadBTG(const std::string& path, SGMaterialLib *matlib, bool calc_lights, bool use_random_objects)
539 {
540   SGBinObject tile;
541   if (!tile.read_bin(path))
542     return false;
543
544   SGTileGeometryBin tileGeometryBin;
545   if (!tileGeometryBin.insertBinObj(tile, matlib))
546     return false;
547
548   SGVec3d center = tile.get_gbs_center2();
549   SGGeod geodPos = SGGeod::fromCart(center);
550   SGQuatd hlOr = SGQuatd::fromLonLat(geodPos);
551   SGVec3f up = toVec3f(hlOr.backTransform(SGVec3d(0, 0, -1)));
552   osg::Matrix world2Tile(-hlOr.osg());
553   GroundLightManager* lightManager = GroundLightManager::instance();
554
555   osg::ref_ptr<osg::Group> lightGroup = new SGOffsetTransform(0.94);
556   osg::ref_ptr<osg::Group> randomObjects;
557   osg::ref_ptr<osg::Group> randomForest;
558   osg::Group* terrainGroup = new osg::Group;
559   
560   osg::Node* node = tileGeometryBin.getSurfaceGeometry(matlib);
561   if (node)
562     terrainGroup->addChild(node);
563     
564   if (use_random_objects) {
565   
566     // Simple matrix for used for flipping models that have been oriented
567     // with the center of the tile but upside down.
568     static const osg::Matrix flip(1,  0,  0, 0,
569                                   0, -1,  0, 0,
570                                   0,  0, -1, 0,
571                                   0,  0,  0, 1);     
572   
573     tileGeometryBin.computeRandomObjects(matlib);
574     
575     if (tileGeometryBin.randomModels.getNumModels() > 0) {
576       // Generate a repeatable random seed
577       mt seed;
578       mt_init(&seed, unsigned(123));
579     
580       // Determine an rotation matrix for the models to place them 
581       // perpendicular to the earth's surface. We use the same matrix, 
582       // based on the centre of the tile, as the small angular differences  
583       // between different points on the tile aren't worth worrying about 
584       // for random objects. We also need to flip the orientation 180 degrees
585       osg::Matrix mAtt = flip * osg::Matrix::rotate(hlOr.osg());
586       
587       LodMap models;
588       
589       for (unsigned int i = 0; i < tileGeometryBin.randomModels.getNumModels(); i++) {
590         SGMatModelBin::MatModel obj = tileGeometryBin.randomModels.getMatModel(i);
591         osg::Node* node = sgGetRandomModel(obj.model);
592         
593         // Create a matrix to place the object in the correct location, and then
594         // apply the rotation matrix created above, with an additional random
595         // heading rotation if appropriate.
596         osg::Matrix mPos = osg::Matrix::translate(obj.position.osg());        
597         osg::MatrixTransform* position;
598         
599         if (obj.model->get_heading_type() == SGMatModel::HEADING_RANDOM) {
600           // Rotate the object around the z axis.
601           double hdg = mt_rand(&seed) * M_PI * 2;
602           osg::Matrix rot(cos(hdg), -sin(hdg), 0, 0,
603                           sin(hdg),  cos(hdg), 0, 0,
604                           0,         0, 1, 0,
605                           0,         0, 0, 1);     
606           position = new osg::MatrixTransform(rot * mAtt * mPos);
607         } else {
608           position = new osg::MatrixTransform(mAtt * mPos);
609         }
610
611         position->addChild(node);        
612         models.insert(std::pair<osg::ref_ptr<osg::Node>,int>(position, obj.lod));
613       }
614       
615       randomObjects = QuadTreeBuilder::makeQuadTree(models, world2Tile);
616       randomObjects->setName("random objects");
617     }
618       
619     // Now add some random forest.
620     tileGeometryBin.computeRandomForest(matlib);
621     
622     if (tileGeometryBin.randomForest.getNumTrees() > 0) {
623       osg::Matrix forAtt = flip * world2Tile;
624       randomForest = createForest(tileGeometryBin.randomForest, forAtt);
625       randomForest->setName("random trees");      
626     } 
627   }
628
629   if (calc_lights) {
630     // FIXME: ugly, has a side effect
631     tileGeometryBin.computeRandomSurfaceLights(matlib);
632
633     if (tileGeometryBin.tileLights.getNumLights() > 0
634         || tileGeometryBin.randomTileLights.getNumLights() > 0) {
635       osg::Group* groundLights0 = new osg::Group;
636       groundLights0->setStateSet(lightManager->getGroundLightStateSet());
637       groundLights0->setNodeMask(GROUNDLIGHTS0_BIT);
638       osg::Geode* geode = new osg::Geode;
639       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.tileLights));
640       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 4, -0.3f));
641       groundLights0->addChild(geode);
642       lightGroup->addChild(groundLights0);
643     }
644     if (tileGeometryBin.randomTileLights.getNumLights() > 0) {
645       osg::Group* groundLights1 = new osg::Group;
646       groundLights1->setStateSet(lightManager->getGroundLightStateSet());
647       groundLights1->setNodeMask(GROUNDLIGHTS1_BIT);
648       osg::Group* groundLights2 = new osg::Group;
649       groundLights2->setStateSet(lightManager->getGroundLightStateSet());
650       groundLights2->setNodeMask(GROUNDLIGHTS2_BIT);
651       osg::Geode* geode = new osg::Geode;
652       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights, 2, -0.15f));
653       groundLights1->addChild(geode);
654       lightGroup->addChild(groundLights1);
655       geode = new osg::Geode;
656       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.randomTileLights));
657       groundLights2->addChild(geode);
658       lightGroup->addChild(groundLights2);
659     }
660   }
661     
662   if (!tileGeometryBin.vasiLights.empty()) {
663     SGVec4f red(1, 0, 0, 1);
664     SGMaterial* mat = matlib->find("RWY_RED_LIGHTS");
665     if (mat)
666       red = mat->get_light_color();
667     SGVec4f white(1, 1, 1, 1);
668     mat = matlib->find("RWY_WHITE_LIGHTS");
669     if (mat)
670       white = mat->get_light_color();
671
672     osg::Geode* geode = new osg::Geode;
673     SGDirectionalLightListBin::const_iterator i;
674     for (i = tileGeometryBin.vasiLights.begin();
675          i != tileGeometryBin.vasiLights.end(); ++i) {
676       geode->addDrawable(SGLightFactory::getVasi(up, *i, red, white));
677     }
678     osg::Group* vasiLights = new osg::Group;
679     vasiLights->setCullCallback(new SGPointSpriteLightCullCallback(osg::Vec3(1, 0.0001, 0.000001), 6));
680     vasiLights->setStateSet(lightManager->getRunwayLightStateSet());
681     vasiLights->addChild(geode);
682     lightGroup->addChild(vasiLights);
683   }
684
685   if (tileGeometryBin.runwayLights.getNumLights() > 0
686       || !tileGeometryBin.rabitLights.empty()
687       || !tileGeometryBin.reilLights.empty()
688       || !tileGeometryBin.odalLights.empty()) {
689     osg::Group* rwyLights = new osg::Group;
690     rwyLights->setCullCallback(new SGPointSpriteLightCullCallback);
691     rwyLights->setStateSet(lightManager->getRunwayLightStateSet());
692     rwyLights->setNodeMask(RUNWAYLIGHTS_BIT);
693     if (tileGeometryBin.runwayLights.getNumLights() != 0) {
694       osg::Geode* geode = new osg::Geode;
695       geode->addDrawable(SGLightFactory::getLights(tileGeometryBin
696                                                    .runwayLights));
697       rwyLights->addChild(geode);
698     }
699     SGDirectionalLightListBin::const_iterator i;
700     for (i = tileGeometryBin.rabitLights.begin();
701          i != tileGeometryBin.rabitLights.end(); ++i) {
702       rwyLights->addChild(SGLightFactory::getSequenced(*i));
703     }
704     for (i = tileGeometryBin.reilLights.begin();
705          i != tileGeometryBin.reilLights.end(); ++i) {
706       rwyLights->addChild(SGLightFactory::getSequenced(*i));
707     }
708     SGLightListBin::const_iterator j;
709     for (j = tileGeometryBin.odalLights.begin();
710          j != tileGeometryBin.odalLights.end(); ++j) {
711       rwyLights->addChild(SGLightFactory::getOdal(*j));
712     }
713     lightGroup->addChild(rwyLights);
714   }
715
716   if (tileGeometryBin.taxiLights.getNumLights() > 0) {
717     osg::Group* taxiLights = new osg::Group;
718     taxiLights->setCullCallback(new SGPointSpriteLightCullCallback);
719     taxiLights->setStateSet(lightManager->getTaxiLightStateSet());
720     taxiLights->setNodeMask(RUNWAYLIGHTS_BIT);
721     osg::Geode* geode = new osg::Geode;
722     geode->addDrawable(SGLightFactory::getLights(tileGeometryBin.taxiLights));
723     taxiLights->addChild(geode);
724     lightGroup->addChild(taxiLights);
725   }
726
727   // The toplevel transform for that tile.
728   osg::MatrixTransform* transform = new osg::MatrixTransform;
729   transform->setName(path);
730   transform->setMatrix(osg::Matrix::translate(center.osg()));
731   transform->addChild(terrainGroup);
732   if (lightGroup->getNumChildren() > 0) {
733     osg::LOD* lightLOD = new osg::LOD;
734     lightLOD->addChild(lightGroup.get(), 0, 30000);
735     unsigned nodeMask = ~0u;
736     nodeMask &= ~SG_NODEMASK_CASTSHADOW_BIT;
737     nodeMask &= ~SG_NODEMASK_RECIEVESHADOW_BIT;
738     nodeMask &= ~SG_NODEMASK_PICK_BIT;
739     nodeMask &= ~SG_NODEMASK_TERRAIN_BIT;
740     lightLOD->setNodeMask(nodeMask);
741     transform->addChild(lightLOD);
742   }
743   
744   if (randomObjects.valid() || randomForest.valid()) {
745   
746     // Add a LoD node, so we don't try to display anything when the tile center
747     // is more than 20km away.
748     osg::LOD* objectLOD = new osg::LOD;
749     
750     if (randomObjects.valid()) objectLOD->addChild(randomObjects.get(), 0, 20000);
751     if (randomForest.valid())  objectLOD->addChild(randomForest.get(), 0, 20000);
752     
753     unsigned nodeMask = SG_NODEMASK_CASTSHADOW_BIT | SG_NODEMASK_RECIEVESHADOW_BIT;
754     objectLOD->setNodeMask(nodeMask);
755     transform->addChild(objectLOD);
756   }
757   
758   return transform;
759 }