]> git.mxchange.org Git - flightgear.git/blob - Scenery/tilemgr.cxx
7c63f048b3966befe939cb100599216178dce0d9
[flightgear.git] / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - curt@infoplane.com
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 // (Log is kept at end of this file)
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #ifdef HAVE_WINDOWS_H
30 #  include <windows.h>
31 #endif
32
33 #include <GL/glut.h>
34 #include <XGL/xgl.h>
35
36 #include <Aircraft/aircraft.hxx>
37
38 #include <Bucket/bucketutils.hxx>
39 #include <Debug/logstream.hxx>
40 #include <Include/fg_constants.h>
41 #include <Main/options.hxx>
42 #include <Main/views.hxx>
43 #include <Math/fg_geodesy.hxx>
44 #include <Math/mat3.h>
45 #include <Math/point3d.hxx>
46 #include <Math/polar3d.hxx>
47 #include <Math/vector.hxx>
48 #include <Objects/material.hxx>
49 #include <Objects/obj.hxx>
50 #include <Weather/weather.hxx>
51
52 #include "scenery.hxx"
53 #include "tile.hxx"
54 #include "tilecache.hxx"
55 #include "tilemgr.hxx"
56
57
58 // to test clipping speedup in fgTileMgrRender()
59 #if defined ( USE_FAST_FOV_CLIP )
60   // #define TEST_FOV_CLIP
61   // #define TEST_ELEV
62 #endif
63
64
65 #define FG_LOCAL_X_Y         81  // max(o->tile_diameter) ** 2
66
67 #define FG_SQUARE( X ) ( (X) * (X) )
68
69 #if defined(USE_MEM) || defined(WIN32)
70 #  define FG_MEM_COPY(to,from,n)        memcpy(to, from, n)
71 #else
72 #  define FG_MEM_COPY(to,from,n)        bcopy(from, to, n)
73 #endif
74
75 // closest (potentially viewable) tiles, centered on current tile.
76 // This is an array of pointers to cache indexes.
77 int tiles[FG_LOCAL_X_Y];
78
79
80 // Initialize the Tile Manager subsystem
81 int fgTileMgrInit( void ) {
82     FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
83
84     // load default material library
85     material_mgr.load_lib();
86
87     return 1;
88 }
89
90
91 // load a tile
92 void fgTileMgrLoadTile( const fgBUCKET& p, int *index) {
93     fgTILECACHE *c;
94
95     c = &global_tile_cache;
96
97     FG_LOG( FG_TERRAIN, FG_DEBUG, "Updating for bucket " << p );
98     
99     // if not in cache, load tile into the next available slot
100     *index = c->exists(p);
101     if ( *index < 0 ) {
102         *index = c->next_avail();
103         c->fill_in(*index, p);
104     }
105
106     FG_LOG( FG_TERRAIN, FG_DEBUG, "Selected cache index: " << *index );
107 }
108
109
110 // Calculate shortest distance from point to line
111 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp, 
112                                        MAT3vec d )
113 {
114     MAT3vec p, p0;
115     double dist;
116
117     p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
118     p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
119
120     dist = fgPointLineSquared(p, p0, d);
121
122     // cout << "dist = " << dist << endl;
123
124     return(dist);
125 }
126
127
128 // Determine scenery altitude.  Normally this just happens when we
129 // render the scene, but we'd also like to be able to do this
130 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
131 // Returns result in meters.
132 double
133 fgTileMgrCurElev( const fgBUCKET& p ) {
134     fgTILE *t;
135     fgFRAGMENT *frag_ptr;
136     Point3D abs_view_pos = current_view.abs_view_pos;
137     Point3D earth_center(0.0);
138     Point3D result;
139     MAT3vec local_up;
140     double dist, lat_geod, alt, sea_level_r;
141     int index;
142
143     local_up[0] = abs_view_pos.x();
144     local_up[1] = abs_view_pos.y();
145     local_up[2] = abs_view_pos.z();
146
147     // Find current translation offset
148     // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
149     index = global_tile_cache.exists(p);
150     if ( index < 0 ) {
151         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
152         return 0.0;
153     }
154
155     t = global_tile_cache.get_tile(index);
156
157     scenery.next_center = t->center;
158     
159     FG_LOG( FG_TERRAIN, FG_DEBUG, 
160             "Current bucket = " << p << "  Index = " << fgBucketGenIndex(&p) );
161     FG_LOG( FG_TERRAIN, FG_DEBUG,
162             "abs_view_pos = " << abs_view_pos );
163
164     // calculate tile offset
165     // x = (t->offset.x = t->center.x - scenery.center.x);
166     // y = (t->offset.y = t->center.y - scenery.center.y);
167     // z = (t->offset.z = t->center.z - scenery.center.z);
168     
169     // calc current terrain elevation calculate distance from
170     // vertical tangent line at current position to center of
171     // tile.
172         
173     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
174        point_line_dist_squared(&(t->offset), &(v->view_pos), 
175        v->local_up), t->bounding_radius); */
176
177     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
178     if ( dist < FG_SQUARE(t->bounding_radius) ) {
179
180         // traverse fragment list for tile
181         fgTILE::FragmentIterator current = t->begin();
182         fgTILE::FragmentIterator last = t->end();
183
184         for ( ; current != last; ++current ) {
185             frag_ptr = &(*current);
186             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
187                point_line_dist_squared( &(frag_ptr->center), 
188                &abs_view_pos), local_up),
189                frag_ptr->bounding_radius); */
190
191             dist = point_line_dist_squared( frag_ptr->center,
192                                             abs_view_pos,
193                                             local_up);
194             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
195                 if ( frag_ptr->intersect( abs_view_pos, 
196                                           earth_center, 0, result ) ) {
197                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
198                             result );
199                     // compute geocentric coordinates of tile center
200                     Point3D pp = fgCartToPolar3d(result);
201                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
202                     // convert to geodetic coordinates
203                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
204                                  &alt, &sea_level_r);
205
206                     // printf("alt = %.2f\n", alt);
207                     // exit since we found an intersection
208                     if ( alt > -9999.0 ) {
209                         // printf("returning alt\n");
210                         return alt;
211                     } else {
212                         // printf("returning 0\n");
213                         return 0.0;
214                     }
215                 }
216             }
217         }
218     }
219
220     cout << "(new) no terrain intersection found\n";
221     return 0.0;
222 }
223
224
225 // Determine scenery altitude.  Normally this just happens when we
226 // render the scene, but we'd also like to be able to do this
227 // explicitely.  lat & lon are in radians.  abs_view_pos in meters.
228 // Returns result in meters.
229 double
230 fgTileMgrCurElevOLD( double lon, double lat, const Point3D& abs_view_pos ) {
231     fgTILECACHE *c;
232     fgTILE *t;
233     // fgVIEW *v;
234     fgFRAGMENT *frag_ptr;
235     fgBUCKET p;
236     Point3D earth_center(0.0);
237     Point3D result;
238     MAT3vec local_up;
239     double dist, lat_geod, alt, sea_level_r;
240     // double x, y, z;
241     int index;
242
243     c = &global_tile_cache;
244     // v = &current_view;
245
246     local_up[0] = abs_view_pos.x();
247     local_up[1] = abs_view_pos.y();
248     local_up[2] = abs_view_pos.z();
249
250     // Find current translation offset
251     fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
252     index = c->exists(p);
253     if ( index < 0 ) {
254         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
255         return 0.0;
256     }
257
258     t = c->get_tile(index);
259
260     scenery.next_center = t->center;
261     
262     // earth_center = Point3D(0.0, 0.0, 0.0);
263
264     FG_LOG( FG_TERRAIN, FG_DEBUG, 
265             "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
266             << ")  Current bucket = " << p 
267             << "  Index = " << fgBucketGenIndex(&p) );
268
269     // calculate tile offset
270     // x = (t->offset.x = t->center.x - scenery.center.x);
271     // y = (t->offset.y = t->center.y - scenery.center.y);
272     // z = (t->offset.z = t->center.z - scenery.center.z);
273     
274     // calc current terrain elevation calculate distance from
275     // vertical tangent line at current position to center of
276     // tile.
277         
278     /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
279        point_line_dist_squared(&(t->offset), &(v->view_pos), 
280        v->local_up), t->bounding_radius); */
281
282     dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
283     if ( dist < FG_SQUARE(t->bounding_radius) ) {
284
285         // traverse fragment list for tile
286         fgTILE::FragmentIterator current = t->begin();
287         fgTILE::FragmentIterator last = t->end();
288
289         for ( ; current != last; ++current ) {
290             frag_ptr = &(*current);
291             /* printf("distance squared = %.2f, bounding radius = %.2f\n", 
292                point_line_dist_squared( &(frag_ptr->center), 
293                &abs_view_pos), local_up),
294                frag_ptr->bounding_radius); */
295
296             dist = point_line_dist_squared( frag_ptr->center,
297                                             abs_view_pos,
298                                             local_up);
299             if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
300                 if ( frag_ptr->intersect( abs_view_pos, 
301                                           earth_center, 0, result ) ) {
302                     FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
303                             result );
304                     // compute geocentric coordinates of tile center
305                     Point3D pp = fgCartToPolar3d(result);
306                     FG_LOG( FG_TERRAIN, FG_DEBUG, "  polar form = " << pp );
307                     // convert to geodetic coordinates
308                     fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod, 
309                                  &alt, &sea_level_r);
310
311                     // printf("alt = %.2f\n", alt);
312                     // exit since we found an intersection
313                     if ( alt > -9999.0 ) {
314                         // printf("returning alt\n");
315                         return alt;
316                     } else {
317                         // printf("returning 0\n");
318                         return 0.0;
319                     }
320                 }
321             }
322         }
323     }
324
325     cout << "(old) no terrain intersection found\n";
326     return 0.0;
327 }
328
329
330 // given the current lon/lat, fill in the array of local chunks.  If
331 // the chunk isn't already in the cache, then read it from disk.
332 int fgTileMgrUpdate( void ) {
333     fgTILECACHE *c;
334     fgFLIGHT *f;
335     fgBUCKET p1, p2;
336     static fgBUCKET p_last = {-1000, 0, 0, 0};
337     int tile_diameter;
338     int i, j, dw, dh;
339
340     c = &global_tile_cache;
341     f = current_aircraft.flight;
342
343     tile_diameter = current_options.get_tile_diameter();
344
345     fgBucketFind( f->get_Longitude() * RAD_TO_DEG,
346                   f->get_Latitude() * RAD_TO_DEG, &p1);
347     dw = tile_diameter / 2;
348     dh = tile_diameter / 2;
349
350     if ( p1 == p_last ) {
351         // same bucket as last time
352         FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
353     } else if ( p_last.lon == -1000 ) {
354         // First time through, initialize the system and load all
355         // relavant tiles
356
357         FG_LOG( FG_TERRAIN, FG_INFO, "  First time through ... " );
358         FG_LOG( FG_TERRAIN, FG_INFO, "  Updating Tile list for " << p1 );
359         FG_LOG( FG_TERRAIN, FG_INFO, "  Loading " 
360                 << tile_diameter * tile_diameter << " tiles" );
361
362         // wipe/initialize tile cache
363         c->init();
364
365         // build the local area list and update cache
366         for ( j = 0; j < tile_diameter; j++ ) {
367             for ( i = 0; i < tile_diameter; i++ ) {
368                 fgBucketOffset(&p1, &p2, i - dw, j - dh);
369                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + i]);
370             }
371         }
372     } else {
373         // We've moved to a new bucket, we need to scroll our
374         // structures, and load in the new tiles
375
376         // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
377         // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
378         // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
379
380         FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
381
382         if ( (p1.lon > p_last.lon) ||
383              ( (p1.lon == p_last.lon) && (p1.x > p_last.x) ) ) {
384             FG_LOG( FG_TERRAIN, FG_INFO, 
385                     "  Loading " << tile_diameter << "tiles" );
386             for ( j = 0; j < tile_diameter; j++ ) {
387                 // scrolling East
388                 for ( i = 0; i < tile_diameter - 1; i++ ) {
389                     tiles[(j*tile_diameter) + i] = 
390                         tiles[(j*tile_diameter) + i + 1];
391                 }
392                 // load in new column
393                 fgBucketOffset(&p_last, &p2, dw + 1, j - dh);
394                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 
395                                              tile_diameter - 1]);
396             }
397         } else if ( (p1.lon < p_last.lon) ||
398                     ( (p1.lon == p_last.lon) && (p1.x < p_last.x) ) ) {
399             FG_LOG( FG_TERRAIN, FG_INFO, 
400                     "  Loading " << tile_diameter << "tiles" );
401             for ( j = 0; j < tile_diameter; j++ ) {
402                 // scrolling West
403                 for ( i = tile_diameter - 1; i > 0; i-- ) {
404                     tiles[(j*tile_diameter) + i] = 
405                         tiles[(j*tile_diameter) + i - 1];
406                 }
407                 // load in new column
408                 fgBucketOffset(&p_last, &p2, -dw - 1, j - dh);
409                 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 0]);
410             }
411         }
412
413         if ( (p1.lat > p_last.lat) ||
414              ( (p1.lat == p_last.lat) && (p1.y > p_last.y) ) ) {
415             FG_LOG( FG_TERRAIN, FG_INFO, 
416                     "  Loading " << tile_diameter << "tiles" );
417             for ( i = 0; i < tile_diameter; i++ ) {
418                 // scrolling North
419                 for ( j = 0; j < tile_diameter - 1; j++ ) {
420                     tiles[(j * tile_diameter) + i] =
421                         tiles[((j+1) * tile_diameter) + i];
422                 }
423                 // load in new column
424                 fgBucketOffset(&p_last, &p2, i - dw, dh + 1);
425                 fgTileMgrLoadTile( p2, &tiles[((tile_diameter-1) * 
426                                                tile_diameter) + i]);
427             }
428         } else if ( (p1.lat < p_last.lat) ||
429                     ( (p1.lat == p_last.lat) && (p1.y < p_last.y) ) ) {
430             FG_LOG( FG_TERRAIN, FG_INFO, 
431                     "  Loading " << tile_diameter << "tiles" );
432             for ( i = 0; i < tile_diameter; i++ ) {
433                 // scrolling South
434                 for ( j = tile_diameter - 1; j > 0; j-- ) {
435                     tiles[(j * tile_diameter) + i] = 
436                         tiles[((j-1) * tile_diameter) + i];
437                 }
438                 // load in new column
439                 fgBucketOffset(&p_last, &p2, i - dw, -dh - 1);
440                 fgTileMgrLoadTile( p2, &tiles[0 + i]);
441             }
442         }
443     }
444
445     // find our current elevation (feed in the current bucket to save work)
446     scenery.cur_elev = fgTileMgrCurElev( p1 );
447
448     p_last.lon = p1.lon;
449     p_last.lat = p1.lat;
450     p_last.x = p1.x;
451     p_last.y = p1.y;
452
453     return 1;
454 }
455
456
457 // Calculate if point/radius is inside view frustum
458 static int viewable( const Point3D& cp, double radius ) {
459     int viewable = 1; // start by assuming it's viewable
460     double x1, y1;
461
462 /********************************/
463 #if defined( USE_FAST_FOV_CLIP ) // views.hxx
464 /********************************/
465         
466     MAT3vec eye;        
467     double *mat;
468     double x, y, z;
469
470     x = cp.x();
471     y = cp.y();
472     z = cp.z();
473         
474     mat = (double *)(current_view.WORLD_TO_EYE);
475         
476     eye[2] =  x*mat[2] + y*mat[6] + z*mat[10] + mat[14];
477         
478     // Check near and far clip plane
479     if( ( eye[2] > radius ) ||
480         ( eye[2] + radius + current_weather.visibility < 0) )
481     {
482         return(0);
483     }
484         
485     eye[0] = (x*mat[0] + y*mat[4] + z*mat[8] + mat[12]) * current_view.slope_x;
486
487     // check right and left clip plane (from eye perspective)
488     x1 = radius * current_view.fov_x_clip;
489     if( (eye[2] > -(eye[0]+x1)) || (eye[2] > (eye[0]-x1)) )
490     {
491         return(0);
492     }
493         
494     eye[1] = (x*mat[1] + y*mat[5] + z*mat[9] + mat[13]) * current_view.slope_y;
495
496     // check bottom and top clip plane (from eye perspective)
497     y1 = radius * current_view.fov_y_clip;
498     if( (eye[2] > -(eye[1]+y1)) || (eye[2] > (eye[1]-y1)) )
499     {
500         return(0);
501     }
502
503 /********************************/      
504 #else // DO NOT USE_FAST_FOV_CLIP
505 /********************************/      
506
507     fgVIEW *v;
508     MAT3hvec world, eye;
509     double x0, slope;
510
511     v = &current_view;
512
513     MAT3_SET_HVEC(world, cp->x, cp->y, cp->z, 1.0);
514     // MAT3mult_vec(eye, world, v->WORLD_TO_EYE);
515     // printf( "\nworld -> eye = %.2f %.2f %.2f  radius = %.2f\n", 
516     //         eye[0], eye[1], eye[2], radius);
517
518     // Use lazy evaluation for calculating eye hvec.
519 #define vec world
520 #define mat v->WORLD_TO_EYE
521     eye[2] = vec[0]*mat[0][2]+vec[1]*mat[1][2]+vec[2]*mat[2][2]+mat[3][2];
522
523     // Check near clip plane
524     if ( eye[2] > radius ) {
525         return(0);
526     }
527
528     // Check far clip plane
529     if ( eye[2] + radius < -current_weather.visibility ) {
530         return(0);
531     }
532
533     // check right clip plane (from eye perspective)
534     // y = m * (x - x0) = equation of a line intercepting X axis at x0
535     x1 = v->cos_fov_x * radius;
536     y1 = v->sin_fov_x * radius;
537     slope = v->slope_x;
538     eye[0] = vec[0]*mat[0][0]+vec[1]*mat[1][0]+vec[2]*mat[2][0]+mat[3][0];
539
540     if ( eye[2] > ((slope * (eye[0] - x1)) + y1) ) {
541         return( false );
542     }
543
544     // check left clip plane (from eye perspective)
545     if ( eye[2] > -((slope * (eye[0] + x1)) - y1) ) {
546         return( false );
547     }
548
549     // check bottom clip plane (from eye perspective)
550     x1 = -(v->cos_fov_y) * radius;
551     y1 = v->sin_fov_y * radius;
552     slope = v->slope_y;
553     eye[1] = vec[0]*mat[0][1]+vec[1]*mat[1][1]+vec[2]*mat[2][1]+mat[3][1];
554 #undef vec
555 #undef mat
556
557     if ( eye[2] > ((slope * (eye[1] - x1)) + y1) ) {
558         return( false );
559     }
560
561     // check top clip plane (from eye perspective)
562     if ( eye[2] > -((slope * (eye[1] + x1)) - y1) ) {
563         return( false );
564     }
565
566 #endif // defined( USE_FAST_FOV_CLIP )
567         
568     return(viewable);
569 }
570
571
572 // NEW 
573
574 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
575 //      calculate distance from vertical tangent line at
576 //      current position to center of object.
577 //      this is equivalent to
578 //      dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos), 
579 //                                      v->local_up );
580 //      if ( dist < FG_SQUARE(t->bounding_radius) ) {
581 //
582 // the compiler should inline this for us
583
584 static int
585 inrange( const double radius, const Point3D& center, const Point3D& vp,
586          const MAT3vec up)
587 {
588     MAT3vec u, u1, v;
589     //  double tmp;
590         
591     // u = p - p0
592     u[0] = center.x() - vp.x();
593     u[1] = center.y() - vp.y();
594     u[2] = center.z() - vp.z();
595         
596     // calculate the projection, u1, of u along d.
597     // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
598         
599     MAT3_SCALE_VEC(u1, up,
600                    (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
601     
602     // v = u - u1 = vector from closest point on line, p1, to the
603     // original point, p.
604     MAT3_SUB_VEC(v, u, u1);
605         
606     return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
607 }
608
609
610 // NEW for legibility
611
612 // update this tile's geometry for current view
613 // The Compiler should inline this
614 static void
615 update_tile_geometry( fgTILE *t, GLdouble *MODEL_VIEW)
616 {
617     GLdouble *m;
618     double x, y, z;
619         
620     // calculate tile offset
621     t->offset = t->center - scenery.center;
622
623     x = t->offset.x();
624     y = t->offset.y();
625     z = t->offset.z();
626         
627     m = t->model_view;
628         
629     // Calculate the model_view transformation matrix for this tile
630     FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
631     
632     // This is equivalent to doing a glTranslatef(x, y, z);
633     m[12] += (m[0]*x + m[4]*y + m[8] *z);
634     m[13] += (m[1]*x + m[5]*y + m[9] *z);
635     m[14] += (m[2]*x + m[6]*y + m[10]*z);
636     // m[15] += (m[3]*x + m[7]*y + m[11]*z);
637     // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
638     // so m[15] is unchanged
639 }
640
641
642 // Render the local tiles
643 void fgTileMgrRender( void ) {
644     fgFLIGHT *f;
645     fgTILECACHE *c;
646     fgTILE *t;
647     fgVIEW *v;
648     Point3D frag_offset;
649     fgFRAGMENT *frag_ptr;
650     fgMATERIAL *mtl_ptr;
651     int i;
652     int tile_diameter;
653     int index;
654     int culled = 0;
655     int drawn = 0;
656
657     c = &global_tile_cache;
658     f = current_aircraft.flight;
659     v = &current_view;
660
661     tile_diameter = current_options.get_tile_diameter();
662
663     // moved to fgTileMgrUpdate, right after we check if we need to
664     // load additional tiles:
665     // scenery.cur_elev = fgTileMgrCurElev( FG_Longitude, FG_Latitude, 
666     //                                      v->abs_view_pos );
667  
668     // initialize the transient per-material fragment lists
669     material_mgr.init_transient_material_lists();
670    
671     // Pass 1
672     // traverse the potentially viewable tile list
673     for ( i = 0; i < (tile_diameter * tile_diameter); i++ ) {
674         index = tiles[i];
675         // fgPrintf( FG_TERRAIN, FG_DEBUG, "Index = %d\n", index);
676         t = c->get_tile(index);
677
678         // calculate tile offset
679         t->SetOffset( scenery.center );
680
681         // Course (tile based) culling
682         if ( viewable(t->offset, t->bounding_radius) ) {
683             // at least a portion of this tile could be viewable
684             
685             // Calculate the model_view transformation matrix for this tile
686             // This is equivalent to doing a glTranslatef(x, y, z);
687             t->UpdateViewMatrix( v->MODEL_VIEW );
688
689             // xglPushMatrix();
690             // xglTranslatef(t->offset.x, t->offset.y, t->offset.z);
691
692             // traverse fragment list for tile
693             fgTILE::FragmentIterator current = t->begin();
694             fgTILE::FragmentIterator last = t->end();
695
696             for ( ; current != last; ++current ) {
697                 frag_ptr = &(*current);
698                 
699                 if ( frag_ptr->display_list >= 0 ) {
700                     // Fine (fragment based) culling
701                     frag_offset = frag_ptr->center - scenery.center;
702
703                     if ( viewable(frag_offset, frag_ptr->bounding_radius*2) ) {
704                         // add to transient per-material property fragment list
705                         // frag_ptr->tile_offset.x = t->offset.x;
706                         // frag_ptr->tile_offset.y = t->offset.y;
707                         // frag_ptr->tile_offset.z = t->offset.z;
708
709                         mtl_ptr = frag_ptr->material_ptr;
710                         // printf(" lookup = %s\n", mtl_ptr->texture_name);
711                         if ( ! mtl_ptr->append_sort_list( frag_ptr ) ) {
712                             FG_LOG( FG_TERRAIN, FG_ALERT,
713                                     "Overran material sorting array" );
714                         }
715
716                         // xglCallList(frag_ptr->display_list);
717                         drawn++;
718                     } else {
719                         // printf("Culled a fragment %.2f %.2f %.2f %.2f\n",
720                         //        frag_ptr->center.x, frag_ptr->center.y,
721                         //        frag_ptr->center.z, frag_ptr->bounding_radius);
722                         culled++;
723                     }
724                 }
725             }
726
727             // xglPopMatrix();
728         } else {
729             culled += t->fragment_list.size();
730         }
731     }
732
733     if ( (drawn + culled) > 0 ) {
734         v->vfc_ratio = (double)culled / (double)(drawn + culled);
735     } else {
736         v->vfc_ratio = 0.0;
737     }
738     // printf("drawn = %d  culled = %d  saved = %.2f\n", drawn, culled, 
739     //        v->vfc_ratio);
740
741     // Pass 2
742     // traverse the transient per-material fragment lists and render
743     // out all fragments for each material property.
744     xglPushMatrix();
745     material_mgr.render_fragments();
746     xglPopMatrix();
747 }
748
749
750 // $Log$
751 // Revision 1.48  1998/12/05 14:20:21  curt
752 // Looking into a terrain intersection problem.
753 //
754 // Revision 1.47  1998/12/05 14:11:19  curt
755 // Sun portability tweak.
756 //
757 // Revision 1.46  1998/12/03 14:15:24  curt
758 // Actually set the current scenery elevation based on scenery intersection point
759 // rather than calculating the intesection point and throwing it away.
760 //
761 // Revision 1.45  1998/12/03 01:18:18  curt
762 // Converted fgFLIGHT to a class.
763 // Tweaks for Sun Portability.
764 // Tweaked current terrain elevation code as per NHV.
765 //
766 // Revision 1.44  1998/11/23 21:49:48  curt
767 // minor tweaks.
768 //
769 // Revision 1.43  1998/11/09 23:40:52  curt
770 // Bernie Bright <bbright@c031.aone.net.au> writes:
771 // I've made some changes to the Scenery handling.  Basically just tidy ups.
772 // The main difference is in tile.[ch]xx where I've changed list<fgFRAGMENT> to
773 // vector<fgFRAGMENT>.  Studying our usage patterns this seems reasonable.
774 // Lists are good if you need to insert/delete elements randomly but we
775 // don't do that.  All access seems to be sequential.  Two additional
776 // benefits are smaller memory usage - each list element requires pointers
777 // to the next and previous elements, and faster access - vector iterators
778 // are smaller and faster than list iterators.  This should also help
779 // Charlie Hotchkiss' problem when compiling with Borland and STLport.
780 //
781 // ./Lib/Bucket/bucketutils.hxx
782 //   Convenience functions for fgBUCKET.
783 //
784 // ./Simulator/Scenery/tile.cxx
785 // ./Simulator/Scenery/tile.hxx
786 //   Changed fragment list to a vector.
787 //   Added some convenience member functions.
788 //
789 // ./Simulator/Scenery/tilecache.cxx
790 // ./Simulator/Scenery/tilecache.hxx
791 //   use const fgBUCKET& instead of fgBUCKET* where appropriate.
792 //
793 // ./Simulator/Scenery/tilemgr.cxx
794 // ./Simulator/Scenery/tilemgr.hxx
795 //   uses all the new convenience functions.
796 //
797 // Revision 1.42  1998/11/06 21:18:23  curt
798 // Converted to new logstream debugging facility.  This allows release
799 // builds with no messages at all (and no performance impact) by using
800 // the -DFG_NDEBUG flag.
801 //
802 // Revision 1.41  1998/10/18 01:17:23  curt
803 // Point3D tweaks.
804 //
805 // Revision 1.40  1998/10/17 01:34:28  curt
806 // C++ ifying ...
807 //
808 // Revision 1.39  1998/10/16 00:55:50  curt
809 // Converted to Point3D class.
810 //
811 // Revision 1.38  1998/09/17 18:36:18  curt
812 // Tweaks and optimizations by Norman Vine.
813 //
814 // Revision 1.37  1998/09/15 01:36:45  curt
815 // cleaned up my fragment.num_faces hack :-) to use the STL (no need in
816 // duplicating work.)
817 // Tweaked fgTileMgrRender() do not calc tile matrix unless necessary.
818 // removed some unneeded stuff from fgTileMgrCurElev()
819 //
820 // Revision 1.36  1998/09/14 12:45:26  curt
821 // minor tweaks.
822 //
823 // Revision 1.35  1998/09/10 19:07:16  curt
824 // /Simulator/Objects/fragment.hxx
825 //   Nested fgFACE inside fgFRAGMENT since its not used anywhere else.
826 //
827 // ./Simulator/Objects/material.cxx
828 // ./Simulator/Objects/material.hxx
829 //   Made fgMATERIAL and fgMATERIAL_MGR bona fide classes with private
830 //   data members - that should keep the rabble happy :)
831 //
832 // ./Simulator/Scenery/tilemgr.cxx
833 //   In viewable() delay evaluation of eye[0] and eye[1] in until they're
834 //   actually needed.
835 //   Change to fgTileMgrRender() to call fgMATERIAL_MGR::render_fragments()
836 //   method.
837 //
838 // ./Include/fg_stl_config.h
839 // ./Include/auto_ptr.hxx
840 //   Added support for g++ 2.7.
841 //   Further changes to other files are forthcoming.
842 //
843 // Brief summary of changes required for g++ 2.7.
844 //   operator->() not supported by iterators: use (*i).x instead of i->x
845 //   default template arguments not supported,
846 //   <functional> doesn't have mem_fun_ref() needed by callbacks.
847 //   some std include files have different names.
848 //   template member functions not supported.
849 //
850 // Revision 1.34  1998/09/09 20:58:09  curt
851 // Tweaks to loop constructs with STL usage.
852 //
853 // Revision 1.33  1998/09/08 15:05:10  curt
854 // Optimization by Norman Vine.
855 //
856 // Revision 1.32  1998/08/25 16:52:44  curt
857 // material.cxx material.hxx obj.cxx obj.hxx texload.c texload.h moved to
858 //   ../Objects
859 //
860 // Revision 1.31  1998/08/24 20:11:40  curt
861 // Tweaks ...
862 //
863 // Revision 1.30  1998/08/22  14:49:59  curt
864 // Attempting to iron out seg faults and crashes.
865 // Did some shuffling to fix a initialization order problem between view
866 // position, scenery elevation.
867 //
868 // Revision 1.29  1998/08/20 15:12:06  curt
869 // Used a forward declaration of classes fgTILE and fgMATERIAL to eliminate
870 // the need for "void" pointers and casts.
871 // Quick hack to count the number of scenery polygons that are being drawn.
872 //
873 // Revision 1.28  1998/08/12 21:13:06  curt
874 // material.cxx: don't load textures if they are disabled
875 // obj.cxx: optimizations from Norman Vine
876 // tile.cxx: minor tweaks
877 // tile.hxx: addition of num_faces
878 // tilemgr.cxx: minor tweaks
879 //
880 // Revision 1.27  1998/07/24 21:42:09  curt
881 // material.cxx: whups, double method declaration with no definition.
882 // obj.cxx: tweaks to avoid errors in SGI's CC.
883 // tile.cxx: optimizations by Norman Vine.
884 // tilemgr.cxx: optimizations by Norman Vine.
885 //
886 // Revision 1.26  1998/07/20 12:51:26  curt
887 // Added far clip plane to fragment clipping calculations and tie this to
888 // weather->visibility.  This way you can increase framerates by increasing
889 // for and lowering visibility.
890 //
891 // Revision 1.25  1998/07/13 21:02:01  curt
892 // Wrote access functions for current fgOPTIONS.
893 //
894 // Revision 1.24  1998/07/12 03:18:29  curt
895 // Added ground collision detection.  This involved:
896 // - saving the entire vertex list for each tile with the tile records.
897 // - saving the face list for each fragment with the fragment records.
898 // - code to intersect the current vertical line with the proper face in
899 //   an efficient manner as possible.
900 // Fixed a bug where the tiles weren't being shifted to "near" (0,0,0)
901 //
902 // Revision 1.23  1998/07/08 14:47:23  curt
903 // Fix GL_MODULATE vs. GL_DECAL problem introduced by splash screen.
904 // polare3d.h renamed to polar3d.hxx
905 // fg{Cartesian,Polar}Point3d consolodated.
906 // Added some initial support for calculating local current ground elevation.
907 //
908 // Revision 1.22  1998/07/04 00:54:31  curt
909 // Added automatic mipmap generation.
910 //
911 // When rendering fragments, use saved model view matrix from associated tile
912 // rather than recalculating it with push() translate() pop().
913 //
914 // Revision 1.21  1998/06/27 16:54:59  curt
915 // Check for GL_VERSION_1_1 or GL_EXT_texture_object to decide whether to use
916 //   "EXT" versions of texture management routines.
917 //
918 // Revision 1.20  1998/06/17 21:36:42  curt
919 // Load and manage multiple textures defined in the Materials library.
920 // Boost max material fagments for each material property to 800.
921 // Multiple texture support when rendering.
922 //
923 // Revision 1.19  1998/06/08 17:57:54  curt
924 // Working first pass at material proporty sorting.
925 //
926 // Revision 1.18  1998/06/06 01:09:32  curt
927 // I goofed on the log message in the last commit ... now fixed.
928 //
929 // Revision 1.17  1998/06/06 01:07:18  curt
930 // Increased per material fragment list size from 100 to 400.
931 // Now correctly draw viewable fragments in per material order.
932 //
933 // Revision 1.16  1998/06/05 22:39:55  curt
934 // Working on sorting by, and rendering by material properties.
935 //
936 // Revision 1.15  1998/06/03 00:47:51  curt
937 // No .h for STL includes.
938 // Minor view culling optimizations.
939 //
940 // Revision 1.14  1998/06/01 17:56:20  curt
941 // Incremental additions to material.cxx (not fully functional)
942 // Tweaked vfc_ratio math to avoid divide by zero.
943 //
944 // Revision 1.13  1998/05/24 02:49:10  curt
945 // Implimented fragment level view frustum culling.
946 //
947 // Revision 1.12  1998/05/23 14:09:23  curt
948 // Added tile.cxx and tile.hxx.
949 // Working on rewriting the tile management system so a tile is just a list
950 // fragments, and the fragment record contains the display list for that fragment.
951 //
952 // Revision 1.11  1998/05/20 20:53:55  curt
953 // Moved global ref point and radius (bounding sphere info, and offset) to
954 // data file rather than calculating it on the fly.
955 // Fixed polygon winding problem in scenery generation stage rather than
956 // compensating for it on the fly.
957 // Made a fgTILECACHE class.
958 //
959 // Revision 1.10  1998/05/17 16:59:34  curt
960 // Frist pass at view frustum culling now operational.
961 //
962 // Revision 1.9  1998/05/16 13:09:58  curt
963 // Beginning to add support for view frustum culling.
964 // Added some temporary code to calculate bouding radius, until the
965 //   scenery generation tools and scenery can be updated.
966 //
967 // Revision 1.8  1998/05/07 23:15:21  curt
968 // Fixed a glTexImage2D() usage bug where width and height were mis-swapped.
969 // Added support for --tile-radius=n option.
970 //
971 // Revision 1.7  1998/05/06 03:16:42  curt
972 // Added an option to control square tile radius.
973 //
974 // Revision 1.6  1998/05/02 01:52:18  curt
975 // Playing around with texture coordinates.
976 //
977 // Revision 1.5  1998/04/30 12:35:32  curt
978 // Added a command line rendering option specify smooth/flat shading.
979 //
980 // Revision 1.4  1998/04/27 03:30:14  curt
981 // Minor transformation adjustments to try to keep scenery tiles closer to
982 // (0, 0, 0)  GLfloats run out of precision at the distances we need to model
983 // the earth, but we can do a bunch of pre-transformations using double math
984 // and then cast to GLfloat once everything is close in where we have less
985 // precision problems.
986 //
987 // Revision 1.3  1998/04/25 22:06:32  curt
988 // Edited cvs log messages in source files ... bad bad bad!
989 //
990 // Revision 1.2  1998/04/24 00:51:09  curt
991 // Wrapped "#include <config.h>" in "#ifdef HAVE_CONFIG_H"
992 // Tweaked the scenery file extentions to be "file.obj" (uncompressed)
993 // or "file.obz" (compressed.)
994 //
995 // Revision 1.1  1998/04/22 13:22:48  curt
996 // C++ - ifing the code a bit.
997 //
998 // Revision 1.25  1998/04/18 04:14:07  curt
999 // Moved fg_debug.c to it's own library.
1000 //
1001 // Revision 1.24  1998/04/14 02:23:18  curt
1002 // Code reorganizations.  Added a Lib/ directory for more general libraries.
1003 //
1004 // Revision 1.23  1998/04/08 23:30:08  curt
1005 // Adopted Gnu automake/autoconf system.
1006 //
1007 // Revision 1.22  1998/04/03 22:11:38  curt
1008 // Converting to Gnu autoconf system.
1009 //
1010 // Revision 1.21  1998/03/23 21:23:05  curt
1011 // Debugging output tweaks.
1012 //
1013 // Revision 1.20  1998/03/14 00:30:51  curt
1014 // Beginning initial terrain texturing experiments.
1015 //
1016 // Revision 1.19  1998/02/20 00:16:25  curt
1017 // Thursday's tweaks.
1018 //
1019 // Revision 1.18  1998/02/19 13:05:54  curt
1020 // Incorporated some HUD tweaks from Michelle America.
1021 // Tweaked the sky's sunset/rise colors.
1022 // Other misc. tweaks.
1023 //
1024 // Revision 1.17  1998/02/16 13:39:46  curt
1025 // Miscellaneous weekend tweaks.  Fixed? a cache problem that caused whole
1026 // tiles to occasionally be missing.
1027 //
1028 // Revision 1.16  1998/02/12 21:59:53  curt
1029 // Incorporated code changes contributed by Charlie Hotchkiss
1030 // <chotchkiss@namg.us.anritsu.com>
1031 //
1032 // Revision 1.14  1998/02/09 21:30:19  curt
1033 // Fixed a nagging problem with terrain tiles not "quite" matching up perfectly.
1034 //
1035 // Revision 1.13  1998/02/07 15:29:46  curt
1036 // Incorporated HUD changes and struct/typedef changes from Charlie Hotchkiss
1037 // <chotchkiss@namg.us.anritsu.com>
1038 //
1039 // Revision 1.12  1998/02/01 03:39:55  curt
1040 // Minor tweaks.
1041 //
1042 // Revision 1.11  1998/01/31 00:43:27  curt
1043 // Added MetroWorks patches from Carmen Volpe.
1044 //
1045 // Revision 1.10  1998/01/29 00:51:40  curt
1046 // First pass at tile cache, dynamic tile loading and tile unloading now works.
1047 //
1048 // Revision 1.9  1998/01/27 03:26:44  curt
1049 // Playing with new fgPrintf command.
1050 //
1051 // Revision 1.8  1998/01/27 00:48:04  curt
1052 // Incorporated Paul Bleisch's <pbleisch@acm.org> new debug message
1053 // system and commandline/config file processing code.
1054 //
1055 // Revision 1.7  1998/01/26 15:55:25  curt
1056 // Progressing on building dynamic scenery system.
1057 //
1058 // Revision 1.6  1998/01/24 00:03:30  curt
1059 // Initial revision.
1060 //
1061 // Revision 1.5  1998/01/19 19:27:18  curt
1062 // Merged in make system changes from Bob Kuehne <rpk@sgi.com>
1063 // This should simplify things tremendously.
1064 //
1065 // Revision 1.4  1998/01/19 18:40:38  curt
1066 // Tons of little changes to clean up the code and to remove fatal errors
1067 // when building with the c++ compiler.
1068 //
1069 // Revision 1.3  1998/01/13 00:23:11  curt
1070 // Initial changes to support loading and management of scenery tiles.  Note,
1071 // there's still a fair amount of work left to be done.
1072 //
1073 // Revision 1.2  1998/01/08 02:22:27  curt
1074 // Continue working on basic features.
1075 //
1076 // Revision 1.1  1998/01/07 23:50:51  curt
1077 // "area" renamed to "tile"
1078 //
1079 // Revision 1.2  1998/01/07 03:29:29  curt
1080 // Given an arbitrary lat/lon, we can now:
1081 //   generate a unique index for the chunk containing the lat/lon
1082 //   generate a path name to the chunk file
1083 //   build a list of the indexes of all the nearby areas.
1084 //
1085 // Revision 1.1  1998/01/07 02:05:48  curt
1086 // Initial revision.