]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
Updates to how we structure runway lighting in the scene graph so we can get
[flightgear.git] / src / Scenery / tileentry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  Curtis L. Olson  - curt@flightgear.org
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29
30 #include <simgear/bucket/newbucket.hxx>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/math/sg_random.h>
34 #include <simgear/misc/sgstream.hxx>
35
36 #include <Aircraft/aircraft.hxx>
37 #include <Include/general.hxx>
38 #include <Main/globals.hxx>
39 #include <Main/viewer.hxx>
40 #include <Scenery/scenery.hxx>
41 #include <Time/light.hxx>
42 #include <Objects/apt_signs.hxx>
43 #include <Objects/matlib.hxx>
44 #include <Objects/newmat.hxx>
45 #include <Objects/obj.hxx>
46
47 #include "tileentry.hxx"
48 #include "tilemgr.hxx"
49
50
51 // Constructor
52 FGTileEntry::FGTileEntry ( const SGBucket& b )
53     : ncount( 0 ),
54       center( Point3D( 0.0 ) ),
55       tile_bucket( b ),
56       terra_transform( new ssgTransform ),
57       rwy_lights_transform( new ssgTransform ),
58       terra_range( new ssgRangeSelector ),
59       loaded(false),
60       pending_models(0),
61       free_tracker(0)
62 {
63     nodes.clear();
64
65     // update the contents
66     // if ( vec3_ptrs.size() || vec2_ptrs.size() || index_ptrs.size() ) {
67     //     SG_LOG( SG_TERRAIN, SG_ALERT, 
68     //             "Attempting to overwrite existing or"
69     //             << " not properly freed leaf data." );
70     //     exit(-1);
71     // }
72 }
73
74
75 // Destructor
76 FGTileEntry::~FGTileEntry () {
77     // cout << "nodes = " << nodes.size() << endl;;
78     // delete[] nodes;
79 }
80
81
82 #if 0
83 // Please keep this for reference.  We use Norman's optimized routine,
84 // but here is what the routine really is doing.
85 void
86 FGTileEntry::WorldCoordinate( sgCoord *obj_pos, Point3D center,
87                               double lat, double lon, double elev, double hdg)
88 {
89     // setup transforms
90     Point3D geod( lon * SGD_DEGREES_TO_RADIANS,
91                   lat * SGD_DEGREES_TO_RADIANS,
92                   elev );
93         
94     Point3D world_pos = sgGeodToCart( geod );
95     Point3D offset = world_pos - center;
96         
97     sgMat4 POS;
98     sgMakeTransMat4( POS, offset.x(), offset.y(), offset.z() );
99
100     sgVec3 obj_rt, obj_up;
101     sgSetVec3( obj_rt, 0.0, 1.0, 0.0); // Y axis
102     sgSetVec3( obj_up, 0.0, 0.0, 1.0); // Z axis
103
104     sgMat4 ROT_lon, ROT_lat, ROT_hdg;
105     sgMakeRotMat4( ROT_lon, lon, obj_up );
106     sgMakeRotMat4( ROT_lat, 90 - lat, obj_rt );
107     sgMakeRotMat4( ROT_hdg, hdg, obj_up );
108
109     sgMat4 TUX;
110     sgCopyMat4( TUX, ROT_hdg );
111     sgPostMultMat4( TUX, ROT_lat );
112     sgPostMultMat4( TUX, ROT_lon );
113     sgPostMultMat4( TUX, POS );
114
115     sgSetCoord( obj_pos, TUX );
116 }
117 #endif
118
119
120 // Norman's 'fast hack' for above
121 static void WorldCoordinate( sgCoord *obj_pos, Point3D center, double lat,
122                              double lon, double elev, double hdg )
123 {
124     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
125     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
126     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
127
128     // setup transforms
129     Point3D geod( lon_rad, lat_rad, elev );
130         
131     Point3D world_pos = sgGeodToCart( geod );
132     Point3D offset = world_pos - center;
133
134     sgMat4 mat;
135
136     SGfloat sin_lat = (SGfloat)sin( lat_rad );
137     SGfloat cos_lat = (SGfloat)cos( lat_rad );
138     SGfloat cos_lon = (SGfloat)cos( lon_rad );
139     SGfloat sin_lon = (SGfloat)sin( lon_rad );
140     SGfloat sin_hdg = (SGfloat)sin( hdg_rad ) ;
141     SGfloat cos_hdg = (SGfloat)cos( hdg_rad ) ;
142
143     mat[0][0] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - sin_hdg * (SGfloat)sin_lon;
144     mat[0][1] =  cos_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + sin_hdg * (SGfloat)cos_lon;
145     mat[0][2] = -cos_hdg * (SGfloat)cos_lat;
146     mat[0][3] =  SG_ZERO;
147
148     mat[1][0] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)cos_lon - cos_hdg * (SGfloat)sin_lon;
149     mat[1][1] = -sin_hdg * (SGfloat)sin_lat * (SGfloat)sin_lon + cos_hdg * (SGfloat)cos_lon;
150     mat[1][2] =  sin_hdg * (SGfloat)cos_lat;
151     mat[1][3] =  SG_ZERO;
152
153     mat[2][0] = (SGfloat)cos_lat * (SGfloat)cos_lon;
154     mat[2][1] = (SGfloat)cos_lat * (SGfloat)sin_lon;
155     mat[2][2] = (SGfloat)sin_lat;
156     mat[2][3] =  SG_ZERO;
157
158     mat[3][0] = offset.x();
159     mat[3][1] = offset.y();
160     mat[3][2] = offset.z();
161     mat[3][3] = SG_ONE ;
162
163     sgSetCoord( obj_pos, mat );
164 }
165
166
167 // recurse an ssg tree and call removeKid() on every node from the
168 // bottom up.  Leaves the original branch in existance, but empty so
169 // it can be removed by the calling routine.
170 static void my_remove_branch( ssgBranch * branch ) {
171     for ( ssgEntity *k = branch->getKid( 0 );
172           k != NULL; 
173           k = branch->getNextKid() )
174     {
175         if ( k -> isAKindOf ( ssgTypeBranch() ) ) {
176             my_remove_branch( (ssgBranch *)k );
177             branch -> removeKid ( k );
178         } else if ( k -> isAKindOf ( ssgTypeLeaf() ) ) {
179             branch -> removeKid ( k ) ;
180         }
181     }
182 }
183
184 // ADA
185 #define TEXRES_X 256
186 #define TEXRES_Y 256
187 unsigned char env_map[TEXRES_X][TEXRES_Y][4];
188 // SetColor & SetColor2 functions were provided by Christian Mayer (26 April 2001) - used without change
189 void setColor(float x, float y, float z, float angular_size, float r,
190 float g, float b, float a)
191 {
192     //normalize
193     float inv_length = 1.0 / sqrt(x*x + y*y + z*z);
194     x *= inv_length; y *= inv_length; z *= inv_length;
195   
196     float cos_angular_size = cos(angular_size*SG_DEGREES_TO_RADIANS);
197
198     for( int s = 0; s < TEXRES_X; s++) {
199         for( int t = 0; t < TEXRES_Y; t++) {
200
201             float s_2 = (float)s/TEXRES_X - 0.5; // centre of texture 0,0
202             float t_2 = (float)t/TEXRES_Y - 0.5; // elev
203
204             float rx, ry, rz;
205
206             if ((1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2) >= 0.0) {
207                 // sphere
208                 float m = 4.0 * sqrt(1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2);
209                 rx = m * s_2;
210                 ry = m * t_2;
211                 rz = m*m / 8.0 - 1.0;
212             } else {
213                 // singularity
214                 rx = 0.0;
215                 ry = 0.0;
216                 rz = -1.0;
217             }
218
219             float tx = rx;  //mirroring on the z=0 plane
220             float ty = ry;  //assumes that the normal is allways
221             float tz = -rz; //n(0.0, 0.0, 1.0)
222          
223             if ( cos_angular_size < (x*tx + y*ty + z*tz) ) {
224                 env_map[s][t][0] = (unsigned char) r * 255;  
225                 env_map[s][t][1] = (unsigned char) g * 255;
226                 env_map[s][t][2] = (unsigned char) b * 255;
227                 env_map[s][t][3] = (unsigned char) a * 255;
228             }
229         }
230     }
231 }
232
233 // elevation_size, float azimuth_size are the *total* angular size of the light
234 void setColor2(float elevation_size,float azimuth_size, float r, float g, float b, float a)
235 {
236     for( int s = 0; s < TEXRES_X; s++) {
237         for( int t = 0; t < TEXRES_Y; t++) {
238             float s_2 = (float)s/TEXRES_X - 0.5;
239             float t_2 = (float)t/TEXRES_Y - 0.5;
240
241             float rx, ry, rz;
242
243             if ((1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2) >= 0.0) {
244
245                 float m = 4.0 * sqrt(1.0 - 4.0*s_2*s_2 - 4.0*t_2*t_2);
246                 rx = m * s_2;
247                 ry = m * t_2;
248                 rz = m*m / 8.0 - 1.0;
249             } else {
250                 rx = 0.0;
251                 ry = 0.0;
252                 rz = -1.0;
253             }
254
255             float tx = rx;  //mirroring on the z=0 plane to reverse
256             float ty = ry;  //OpenGLs automatic mirroring
257             float tz = -rz; 
258
259             //get elevation => project t onto the x-z-plane
260             float tz_proj1 = tz / sqrt(tx*tx + tz*tz);
261             float televation = acos( -tz_proj1 ) * SG_RADIANS_TO_DEGREES;
262
263             //get azi => project t onto the y-z-plane
264             float tz_proj2 = tz / sqrt(ty*ty + tz*tz);
265             float tazimuth = acos( -tz_proj2 ) * SG_RADIANS_TO_DEGREES;
266
267             //note televation and tazimuth are the angles *between* the
268             //temporary vector and the normal (0,0,-1). They are *NOT*
269             //the elevation and azimuth angles
270
271             //square:
272             //if (((elevation_size > televation) || (elevation_size < -televation)) &&
273             //    ((azimuth_size   > tazimuth  ) || (azimuth_size   < -tazimuth  ))) 
274             //elliptical
275             if (((televation*televation) / (elevation_size*elevation_size / 4.0) +
276                  (tazimuth  *tazimuth  ) / (azimuth_size  *azimuth_size   / 4.0)) <= 1.0)
277             {
278                 env_map[s][t][0] = (unsigned char) r * 255;  
279                 env_map[s][t][1] = (unsigned char) g * 255;
280                 env_map[s][t][2] = (unsigned char) b * 255;
281                 env_map[s][t][3] = (unsigned char) a * 255;
282             }
283         }
284     }
285 }
286
287 // 23 March 2001
288 // This function performs billboarding of polygons drawn using the UP and RIGHT vectors obtained
289 // from the transpose of the MODEL_VIEW_MATRIX of the ssg_current_context. Each polygon is drawn
290 // at the coordinate array and material state as passed thro arguments.
291 void *fgBillboard( ssgBranch *lightmaps, ssgVertexArray *light_maps, ssgSimpleState *lightmap_state, float size) {
292     sgMat4 tmat;
293     sgVec3 rt, up, nrt, nup, pt, quads[4], lmaps[4];
294
295     ssgGetModelviewMatrix ( tmat );
296     sgSetVec3 (rt, tmat[0][0], tmat[1][0], tmat[2][0]);
297     sgSetVec3 (up, tmat[0][1], tmat[1][1], tmat[2][1]);
298     sgSetVec3 (nrt, tmat[0][0], tmat[1][0], tmat[2][0]);
299     sgSetVec3 (nup, tmat[0][1], tmat[1][1], tmat[2][1]);
300     sgNegateVec3 (nrt);
301     sgNegateVec3 (nup);
302
303     sgAddVec3 (quads[0], nrt, nup);
304     sgAddVec3 (quads[1],  rt, nup);
305     sgAddVec3 (quads[2],  rt,  up);
306     sgAddVec3 (quads[3], nrt,  up);
307
308     sgScaleVec3 (quads[0], size);
309     sgScaleVec3 (quads[1], size);
310     sgScaleVec3 (quads[2], size);
311     sgScaleVec3 (quads[3], size);
312
313     sgVec4 color;
314     sgSetVec4( color, 1.0, 1.0, 0.0, 1.0 );
315
316     sgVec2 texcoords[4];
317     sgSetVec2( texcoords[0], 1.0, 1.0 );
318     sgSetVec2( texcoords[1], 0.0, 1.0 );
319     sgSetVec2( texcoords[2], 0.0, 0.0 );
320     sgSetVec2( texcoords[3], 1.0, 0.0 );
321     
322     for (int j = 0; j < 4; j++ ) {
323         sgCopyVec3(lmaps[j]     ,quads[j]);
324     }
325
326     for ( int i = 0; i < light_maps->getNum(); ++i ) {
327         // Allocate ssg structure
328         ssgVertexArray   *vl = new ssgVertexArray( 1 );
329         ssgTexCoordArray *tl = new ssgTexCoordArray( 1 );
330         ssgColourArray   *cl = new ssgColourArray( 1 );
331
332         float *temp = light_maps->get(i);
333         sgSetVec3(pt,temp[0],temp[1],temp[2]);
334
335         for (int k=0; k<4; k++) {
336             sgAddVec3( quads[k],lmaps[k], pt );                 
337             vl->add(quads[k]);
338             tl->add(texcoords[k]);
339             cl->add(color);
340         }
341
342         ssgLeaf *leaf = NULL;
343         leaf = new ssgVtxTable ( GL_TRIANGLE_FAN, vl, NULL, tl, cl );
344         leaf->setState( lightmap_state );
345         lightmaps->addKid( leaf );
346     }
347
348     return NULL;
349 }
350
351 ssgBranch* FGTileEntry::gen_runway_lights( ssgVertexArray *points,ssgVertexArray *normal,
352                                            ssgVertexArray *dir, int type[]) 
353 {
354
355     //************** HARD CODED RUNWAY LIGHT TEXTURES BEGIN ************************    
356     GLuint texEdge, texTaxi, texTouchdown;
357     GLuint texThreshold;
358     GLuint texVasi, texWhite, texRed, texGreen, texYellow;
359
360     //VASI lights
361     setColor(0.0,0.0,1.0,360.0, 0, 0, 0, 0);
362     setColor2(10.0, 40.0, 1, 1, 1, 1);
363     setColor2(6.0, 40.0, 1, 0.5, 0.5, 1);
364     setColor2(5.0, 40.0, 1, 0, 0, 1);
365     glGenTextures(1, &texVasi);
366     glBindTexture(GL_TEXTURE_2D, texVasi);
367     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
368     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
369     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
370     ssgSimpleState *vasi_state;
371     vasi_state = new ssgSimpleState();
372     vasi_state->ref();
373     vasi_state->setTexture( texVasi );
374     vasi_state->disable( GL_LIGHTING );
375     vasi_state->enable( GL_TEXTURE_2D );
376     vasi_state->setShadeModel( GL_SMOOTH );
377
378     //EDGE
379     setColor(0.0,0.0,-1.0,180.0, 1, 1, 0.5, 1);
380     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
381     glGenTextures(1, &texEdge);
382     glBindTexture(GL_TEXTURE_2D, texEdge);
383     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
384     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
385     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
386     ssgSimpleState *edge_state;
387     edge_state = new ssgSimpleState();
388     edge_state->ref();
389     edge_state->setTexture( texEdge );
390     edge_state->disable( GL_LIGHTING );
391     edge_state->enable( GL_TEXTURE_2D );
392     edge_state->setShadeModel( GL_SMOOTH );
393
394     //TOUCHDOWN
395     setColor(0.0,0.0,-1.0,180.0, 0, 1, 0, 1);
396     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
397     glGenTextures(1, &texTouchdown);
398     glBindTexture(GL_TEXTURE_2D, texTouchdown);
399     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
400     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
401     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
402     ssgSimpleState *touchdown_state;
403     touchdown_state = new ssgSimpleState();
404     touchdown_state->ref();
405     touchdown_state->setTexture( texTouchdown );
406     touchdown_state->disable( GL_LIGHTING );
407     touchdown_state->enable( GL_TEXTURE_2D );
408     touchdown_state->setShadeModel( GL_SMOOTH );
409         
410     //THRESHOLD
411     setColor(0.0,0.0,-1.0,180.0, 1, 0, 0, 1);
412     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
413     glGenTextures(1, &texThreshold);
414     glBindTexture(GL_TEXTURE_2D, texThreshold);
415     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
416     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
417     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
418     ssgSimpleState *threshold_state;
419     threshold_state = new ssgSimpleState();
420     threshold_state->ref();
421     threshold_state->setTexture( texThreshold );
422     threshold_state->disable( GL_LIGHTING );
423     threshold_state->enable( GL_TEXTURE_2D );
424     threshold_state->setShadeModel( GL_SMOOTH );
425
426     //TAXI
427     setColor(0.0,0.0,-1.0,180.0, 0, 0, 1, 1);
428     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
429     glGenTextures(1, &texTaxi);
430     glBindTexture(GL_TEXTURE_2D, texTaxi);
431     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
432     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
433     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
434     ssgSimpleState *taxi_state;
435     taxi_state = new ssgSimpleState();
436     taxi_state->ref();
437     taxi_state->setTexture( texTaxi );
438     taxi_state->disable( GL_LIGHTING );
439     taxi_state->enable( GL_TEXTURE_2D );
440     taxi_state->setShadeModel( GL_SMOOTH );
441
442     //WHITE
443     setColor(0.0,0.0,-1.0,180.0, 1, 1, 1, 1);
444     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
445     glGenTextures(1, &texWhite);
446     glBindTexture(GL_TEXTURE_2D, texWhite);
447     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
448     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
449     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
450     ssgSimpleState *white_state;
451     white_state = new ssgSimpleState();
452     white_state->ref();
453     white_state->setTexture( texWhite );
454     white_state->disable( GL_LIGHTING );
455     white_state->enable( GL_TEXTURE_2D );
456     white_state->setShadeModel( GL_SMOOTH );
457
458     //RED
459     setColor(0.0,0.0,-1.0,180.0, 1, 0, 0, 1);
460     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
461     glGenTextures(1, &texRed);
462     glBindTexture(GL_TEXTURE_2D, texRed);
463     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
464     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
465     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
466     ssgSimpleState *red_state;
467     red_state = new ssgSimpleState();
468     red_state->ref();
469     red_state->setTexture( texRed );
470     red_state->disable( GL_LIGHTING );
471     red_state->enable( GL_TEXTURE_2D );
472     red_state->setShadeModel( GL_SMOOTH );
473
474     //GREEN
475     setColor(0.0,0.0,-1.0,180.0, 0, 1, 0, 1);
476     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
477     glGenTextures(1, &texGreen);
478     glBindTexture(GL_TEXTURE_2D, texGreen);
479     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
480     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
481     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
482     ssgSimpleState *green_state;
483     green_state = new ssgSimpleState();
484     green_state->ref();
485     green_state->setTexture( texGreen );
486     green_state->disable( GL_LIGHTING );
487     green_state->enable( GL_TEXTURE_2D );
488     green_state->setShadeModel( GL_SMOOTH );
489
490     //YELLOW
491     setColor(0.0,0.0,-1.0,180.0, 1, 1, 0, 1);
492     glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
493     glGenTextures(1, &texYellow);
494     glBindTexture(GL_TEXTURE_2D, texYellow);
495     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
496     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
497     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, TEXRES_X, TEXRES_Y, 0, GL_RGBA, GL_UNSIGNED_BYTE, env_map);
498     ssgSimpleState *yellow_state;
499     yellow_state = new ssgSimpleState();
500     yellow_state->ref();
501     yellow_state->setTexture( texYellow );
502     yellow_state->disable( GL_LIGHTING );
503     yellow_state->enable( GL_TEXTURE_2D );
504     yellow_state->setShadeModel( GL_SMOOTH );
505 //************** HARD CODED RUNWAY LIGHT TEXTURES END ************************    
506
507     ssgBranch *runway_lights = new ssgBranch;
508     sgVec3 v2,v3,inf,side;
509
510     ssgLeaf *leaf1 = NULL;
511     ssgLeaf *leaf2 = NULL;
512     ssgLeaf *leaf7 = NULL;
513     ssgLeaf *leaf8 = NULL;
514     ssgLeaf *leaf9 = NULL;
515
516     ssgVertexArray   *vlw = new ssgVertexArray( 1 );
517     ssgNormalArray   *nlw = new ssgNormalArray( 1 );
518     ssgVertexArray   *vlt = new ssgVertexArray( 1 );
519     ssgNormalArray   *nlt = new ssgNormalArray( 1 );
520     ssgVertexArray   *vlr = new ssgVertexArray( 1 );
521     ssgNormalArray   *nlr = new ssgNormalArray( 1 );
522     ssgVertexArray   *vlg = new ssgVertexArray( 1 );
523     ssgNormalArray   *nlg = new ssgNormalArray( 1 );
524     ssgVertexArray   *vly = new ssgVertexArray( 1 );
525     ssgNormalArray   *nly = new ssgNormalArray( 1 );
526
527     for ( int i = 0; i < points->getNum()-1; i=i++ ) {
528
529         // Allocate ssg structure
530         ssgVertexArray   *vl = new ssgVertexArray( 1 );
531         ssgNormalArray   *nl = new ssgNormalArray( 1 );
532         ssgVertexArray   *vl1 = new ssgVertexArray( 1 );
533         ssgNormalArray   *nl1 = new ssgNormalArray( 1 );
534
535         float *n1 = normal->get(i);
536         float *d1 = dir->get(i);
537
538         /* TEMPORARY CODE BEGIN 
539            // calculate normal using 1st, 2nd & last vertices of the group
540            sgVec3 n1;
541            sgMakeNormal (n1, points->get(0), points->get(1), points->get(points->getNum()-1) );
542            sgVec3 d1;
543            sgSubVec3(d1,points->get(1),points->get(0));
544            printf("%f %f %f\n",n1[0],n1[1],n1[2]);
545            printf("%f %f %f\n",d1[0],d1[1],d1[2]);
546            type[i] = 2;
547            ----TEMPORARY CODE END */
548
549
550         sgNormaliseVec3 ( n1 );
551         sgNormaliseVec3 ( d1 );
552         sgVec3 d2;
553         d2[0] = -d1[0];
554         d2[1] = -d1[1];
555         d2[2] = -d1[2];
556
557         sgVectorProductVec3(side,n1,d1);
558         sgScaleVec3 (inf,n1,-50);
559         sgScaleVec3 (side,5);
560
561         float *v1 = points->get(i);
562         sgAddVec3(v2,v1,inf);
563         sgAddVec3(v3,v2,side);
564
565         if ( type[i] == 1) {        //POINT,WHITE
566
567             vlw->add(v1);
568             nlw->add(d1);
569
570         } else if (type[i] == 2) {  //POINT,TAXI
571
572             vlt->add(v1);
573             nlt->add(d1);
574
575         } else if (type[i] == 3) {  //SINGLE POLYGON,VASI
576
577             vl->add(v1);
578             nl->add(d1);
579             vl->add(v3);
580             nl->add(d1);
581             vl->add(v2);
582             nl->add(d1);
583
584             ssgLeaf *leaf3 = NULL;
585             leaf3 = new ssgVtxTable ( GL_POLYGON, vl, nl, NULL, NULL );
586             leaf3->setState( vasi_state );
587             runway_lights->addKid( leaf3 );
588
589         } else if (type[i] == 4) {  //BACK-TO-BACK POLYGONS,TOUCHDOWN/THRESHOLD
590                 
591             vl->add(v1);
592             nl->add(d1);
593             vl->add(v3);
594             nl->add(d1);
595             vl->add(v2);
596             nl->add(d1);
597
598             vl1->add(v3);
599             nl1->add(d2);
600             vl1->add(v1);
601             nl1->add(d2);
602             vl1->add(v2);
603             nl1->add(d2);
604
605             ssgLeaf *leaf41 = NULL;
606             leaf41 = new ssgVtxTable ( GL_POLYGON, vl, nl, NULL, NULL );
607             leaf41->setState( touchdown_state );
608             runway_lights->addKid( leaf41 );
609
610             ssgLeaf *leaf42 = NULL;
611             leaf42 = new ssgVtxTable ( GL_POLYGON, vl1, nl1, NULL, NULL );
612             leaf42->setState( threshold_state );
613             runway_lights->addKid( leaf42 );
614
615         } else if ( type[i] == 5) {        //POINT,WHITE, SEQUENCE LIGHTS (RABBIT)
616
617             vl->add(v1);
618             nl->add(d1);
619             ssgLeaf *leaf5 = NULL;
620             leaf5 = new ssgVtxTable ( GL_POINTS, vl, nl, NULL, NULL );
621             leaf5->setState( white_state );
622             lightmaps_sequence->addKid (leaf5);
623
624         } else if ( type[i] == 6) {        //POINT,WHITE, SEQUENCE LIGHTS (RABBIT)
625
626             vl->add(v1);
627             nl->add(d1);
628             ssgLeaf *leaf6 = NULL;
629             leaf6 = new ssgVtxTable ( GL_POINTS, vl, nl, NULL, NULL );
630             leaf6->setState( yellow_state );
631             ols_transform->addKid (leaf6);
632             // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
633             //                  lightmaps_sequence->addKid (leaf6);
634             // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
635
636         } else if (type[i] == 7) {  //POINT,RED
637
638             vlr->add(v1);
639             nlr->add(d1);
640
641         } else if (type[i] == 8) {  //POINT,GREEN
642
643             vlg->add(v1);
644             nlg->add(d1);
645
646         } else if (type[i] == 9) {  //POINT,YELLOW
647
648             vly->add(v1);
649             nly->add(d1);
650
651         }
652
653     }
654
655     leaf1 = new ssgVtxTable ( GL_POINTS, vlw, nlw, NULL, NULL );
656     leaf1->setState( white_state );
657     runway_lights->addKid( leaf1 );
658
659     leaf2 = new ssgVtxTable ( GL_POINTS, vlt, nlt, NULL, NULL );
660     leaf2->setState( taxi_state );
661     runway_lights->addKid( leaf2 );
662         
663     leaf7 = new ssgVtxTable ( GL_POINTS, vlr, nlr, NULL, NULL );
664     leaf7->setState( red_state );
665     runway_lights->addKid( leaf7 );
666
667     leaf8 = new ssgVtxTable ( GL_POINTS, vlg, nlg, NULL, NULL );
668     leaf8->setState( green_state );
669     // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
670     ols_transform->ref();
671     lightmaps_sequence->addKid (ols_transform);
672     // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
673     lightmaps_sequence->addKid (leaf8);
674
675     leaf9 = new ssgVtxTable ( GL_POINTS, vly, nly, NULL, NULL );
676     leaf9->setState( yellow_state );
677     runway_lights->addKid( leaf9 );
678
679     lightmaps_sequence->select(0xFFFFFF);       
680     return runway_lights;
681 }
682 // ADA
683         
684
685 // Free "n" leaf elements of an ssg tree.  returns the number of
686 // elements freed.  An empty branch node is considered a leaf.  This
687 // is intended to spread the load of freeing a complex tile out over
688 // several frames.
689 static int fgPartialFreeSSGtree( ssgBranch *b, int n ) {
690     // ssgDeRefDelete( b );
691     // return 0;
692
693     int num_deletes = 0;
694
695     if ( n > 0 ) {
696         // we still have some delete budget left
697         for ( int i = 0; i < b->getNumKids(); ++i ) {
698             ssgEntity *kid = b->getKid(i);
699             if ( kid->isAKindOf( ssgTypeBranch() ) && kid->getRef() <= 1 ) {
700                 int result = fgPartialFreeSSGtree( (ssgBranch *)kid, n );
701                 num_deletes += result;
702                 n -= result;
703                 if ( n < 0 ) {
704                     break;
705                 }
706             }
707             // remove the kid if it is now empty
708             if ( kid->getNumKids() == 0 ) {
709                 b->removeKid( kid );
710                 num_deletes++;
711                 n--;
712             }
713         }
714     }
715
716     return num_deletes;
717 }
718
719
720 // Clean up the memory used by this tile and delete the arrays used by
721 // ssg as well as the whole ssg branch
722 bool FGTileEntry::free_tile() {
723     int i;
724     int delete_size = 100;
725     SG_LOG( SG_TERRAIN, SG_DEBUG,
726             "FREEING TILE = (" << tile_bucket << ")" );
727
728     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
729     
730     if ( !(free_tracker & NODES) ) {
731         SG_LOG( SG_TERRAIN, SG_DEBUG,
732                 "  deleting " << nodes.size() << " nodes" );
733         nodes.clear();
734
735         free_tracker |= NODES;
736     } else if ( !(free_tracker & VEC_PTRS) ) {
737         // delete the vector pointers
738         SG_LOG( SG_TERRAIN, SG_DEBUG,
739                 "  deleting (leaf data) vertex, normal, and "
740                 << " texture coordinate arrays" );
741
742         for ( i = 0; i < (int)vec3_ptrs.size(); ++i ) {
743             delete [] vec3_ptrs[i];
744         }
745         vec3_ptrs.clear();
746
747         for ( i = 0; i < (int)vec2_ptrs.size(); ++i ) {
748             delete [] vec2_ptrs[i];
749         }
750         vec2_ptrs.clear();
751
752         for ( i = 0; i < (int)index_ptrs.size(); ++i ) {
753             delete index_ptrs[i];
754         }
755         index_ptrs.clear();
756
757         free_tracker |= VEC_PTRS;
758     } else if ( !(free_tracker & TERRA_NODE) ) {
759         // delete the terrain branch (this should already have been
760         // disconnected from the scene graph)
761         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
762         if ( fgPartialFreeSSGtree( terra_transform, delete_size ) == 0 ) {
763             ssgDeRefDelete( terra_transform );
764             free_tracker |= TERRA_NODE;
765         }
766     } else if ( !(free_tracker & GROUND_LIGHTS) && gnd_lights_transform ) {
767         // delete the terrain lighting branch (this should already have been
768         // disconnected from the scene graph)
769         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING gnd_lights_transform" );
770         if ( fgPartialFreeSSGtree( gnd_lights_transform, delete_size ) == 0 ) {
771             ssgDeRefDelete( gnd_lights_transform );
772             free_tracker |= GROUND_LIGHTS;
773         }
774     } else if ( !(free_tracker & RWY_LIGHTS) && rwy_lights_transform ) {
775         // delete the terrain lighting branch (this should already have been
776         // disconnected from the scene graph)
777         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING rwy_lights_transform" );
778         if ( fgPartialFreeSSGtree( rwy_lights_transform, delete_size ) == 0 ) {
779             ssgDeRefDelete( rwy_lights_transform );
780             free_tracker |= RWY_LIGHTS;
781         }
782     } else if ( !(free_tracker & LIGHTMAPS) && lightmaps_transform ) {
783         // ADA
784         // delete the terrain lighting branch (this should already have been
785         // disconnected from the scene graph)
786         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING lightmaps_transform" );
787         if ( fgPartialFreeSSGtree( lightmaps_transform, delete_size ) == 0 ) {
788             ssgDeRefDelete( lightmaps_transform );
789             free_tracker |= LIGHTMAPS;
790         }
791     } else {
792         return true;
793     }
794
795     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
796
797     // if we fall down to here, we still have work todo, return false
798     return false;
799 }
800
801
802 // Update the ssg transform node for this tile so it can be
803 // properly drawn relative to our (0,0,0) point
804 void FGTileEntry::prep_ssg_node( const Point3D& p, sgVec3 up, float vis) {
805     if ( !loaded ) return;
806
807     SetOffset( p );
808
809     terra_range->setRange( 0, SG_ZERO );
810     terra_range->setRange( 1, vis + bounding_radius );
811     if ( gnd_lights_range ) {
812         gnd_lights_range->setRange( 0, SG_ZERO );
813         gnd_lights_range->setRange( 1, vis * 1.5 + bounding_radius );
814     }
815
816     sgVec3 sgTrans;
817     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
818     terra_transform->setTransform( sgTrans );
819
820     if ( gnd_lights_transform ) {
821         // we need to lift the lights above the terrain to avoid
822         // z-buffer fighting.  We do this based on our altitude and
823         // the distance this tile is away from scenery center.
824
825         // we expect 'up' to be a unit vector coming in, but since we
826         // modify the value of lift_vec, we need to create a local
827         // copy.
828         sgVec3 lift_vec;
829         sgCopyVec3( lift_vec, up );
830
831         double agl;
832         agl = globals->get_current_view()->getAltitudeASL_ft()
833             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
834
835         // sgTrans just happens to be the
836         // vector from scenery center to the center of this tile which
837         // is what we want to calculate the distance of
838         sgVec3 to;
839         sgCopyVec3( to, sgTrans );
840         double dist = sgLengthVec3( to );
841
842         if ( general.get_glDepthBits() > 16 ) {
843             sgScaleVec3( lift_vec, 10.0 + agl / 100.0 + dist / 10000 );
844         } else {
845             sgScaleVec3( lift_vec, 10.0 + agl / 20.0 + dist / 5000 );
846         }
847
848         sgVec3 lt_trans;
849         sgCopyVec3( lt_trans, sgTrans );
850
851         sgAddVec3( lt_trans, lift_vec );
852         gnd_lights_transform->setTransform( lt_trans );
853
854         // select which set of lights based on sun angle
855         float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
856         if ( sun_angle > 95 ) {
857             gnd_lights_brightness->select(0x04);
858         } else if ( sun_angle > 92 ) {
859             gnd_lights_brightness->select(0x02);
860         } else if ( sun_angle > 89 ) {
861             gnd_lights_brightness->select(0x01);
862         } else {
863             gnd_lights_brightness->select(0x00);
864         }
865     }
866
867     if ( rwy_lights_transform ) {
868         // we need to lift the lights above the terrain to avoid
869         // z-buffer fighting.  We do this based on our altitude and
870         // the distance this tile is away from scenery center.
871
872         sgVec3 lift_vec;
873         sgCopyVec3( lift_vec, up );
874
875         double agl;
876         agl = globals->get_current_view()->getAltitudeASL_ft()
877             * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
878
879         // sgTrans just happens to be the
880         // vector from scenery center to the center of this tile which
881         // is what we want to calculate the distance of
882         sgVec3 to;
883         sgCopyVec3( to, sgTrans );
884         double dist = sgLengthVec3( to );
885
886         if ( general.get_glDepthBits() > 16 ) {
887             sgScaleVec3( lift_vec, 0.0 + agl / 500.0 + dist / 10000 );
888         } else {
889             sgScaleVec3( lift_vec, 1.0 + agl / 20.0 + dist / 5000 );
890         }
891
892         sgVec3 lt_trans;
893         sgCopyVec3( lt_trans, sgTrans );
894
895         sgAddVec3( lt_trans, lift_vec );
896         rwy_lights_transform->setTransform( lt_trans );
897
898         // select which set of lights based on sun angle
899         // float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
900         // if ( sun_angle > 95 ) {
901         //     gnd_lights_brightness->select(0x04);
902         // } else if ( sun_angle > 92 ) {
903         //     gnd_lights_brightness->select(0x02);
904         // } else if ( sun_angle > 89 ) {
905         //     gnd_lights_brightness->select(0x01);
906         // } else {
907         //     gnd_lights_brightness->select(0x00);
908         // }
909     }
910
911     // ADA
912     // Transform & Render runway lights - 23 Mar 2001
913     sgSetVec3( sgTrans, offset.x(), offset.y(), offset.z() );
914     if ( lightmaps_transform ) {
915         static unsigned int selectnode = 0;
916         // Run-time extension check.
917         if (!glutExtensionSupported("GL_EXT_point_parameters")) {
918             //use lightmaps on billboarded polygons
919         } else {
920             // using GL_EXT_point_parameters
921                 
922             // This part is same as ground-lights code above by Curt
923             sgVec3 lift_vec;
924             sgCopyVec3( lift_vec, up );
925             
926             double agl1;
927             agl1 = globals->get_current_view()->getAltitudeASL_ft()
928                 * SG_FEET_TO_METER - globals->get_scenery()->get_cur_elev();
929
930             // sgTrans just happens to be the
931             // vector from scenery center to the center of this tile which
932             // is what we want to calculate the distance of
933             sgVec3 to1;
934             sgCopyVec3( to1, sgTrans );
935             double dist1 = sgLengthVec3( to1 );
936
937             if ( general.get_glDepthBits() > 16 ) {
938                 sgScaleVec3( lift_vec, 0.0 + agl1 / 2000.0 + dist1 / 10000 );
939             } else {
940                 sgScaleVec3( lift_vec, 0.0 + agl1 / 20.0 + dist1 / 5000 );
941             }
942             sgAddVec3( sgTrans, lift_vec );
943             lightmaps_transform->setTransform( sgTrans );
944
945             float sun_angle1 = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
946             if ( (sun_angle1 > 89) ) {
947                 lightmaps_brightness->select(0x01);
948                 selectnode *=2;
949                 selectnode = selectnode | 0x000001;
950                 if (selectnode > 0xFFFFFF) selectnode = 1;
951                 lightmaps_sequence->select(selectnode);
952             } else {
953                 lightmaps_brightness->select(0x00);
954                 lightmaps_sequence->select(0x000000);
955             } 
956         } // end of GL_EXT_point_parameters section
957
958     } // end of runway lights section
959     // ADA
960
961 }
962
963
964 // Set up lights rendering call backs
965 static int fgLightsPredraw( ssgEntity *e ) {
966 #if 0
967 #ifdef GL_EXT_point_parameters
968     if (glutExtensionSupported("GL_EXT_point_parameters")) {
969         static float quadratic[3] = {1.0, 0.01, 0.0001};
970         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
971         glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0); 
972         glPointSize(4.0);
973     }
974 #endif
975 #endif
976     return true;
977 }
978
979 static int fgLightsPostdraw( ssgEntity *e ) {
980 #if 0
981 #ifdef GL_EXT_point_parameters
982     if (glutExtensionSupported("GL_EXT_point_parameters")) {
983         static float default_attenuation[3] = {1.0, 0.0, 0.0};
984         glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
985                               default_attenuation);
986         glPointSize(1.0);
987     }
988 #endif
989 #endif
990     return true;
991 }
992
993
994 ssgLeaf* FGTileEntry::gen_lights( ssgVertexArray *lights, int inc, float bright ) {
995     // generate a repeatable random seed
996     float *p1 = lights->get( 0 );
997     unsigned int *seed = (unsigned int *)p1;
998     sg_srandom( *seed );
999
1000     int size = lights->getNum() / inc;
1001
1002     // Allocate ssg structure
1003     ssgVertexArray   *vl = new ssgVertexArray( size + 1 );
1004     ssgNormalArray   *nl = NULL;
1005     ssgTexCoordArray *tl = NULL;
1006     ssgColourArray   *cl = new ssgColourArray( size + 1 );
1007
1008     sgVec4 color;
1009     for ( int i = 0; i < lights->getNum(); ++i ) {
1010         // this loop is slightly less efficient than it otherwise
1011         // could be, but we want a red light to always be red, and a
1012         // yellow light to always be yellow, etc. so we are trying to
1013         // preserve the random sequence.
1014         float zombie = sg_random();
1015         if ( i % inc == 0 ) {
1016             vl->add( lights->get(i) );
1017
1018             // factor = sg_random() ^ 2, range = 0 .. 1 concentrated towards 0
1019             float factor = sg_random();
1020             factor *= factor;
1021
1022             if ( zombie > 0.5 ) {
1023                 // 50% chance of yellowish
1024                 sgSetVec4( color, 0.9, 0.9, 0.3, bright - factor * 0.2 );
1025             } else if ( zombie > 0.15 ) {
1026                 // 35% chance of whitish
1027                 sgSetVec4( color, 0.9, 0.9, 0.8, bright - factor * 0.2 );
1028             } else if ( zombie > 0.05 ) {
1029                 // 10% chance of orangish
1030                 sgSetVec4( color, 0.9, 0.6, 0.2, bright - factor * 0.2 );
1031             } else {
1032                 // 5% chance of redish
1033                 sgSetVec4( color, 0.9, 0.2, 0.2, bright - factor * 0.2 );
1034             }
1035             cl->add( color );
1036         }
1037     }
1038
1039     // create ssg leaf
1040     ssgLeaf *leaf = 
1041         new ssgVtxTable ( GL_POINTS, vl, nl, tl, cl );
1042
1043     // assign state
1044     FGNewMat *newmat = material_lib.find( "GROUND_LIGHTS" );
1045     leaf->setState( newmat->get_state() );
1046     leaf->setCallback( SSG_CALLBACK_PREDRAW, fgLightsPredraw );
1047     leaf->setCallback( SSG_CALLBACK_POSTDRAW, fgLightsPostdraw );
1048
1049     return leaf;
1050 }
1051
1052
1053 bool FGTileEntry::obj_load( const std::string& path,
1054                        ssgBranch* geometry,
1055                        ssgBranch* rwy_lights,
1056                        ssgVertexArray* ground_lights, bool is_base )
1057 {
1058     Point3D c;                  // returned center point
1059     double br;                  // returned bounding radius
1060
1061     // try loading binary format
1062     if ( fgBinObjLoad( path, is_base,
1063                        &c, &br, geometry, rwy_lights, ground_lights ) )
1064     {
1065         if ( is_base ) {
1066             center = c;
1067             bounding_radius = br;
1068         }
1069     } else {
1070         // next try the older ascii format, this is some ugly
1071         // weirdness because the ascii loader is *old* and hasn't been
1072         // updated, but hopefully we can can the ascii format soon.
1073         ssgBranch *tmp = fgAsciiObjLoad( path, this, ground_lights, is_base );
1074         if ( tmp ) {
1075             return (NULL != tmp);
1076         } else {
1077             // default to an ocean tile
1078             if ( fgGenTile( path, tile_bucket, &c, &br, geometry ) ) {
1079                 center = c;
1080                 bounding_radius = br;
1081             } else {
1082                 SG_LOG( SG_TERRAIN, SG_ALERT,
1083                         "Warning: failed to generate ocean tile!" );
1084             }
1085         }
1086     }
1087
1088     return (geometry != NULL);
1089 }
1090
1091
1092 void
1093 FGTileEntry::load( const SGPath& base, bool is_base )
1094 {
1095     SG_LOG( SG_TERRAIN, SG_INFO, "load() base = " << base.str() );
1096
1097     // Generate names for later use
1098     string index_str = tile_bucket.gen_index_str();
1099
1100     SGPath tile_path = base;
1101     tile_path.append( tile_bucket.gen_base_path() );
1102
1103     SGPath basename = tile_path;
1104     basename.append( index_str );
1105     // string path = basename.str();
1106
1107     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << basename.str() );
1108
1109 #define FG_MAX_LIGHTS 1000
1110
1111     // obj_load() will generate ground lighting for us ...
1112     ssgVertexArray *light_pts = new ssgVertexArray( 100 );
1113
1114     // ADA
1115     ssgVertexArray *lights_rway = new ssgVertexArray( 100 );
1116     ssgVertexArray *lights_dir = new ssgVertexArray( 100 );
1117     ssgVertexArray *lights_normal = new ssgVertexArray( 100 );
1118     int lights_type[FG_MAX_LIGHTS];
1119     // ADA
1120
1121     ssgBranch* new_tile = new ssgBranch;
1122
1123     // Check for master .stg (scene terra gear) file
1124     SGPath stg_name = basename;
1125     stg_name.concat( ".stg" );
1126
1127     sg_gzifstream in( stg_name.str() );
1128
1129     if ( in.is_open() ) {
1130         string token, name;
1131
1132         while ( ! in.eof() ) {
1133             in >> token;
1134
1135             if ( token == "OBJECT_BASE" ) {
1136                 in >> name >> ::skipws;
1137                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1138                         << " name = " << name );
1139
1140                 SGPath custom_path = tile_path;
1141                 custom_path.append( name );
1142
1143                 ssgBranch *geometry = new ssgBranch;
1144                 if ( obj_load( custom_path.str(),
1145                                geometry, NULL, light_pts, true ) )
1146                 {
1147                     new_tile -> addKid( geometry );
1148                 } else {
1149                     delete geometry;
1150                 }
1151             } else if ( token == "OBJECT" ) {
1152                 in >> name >> ::skipws;
1153                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1154                         << " name = " << name );
1155
1156                 SGPath custom_path = tile_path;
1157                 custom_path.append( name );
1158
1159                 ssgBranch *geometry = new ssgBranch;
1160                 ssgBranch *rwy_lights = new ssgBranch;
1161                 if ( obj_load( custom_path.str(),
1162                                geometry, rwy_lights, NULL, false ) )
1163                 {
1164                     if ( geometry -> getNumKids() > 0 ) {
1165                         new_tile -> addKid( geometry );
1166                     } else {
1167                         delete geometry;
1168                     }
1169                     if ( rwy_lights -> getNumKids() > 0 ) {
1170                         rwy_lights_transform -> addKid( rwy_lights );
1171                     } else {
1172                         delete rwy_lights;
1173                     }
1174                 } else {
1175                     delete geometry;
1176                     delete rwy_lights;
1177                 }
1178
1179             } else if ( token == "OBJECT_STATIC" ||
1180                         token == "OBJECT_SHARED" ) {
1181                 // load object info
1182                 double lon, lat, elev, hdg;
1183                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1184                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1185                         << " name = " << name 
1186                         << " pos = " << lon << ", " << lat
1187                         << " elevation = " << elev
1188                         << " heading = " << hdg );
1189
1190                 // object loading is deferred to main render thread,
1191                 // but lets figure out the paths right now.
1192                 SGPath custom_path;
1193                 if ( token == "OBJECT_STATIC" )
1194                     custom_path= tile_path;
1195                 custom_path.append( name );
1196
1197                 sgCoord obj_pos;
1198                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1199                 
1200                 ssgTransform *obj_trans = new ssgTransform;
1201                 obj_trans->setTransform( &obj_pos );
1202
1203                 // wire as much of the scene graph together as we can
1204                 new_tile->addKid( obj_trans );
1205
1206                 // bump up the pending models count
1207                 pending_models++;
1208
1209                 // push an entry onto the model load queue
1210                 FGDeferredModel *dm
1211                     = new FGDeferredModel( custom_path.str(), tile_path.str(),
1212                                            this, obj_trans );
1213                 FGTileMgr::model_ready( dm );
1214             } else if ( token == "OBJECT_TAXI_SIGN" ) {
1215                 // load object info
1216                 double lon, lat, elev, hdg;
1217                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1218                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1219                         << " name = " << name 
1220                         << " pos = " << lon << ", " << lat
1221                         << " elevation = " << elev
1222                         << " heading = " << hdg );
1223
1224                 // load the object itself
1225                 SGPath custom_path = tile_path;
1226                 custom_path.append( name );
1227
1228                 sgCoord obj_pos;
1229                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1230
1231                 ssgTransform *obj_trans = new ssgTransform;
1232                 obj_trans->setTransform( &obj_pos );
1233
1234                 ssgBranch *custom_obj
1235                     = gen_taxi_sign( custom_path.str(), name );
1236
1237                 // wire the pieces together
1238                 if ( custom_obj != NULL ) {
1239                     obj_trans -> addKid( custom_obj );
1240                 }
1241                 new_tile->addKid( obj_trans );
1242             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
1243                 // load object info
1244                 double lon, lat, elev, hdg;
1245                 in >> name >> lon >> lat >> elev >> hdg >> ::skipws;
1246                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1247                         << " name = " << name 
1248                         << " pos = " << lon << ", " << lat
1249                         << " elevation = " << elev
1250                         << " heading = " << hdg );
1251
1252                 // load the object itself
1253                 SGPath custom_path = tile_path;
1254                 custom_path.append( name );
1255
1256                 sgCoord obj_pos;
1257                 WorldCoordinate( &obj_pos, center, lat, lon, elev, hdg );
1258
1259                 ssgTransform *obj_trans = new ssgTransform;
1260                 obj_trans->setTransform( &obj_pos );
1261
1262                 ssgBranch *custom_obj
1263                     = gen_runway_sign( custom_path.str(), name );
1264
1265                 // wire the pieces together
1266                 if ( custom_obj != NULL ) {
1267                     obj_trans -> addKid( custom_obj );
1268                 }
1269                 new_tile->addKid( obj_trans );
1270             } else if ( token == "RWY_LIGHTS" ) {
1271                 double lon, lat, hdg, len, width;
1272                 string common, end1, end2;
1273                 in >> lon >> lat >> hdg >> len >> width
1274                    >> common >> end1 >> end2;
1275                 SG_LOG( SG_TERRAIN, SG_INFO, "token = " << token
1276                         << " pos = " << lon << ", " << lat
1277                         << " hdg = " << hdg
1278                         << " size = " << len << ", " << width
1279                         << " codes = " << common << " "
1280                         << end1 << " " << end2 );
1281             } else {
1282                 SG_LOG( SG_TERRAIN, SG_ALERT,
1283                         "Unknown token " << token << " in "
1284                         << stg_name.str() );
1285                 in >> ::skipws;
1286             }
1287         }
1288     } else {
1289         // no .stg file, generate an ocean tile on the fly for this
1290         // area
1291         ssgBranch *geometry = new ssgBranch;
1292         Point3D c;
1293         double br;
1294         if ( fgGenTile( basename.str(), tile_bucket, &c, &br, geometry ) ) {
1295             center = c;
1296             bounding_radius = br;
1297             new_tile -> addKid( geometry );
1298         } else {
1299             delete geometry;
1300             SG_LOG( SG_TERRAIN, SG_ALERT,
1301                     "Warning: failed to generate ocean tile!" );
1302         }
1303     }
1304
1305     if ( new_tile != NULL ) {
1306         terra_range->addKid( new_tile );
1307     }
1308
1309     terra_transform->addKid( terra_range );
1310
1311     // calculate initial tile offset
1312     SetOffset( globals->get_scenery()->get_center() );
1313     sgCoord sgcoord;
1314     sgSetCoord( &sgcoord,
1315                 offset.x(), offset.y(), offset.z(),
1316                 0.0, 0.0, 0.0 );
1317     terra_transform->setTransform( &sgcoord );
1318     // terrain->addKid( terra_transform );
1319
1320     // Add ground lights to scene graph if any exist
1321     gnd_lights_transform = NULL;
1322     gnd_lights_range = NULL;
1323     if ( light_pts->getNum() ) {
1324         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating lights" );
1325         gnd_lights_transform = new ssgTransform;
1326         gnd_lights_range = new ssgRangeSelector;
1327         gnd_lights_brightness = new ssgSelector;
1328         ssgLeaf *lights;
1329
1330         lights = gen_lights( light_pts, 4, 0.7 );
1331         gnd_lights_brightness->addKid( lights );
1332
1333         lights = gen_lights( light_pts, 2, 0.85 );
1334         gnd_lights_brightness->addKid( lights );
1335
1336         lights = gen_lights( light_pts, 1, 1.0 );
1337         gnd_lights_brightness->addKid( lights );
1338
1339         gnd_lights_range->addKid( gnd_lights_brightness );
1340         gnd_lights_transform->addKid( gnd_lights_range );
1341         gnd_lights_transform->setTransform( &sgcoord );
1342     }
1343
1344     // Add runway lights to scene graph if any exist
1345     if ( rwy_lights_transform->getNumKids() > 0 ) {
1346         SG_LOG( SG_TERRAIN, SG_DEBUG, "adding runway lights" );
1347         rwy_lights_transform->setTransform( &sgcoord );
1348     }
1349
1350     // ADA
1351     // Create runway lights - 23 Mar 2001
1352     lightmaps_transform = NULL;
1353     lightmaps_sequence = NULL;
1354     ols_transform = NULL;
1355     //    lightmaps_range = NULL;
1356
1357     if ( lights_rway->getNum() ) {
1358         SG_LOG( SG_TERRAIN, SG_DEBUG, "generating airport lights" );
1359         lightmaps_transform = new ssgTransform;
1360         //      lightmaps_range = new ssgRangeSelector;
1361         lightmaps_brightness = new ssgSelector;
1362         lightmaps_sequence = new ssgSelector;
1363         ols_transform = new ssgTransform;
1364         ssgBranch *lightmaps_branch;
1365
1366         // call function to generate the runway lights
1367         lightmaps_branch = gen_runway_lights( lights_rway, 
1368                                               lights_normal, lights_dir, lights_type);
1369         lightmaps_brightness->addKid( lightmaps_branch );
1370         
1371         // build the runway lights' scene
1372         //    lightmaps_range->addKid( lightmaps_brightness ); //dont know why this doesnt work !!
1373         //      lightmaps_transform->addKid( lightmaps_range );    //dont know why this doesnt work !!
1374         lightmaps_transform->addKid( lightmaps_brightness );
1375         lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1376         lightmaps_transform->addKid( lightmaps_sequence );
1377         lightmaps_transform->setTransform( &sgcoord );
1378     }
1379     // ADA
1380 }
1381
1382
1383 void
1384 FGTileEntry::add_ssg_nodes( ssgBranch* terrain_branch,
1385                             ssgBranch* gnd_lights_branch,
1386                             ssgBranch* rwy_lights_branch )
1387 {
1388     // bump up the ref count so we can remove this later without
1389     // having ssg try to free the memory.
1390     terra_transform->ref();
1391     terrain_branch->addKid( terra_transform );
1392
1393     SG_LOG( SG_TERRAIN, SG_DEBUG,
1394             "connected a tile into scene graph.  terra_transform = "
1395             << terra_transform );
1396     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
1397             << terra_transform->getNumParents() );
1398
1399     if ( gnd_lights_transform != NULL ) {
1400         // bump up the ref count so we can remove this later without
1401         // having ssg try to free the memory.
1402         gnd_lights_transform->ref();
1403         gnd_lights_branch->addKid( gnd_lights_transform );
1404     }
1405
1406     if ( rwy_lights_transform != NULL ) {
1407         // bump up the ref count so we can remove this later without
1408         // having ssg try to free the memory.
1409         rwy_lights_transform->ref();
1410         rwy_lights_branch->addKid( rwy_lights_transform );
1411     }
1412
1413     // ADA
1414     if ( lightmaps_transform != 0 ) {
1415         // bump up the ref count so we can remove this later without
1416         // having ssg try to free the memory.
1417         lightmaps_transform->ref();
1418         gnd_lights_branch->addKid( lightmaps_transform );
1419     }
1420     // ADA
1421
1422     loaded = true;
1423 }
1424
1425
1426 void
1427 FGTileEntry::disconnect_ssg_nodes()
1428 {
1429     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
1430
1431     if ( ! loaded ) {
1432         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
1433     } else {
1434         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform );
1435     }
1436         
1437     // find the terrain branch parent
1438     int pcount = terra_transform->getNumParents();
1439     if ( pcount > 0 ) {
1440         // find the first parent (should only be one)
1441         ssgBranch *parent = terra_transform->getParent( 0 ) ;
1442         if( parent ) {
1443             // disconnect the tile (we previously ref()'d it so it
1444             // won't get freed now)
1445             parent->removeKid( terra_transform );
1446         } else {
1447             SG_LOG( SG_TERRAIN, SG_ALERT,
1448                     "parent pointer is NULL!  Dying" );
1449             exit(-1);
1450         }
1451     } else {
1452         SG_LOG( SG_TERRAIN, SG_ALERT,
1453                 "Parent count is zero for an ssg tile!  Dying" );
1454         exit(-1);
1455     }
1456
1457     // find the ground lighting branch
1458     if ( gnd_lights_transform ) {
1459         pcount = gnd_lights_transform->getNumParents();
1460         if ( pcount > 0 ) {
1461             // find the first parent (should only be one)
1462             ssgBranch *parent = gnd_lights_transform->getParent( 0 ) ;
1463             if( parent ) {
1464                 // disconnect the light branch (we previously ref()'d
1465                 // it so it won't get freed now)
1466                 parent->removeKid( gnd_lights_transform );
1467             } else {
1468                 SG_LOG( SG_TERRAIN, SG_ALERT,
1469                         "parent pointer is NULL!  Dying" );
1470                 exit(-1);
1471             }
1472         } else {
1473             SG_LOG( SG_TERRAIN, SG_ALERT,
1474                     "Parent count is zero for an ssg light tile!  Dying" );
1475             exit(-1);
1476         }
1477     }
1478
1479     // find the runway lighting branch
1480     if ( rwy_lights_transform ) {
1481         pcount = rwy_lights_transform->getNumParents();
1482         if ( pcount > 0 ) {
1483             // find the first parent (should only be one)
1484             ssgBranch *parent = rwy_lights_transform->getParent( 0 ) ;
1485             if( parent ) {
1486                 // disconnect the light branch (we previously ref()'d
1487                 // it so it won't get freed now)
1488                 parent->removeKid( rwy_lights_transform );
1489             } else {
1490                 SG_LOG( SG_TERRAIN, SG_ALERT,
1491                         "parent pointer is NULL!  Dying" );
1492                 exit(-1);
1493             }
1494         } else {
1495             SG_LOG( SG_TERRAIN, SG_ALERT,
1496                     "Parent count is zero for an ssg light tile!  Dying" );
1497             exit(-1);
1498         }
1499     }
1500
1501     // ADA
1502     //runway lights - 23 Mar 2001
1503     // Delete runway lights and free memory
1504     if ( lightmaps_transform ) {
1505         // delete the runway lighting branch
1506         pcount = lightmaps_transform->getNumParents();
1507         if ( pcount > 0 ) {
1508             // find the first parent (should only be one)
1509             ssgBranch *parent = lightmaps_transform->getParent( 0 ) ;
1510             if( parent ) {
1511                 parent->removeKid( lightmaps_transform );
1512                 lightmaps_transform = NULL;
1513             } else {
1514                 SG_LOG( SG_TERRAIN, SG_ALERT,
1515                         "lightmaps parent pointer is NULL!  Dying" );
1516                 exit(-1);
1517             }
1518         } else {
1519             SG_LOG( SG_TERRAIN, SG_ALERT,
1520                     "Parent count is zero for an ssg lightmap tile!  Dying" );
1521             exit(-1);
1522         }
1523     }
1524     // ADA
1525 }