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