1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
3 // Written by Curtis Olson, started January 1998.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
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.
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.
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.
35 #include <Aircraft/aircraft.hxx>
37 #include <Debug/logstream.hxx>
38 // #include <Bucket/bucketutils.hxx>
39 #include <Include/fg_constants.h>
40 #include <Main/options.hxx>
41 #include <Main/views.hxx>
42 #include <Math/fg_geodesy.hxx>
43 #include <Math/mat3.h>
44 #include <Math/point3d.hxx>
45 #include <Math/polar3d.hxx>
46 #include <Math/vector.hxx>
47 #include <Objects/material.hxx>
48 #include <Objects/obj.hxx>
49 #include <Weather/weather.hxx>
51 #include "scenery.hxx"
53 #include "tilecache.hxx"
54 #include "tilemgr.hxx"
57 // to test clipping speedup in fgTileMgrRender()
58 #if defined ( USE_FAST_FOV_CLIP )
59 // #define TEST_FOV_CLIP
64 #define FG_LOCAL_X_Y 81 // max(o->tile_diameter) ** 2
66 #define FG_SQUARE( X ) ( (X) * (X) )
68 #if defined(USE_MEM) || defined(WIN32)
69 # define FG_MEM_COPY(to,from,n) memcpy(to, from, n)
71 # define FG_MEM_COPY(to,from,n) bcopy(from, to, n)
74 // closest (potentially viewable) tiles, centered on current tile.
75 // This is an array of pointers to cache indexes.
76 int tiles[FG_LOCAL_X_Y];
79 // Initialize the Tile Manager subsystem
80 int fgTileMgrInit( void ) {
81 FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
83 // load default material library
84 material_mgr.load_lib();
91 void fgTileMgrLoadTile( const FGBucket& p, int *index) {
94 c = &global_tile_cache;
96 FG_LOG( FG_TERRAIN, FG_DEBUG, "Updating for bucket " << p );
98 // if not in cache, load tile into the next available slot
99 *index = c->exists(p);
101 *index = c->next_avail();
102 c->fill_in(*index, p);
105 FG_LOG( FG_TERRAIN, FG_DEBUG, "Selected cache index: " << *index );
109 // Calculate shortest distance from point to line
110 static double point_line_dist_squared( const Point3D& tc, const Point3D& vp,
116 p[0] = tc.x(); p[1] = tc.y(); p[2] = tc.z();
117 p0[0] = vp.x(); p0[1] = vp.y(); p0[2] = vp.z();
119 return fgPointLineSquared(p, p0, d);
123 // Determine scenery altitude. Normally this just happens when we
124 // render the scene, but we'd also like to be able to do this
125 // explicitely. lat & lon are in radians. abs_view_pos in meters.
126 // Returns result in meters.
128 fgTileMgrCurElevNEW( const FGBucket& p ) {
130 fgFRAGMENT *frag_ptr;
131 Point3D abs_view_pos = current_view.get_abs_view_pos();
132 Point3D earth_center(0.0);
135 double dist, lat_geod, alt, sea_level_r;
138 local_up[0] = abs_view_pos.x();
139 local_up[1] = abs_view_pos.y();
140 local_up[2] = abs_view_pos.z();
142 // Find current translation offset
143 // fgBucketFind(lon * RAD_TO_DEG, lat * RAD_TO_DEG, &p);
144 index = global_tile_cache.exists(p);
146 FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
150 t = global_tile_cache.get_tile(index);
152 scenery.next_center = t->center;
154 FG_LOG( FG_TERRAIN, FG_DEBUG,
155 "Current bucket = " << p << " Index = " << p.gen_index_str() );
156 FG_LOG( FG_TERRAIN, FG_DEBUG,
157 "abs_view_pos = " << abs_view_pos );
159 // calculate tile offset
160 // x = (t->offset.x = t->center.x - scenery.center.x);
161 // y = (t->offset.y = t->center.y - scenery.center.y);
162 // z = (t->offset.z = t->center.z - scenery.center.z);
164 // calc current terrain elevation calculate distance from
165 // vertical tangent line at current position to center of
168 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
169 point_line_dist_squared(&(t->offset), &(v->view_pos),
170 v->local_up), t->bounding_radius); */
172 dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
173 if ( dist < FG_SQUARE(t->bounding_radius) ) {
175 // traverse fragment list for tile
176 fgTILE::FragmentIterator current = t->begin();
177 fgTILE::FragmentIterator last = t->end();
179 for ( ; current != last; ++current ) {
180 frag_ptr = &(*current);
181 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
182 point_line_dist_squared( &(frag_ptr->center),
183 &abs_view_pos), local_up),
184 frag_ptr->bounding_radius); */
186 dist = point_line_dist_squared( frag_ptr->center,
189 if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
190 if ( frag_ptr->intersect( abs_view_pos,
191 earth_center, 0, result ) ) {
192 FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
194 // compute geocentric coordinates of tile center
195 Point3D pp = fgCartToPolar3d(result);
196 FG_LOG( FG_TERRAIN, FG_DEBUG, " polar form = " << pp );
197 // convert to geodetic coordinates
198 fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod,
201 // printf("alt = %.2f\n", alt);
202 // exit since we found an intersection
203 if ( alt > -9999.0 ) {
204 // printf("returning alt\n");
207 // printf("returning 0\n");
215 FG_LOG( FG_TERRAIN, FG_INFO, "(new) no terrain intersection found" );
221 // Determine scenery altitude. Normally this just happens when we
222 // render the scene, but we'd also like to be able to do this
223 // explicitely. lat & lon are in radians. abs_view_pos in meters.
224 // Returns result in meters.
226 fgTileMgrCurElev( double lon, double lat, const Point3D& abs_view_pos ) {
229 fgFRAGMENT *frag_ptr;
230 Point3D earth_center(0.0);
233 double dist, lat_geod, alt, sea_level_r;
236 c = &global_tile_cache;
238 local_up[0] = abs_view_pos.x();
239 local_up[1] = abs_view_pos.y();
240 local_up[2] = abs_view_pos.z();
242 FG_LOG( FG_TERRAIN, FG_DEBUG, "Absolute view pos = " << abs_view_pos );
244 // Find current translation offset
245 FGBucket p( lon * RAD_TO_DEG, lat * RAD_TO_DEG );
246 index = c->exists(p);
248 FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found" );
252 t = c->get_tile(index);
254 scenery.next_center = t->center;
256 FG_LOG( FG_TERRAIN, FG_DEBUG,
257 "Pos = (" << lon * RAD_TO_DEG << ", " << lat * RAD_TO_DEG
258 << ") Current bucket = " << p
259 << " Index = " << p.gen_index_str() );
261 FG_LOG( FG_TERRAIN, FG_DEBUG, "Tile center " << t->center
262 << " bounding radius = " << t->bounding_radius );
264 // calculate tile offset
265 // x = (t->offset.x = t->center.x - scenery.center.x);
266 // y = (t->offset.y = t->center.y - scenery.center.y);
267 // z = (t->offset.z = t->center.z - scenery.center.z);
269 // calc current terrain elevation calculate distance from
270 // vertical tangent line at current position to center of
273 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
274 point_line_dist_squared(&(t->offset), &(v->view_pos),
275 v->local_up), t->bounding_radius); */
277 dist = point_line_dist_squared( t->center, abs_view_pos, local_up );
278 FG_LOG( FG_TERRAIN, FG_DEBUG, "(gross check) dist squared = " << dist );
280 if ( dist < FG_SQUARE(t->bounding_radius) ) {
282 // traverse fragment list for tile
283 fgTILE::FragmentIterator current = t->begin();
284 fgTILE::FragmentIterator last = t->end();
286 for ( ; current != last; ++current ) {
287 frag_ptr = &(*current);
288 /* printf("distance squared = %.2f, bounding radius = %.2f\n",
289 point_line_dist_squared( &(frag_ptr->center),
290 &abs_view_pos), local_up),
291 frag_ptr->bounding_radius); */
293 dist = point_line_dist_squared( frag_ptr->center,
296 if ( dist <= FG_SQUARE(frag_ptr->bounding_radius) ) {
297 if ( frag_ptr->intersect( abs_view_pos,
298 earth_center, 0, result ) ) {
299 FG_LOG( FG_TERRAIN, FG_DEBUG, "intersection point " <<
301 // compute geocentric coordinates of tile center
302 Point3D pp = fgCartToPolar3d(result);
303 FG_LOG( FG_TERRAIN, FG_DEBUG, " polar form = " << pp );
304 // convert to geodetic coordinates
305 fgGeocToGeod(pp.lat(), pp.radius(), &lat_geod,
308 // printf("alt = %.2f\n", alt);
309 // exit since we found an intersection
310 if ( alt > -9999.0 ) {
311 // printf("returning alt\n");
314 // printf("returning 0\n");
322 FG_LOG( FG_TERRAIN, FG_INFO, "(old) no terrain intersection found" );
328 // given the current lon/lat, fill in the array of local chunks. If
329 // the chunk isn't already in the cache, then read it from disk.
330 int fgTileMgrUpdate( void ) {
334 static FGBucket p_last(false);
335 static double last_lon = -1000.0; // in degrees
336 static double last_lat = -1000.0; // in degrees
340 c = &global_tile_cache;
341 f = current_aircraft.fdm_state;
343 tile_diameter = current_options.get_tile_diameter();
345 FGBucket p1( f->get_Longitude() * RAD_TO_DEG,
346 f->get_Latitude() * RAD_TO_DEG );
347 dw = tile_diameter / 2;
348 dh = tile_diameter / 2;
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.get_lon() == -1000 ) {
354 // First time through, initialize the system and load all
357 FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
358 FG_LOG( FG_TERRAIN, FG_INFO, " First time through ... " );
359 FG_LOG( FG_TERRAIN, FG_INFO, " Updating Tile list for " << p1 );
360 FG_LOG( FG_TERRAIN, FG_INFO, " Loading "
361 << tile_diameter * tile_diameter << " tiles" );
363 // wipe/initialize tile cache
366 // build the local area list and update cache
367 for ( j = 0; j < tile_diameter; j++ ) {
368 for ( i = 0; i < tile_diameter; i++ ) {
369 // fgBucketOffset(&p1, &p2, i - dw, j - dh);
370 p2 = fgBucketOffset( f->get_Longitude() * RAD_TO_DEG,
371 f->get_Latitude() * RAD_TO_DEG,
373 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + i]);
377 // We've moved to a new bucket, we need to scroll our
378 // structures, and load in the new tiles
380 // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
381 // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
382 // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
384 FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << p1 );
386 if ( (p1.get_lon() > p_last.get_lon()) ||
387 ( (p1.get_lon() == p_last.get_lon()) && (p1.get_x() > p_last.get_x()) ) ) {
388 FG_LOG( FG_TERRAIN, FG_INFO,
389 " Loading " << tile_diameter << "tiles" );
390 for ( j = 0; j < tile_diameter; j++ ) {
392 for ( i = 0; i < tile_diameter - 1; i++ ) {
393 tiles[(j*tile_diameter) + i] =
394 tiles[(j*tile_diameter) + i + 1];
396 // load in new column
397 // fgBucketOffset(&p_last, &p2, dw + 1, j - dh);
398 p2 = fgBucketOffset( last_lon, last_lat, dw + 1, j - dh );
399 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) +
402 } else if ( (p1.get_lon() < p_last.get_lon()) ||
403 ( (p1.get_lon() == p_last.get_lon()) && (p1.get_x() < p_last.get_x()) ) ) {
404 FG_LOG( FG_TERRAIN, FG_INFO,
405 " Loading " << tile_diameter << "tiles" );
406 for ( j = 0; j < tile_diameter; j++ ) {
408 for ( i = tile_diameter - 1; i > 0; i-- ) {
409 tiles[(j*tile_diameter) + i] =
410 tiles[(j*tile_diameter) + i - 1];
412 // load in new column
413 // fgBucketOffset(&p_last, &p2, -dw - 1, j - dh);
414 p2 = fgBucketOffset( last_lon, last_lat, -dw - 1, j - dh );
415 fgTileMgrLoadTile( p2, &tiles[(j*tile_diameter) + 0]);
419 if ( (p1.get_lat() > p_last.get_lat()) ||
420 ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() > p_last.get_y()) ) ) {
421 FG_LOG( FG_TERRAIN, FG_INFO,
422 " Loading " << tile_diameter << "tiles" );
423 for ( i = 0; i < tile_diameter; i++ ) {
425 for ( j = 0; j < tile_diameter - 1; j++ ) {
426 tiles[(j * tile_diameter) + i] =
427 tiles[((j+1) * tile_diameter) + i];
429 // load in new column
430 // fgBucketOffset(&p_last, &p2, i - dw, dh + 1);
431 p2 = fgBucketOffset( last_lon, last_lat, i - dw, dh + 1);
432 fgTileMgrLoadTile( p2, &tiles[((tile_diameter-1) *
433 tile_diameter) + i]);
435 } else if ( (p1.get_lat() < p_last.get_lat()) ||
436 ( (p1.get_lat() == p_last.get_lat()) && (p1.get_y() < p_last.get_y()) ) ) {
437 FG_LOG( FG_TERRAIN, FG_INFO,
438 " Loading " << tile_diameter << "tiles" );
439 for ( i = 0; i < tile_diameter; i++ ) {
441 for ( j = tile_diameter - 1; j > 0; j-- ) {
442 tiles[(j * tile_diameter) + i] =
443 tiles[((j-1) * tile_diameter) + i];
445 // load in new column
446 // fgBucketOffset(&p_last, &p2, i - dw, -dh - 1);
447 p2 = fgBucketOffset( last_lon, last_lat, i - dw, -dh - 1);
448 fgTileMgrLoadTile( p2, &tiles[0 + i]);
453 // find our current elevation (feed in the current bucket to save work)
454 Point3D geod_pos = Point3D( f->get_Longitude(), f->get_Latitude(), 0.0);
455 Point3D tmp_abs_view_pos = fgGeodToCart(geod_pos);
458 fgTileMgrCurElev( f->get_Longitude(), f->get_Latitude(),
462 last_lon = f->get_Longitude() * RAD_TO_DEG;
463 last_lat = f->get_Latitude() * RAD_TO_DEG;
469 // Calculate if point/radius is inside view frustum
470 static int viewable( const Point3D& cp, double radius ) {
471 int viewable = 1; // start by assuming it's viewable
474 /********************************/
475 #if defined( USE_FAST_FOV_CLIP ) // views.hxx
476 /********************************/
486 mat = (double *)(current_view.get_WORLD_TO_EYE());
488 eye[2] = x*mat[2] + y*mat[6] + z*mat[10] + mat[14];
490 // Check near and far clip plane
491 if( ( eye[2] > radius ) ||
492 ( eye[2] + radius + current_weather.get_visibility() < 0) )
497 eye[0] = (x*mat[0] + y*mat[4] + z*mat[8] + mat[12])
498 * current_view.get_slope_x();
500 // check right and left clip plane (from eye perspective)
501 x1 = radius * current_view.get_fov_x_clip();
502 if( (eye[2] > -(eye[0]+x1)) || (eye[2] > (eye[0]-x1)) )
507 eye[1] = (x*mat[1] + y*mat[5] + z*mat[9] + mat[13])
508 * current_view.get_slope_y();
510 // check bottom and top clip plane (from eye perspective)
511 y1 = radius * current_view.get_fov_y_clip();
512 if( (eye[2] > -(eye[1]+y1)) || (eye[2] > (eye[1]-y1)) )
517 /********************************/
518 #else // DO NOT USE_FAST_FOV_CLIP
519 /********************************/
527 MAT3_SET_HVEC(world, cp->x, cp->y, cp->z, 1.0);
528 // MAT3mult_vec(eye, world, v->WORLD_TO_EYE);
529 // printf( "\nworld -> eye = %.2f %.2f %.2f radius = %.2f\n",
530 // eye[0], eye[1], eye[2], radius);
532 // Use lazy evaluation for calculating eye hvec.
534 #define mat v->WORLD_TO_EYE
535 eye[2] = vec[0]*mat[0][2]+vec[1]*mat[1][2]+vec[2]*mat[2][2]+mat[3][2];
537 // Check near clip plane
538 if ( eye[2] > radius ) {
542 // Check far clip plane
543 if ( eye[2] + radius < -current_weather.get_visibility() ) {
547 // check right clip plane (from eye perspective)
548 // y = m * (x - x0) = equation of a line intercepting X axis at x0
549 x1 = v->cos_fov_x * radius;
550 y1 = v->sin_fov_x * radius;
552 eye[0] = vec[0]*mat[0][0]+vec[1]*mat[1][0]+vec[2]*mat[2][0]+mat[3][0];
554 if ( eye[2] > ((slope * (eye[0] - x1)) + y1) ) {
558 // check left clip plane (from eye perspective)
559 if ( eye[2] > -((slope * (eye[0] + x1)) - y1) ) {
563 // check bottom clip plane (from eye perspective)
564 x1 = -(v->cos_fov_y) * radius;
565 y1 = v->sin_fov_y * radius;
567 eye[1] = vec[0]*mat[0][1]+vec[1]*mat[1][1]+vec[2]*mat[2][1]+mat[3][1];
571 if ( eye[2] > ((slope * (eye[1] - x1)) + y1) ) {
575 // check top clip plane (from eye perspective)
576 if ( eye[2] > -((slope * (eye[1] + x1)) - y1) ) {
580 #endif // defined( USE_FAST_FOV_CLIP )
588 // inrange() IS THIS POINT WITHIN POSSIBLE VIEWING RANGE ?
589 // calculate distance from vertical tangent line at
590 // current position to center of object.
591 // this is equivalent to
592 // dist = point_line_dist_squared( &(t->center), &(v->abs_view_pos),
594 // if ( dist < FG_SQUARE(t->bounding_radius) ) {
596 // the compiler should inline this for us
599 inrange( const double radius, const Point3D& center, const Point3D& vp,
606 u[0] = center.x() - vp.x();
607 u[1] = center.y() - vp.y();
608 u[2] = center.z() - vp.z();
610 // calculate the projection, u1, of u along d.
611 // u1 = ( dot_prod(u, d) / dot_prod(d, d) ) * d;
613 MAT3_SCALE_VEC(u1, up,
614 (MAT3_DOT_PRODUCT(u, up) / MAT3_DOT_PRODUCT(up, up)) );
616 // v = u - u1 = vector from closest point on line, p1, to the
617 // original point, p.
618 MAT3_SUB_VEC(v, u, u1);
620 return( FG_SQUARE(radius) >= MAT3_DOT_PRODUCT(v, v));
624 // NEW for legibility
626 // update this tile's geometry for current view
627 // The Compiler should inline this
629 update_tile_geometry( fgTILE *t, GLdouble *MODEL_VIEW)
634 // calculate tile offset
635 t->offset = t->center - scenery.center;
643 // Calculate the model_view transformation matrix for this tile
644 FG_MEM_COPY( m, MODEL_VIEW, 16*sizeof(GLdouble) );
646 // This is equivalent to doing a glTranslatef(x, y, z);
647 m[12] += (m[0]*x + m[4]*y + m[8] *z);
648 m[13] += (m[1]*x + m[5]*y + m[9] *z);
649 m[14] += (m[2]*x + m[6]*y + m[10]*z);
650 // m[15] += (m[3]*x + m[7]*y + m[11]*z);
651 // m[3] m7[] m[11] are 0.0 see LookAt() in views.cxx
652 // so m[15] is unchanged
656 // Render the local tiles
657 void fgTileMgrRender( void ) {
663 fgFRAGMENT *frag_ptr;
671 c = &global_tile_cache;
672 f = current_aircraft.fdm_state;
675 tile_diameter = current_options.get_tile_diameter();
677 // moved to fgTileMgrUpdate, right after we check if we need to
678 // load additional tiles:
679 // scenery.cur_elev = fgTileMgrCurElev( FG_Longitude, FG_Latitude,
680 // v->abs_view_pos );
682 // initialize the transient per-material fragment lists
683 material_mgr.init_transient_material_lists();
686 // traverse the potentially viewable tile list
687 for ( i = 0; i < (tile_diameter * tile_diameter); i++ ) {
689 // fgPrintf( FG_TERRAIN, FG_DEBUG, "Index = %d\n", index);
690 t = c->get_tile(index);
692 // calculate tile offset
693 t->SetOffset( scenery.center );
695 // Course (tile based) culling
696 if ( viewable(t->offset, t->bounding_radius) ) {
697 // at least a portion of this tile could be viewable
699 // Calculate the model_view transformation matrix for this tile
700 // This is equivalent to doing a glTranslatef(x, y, z);
701 t->UpdateViewMatrix( v->get_MODEL_VIEW() );
704 // xglTranslatef(t->offset.x, t->offset.y, t->offset.z);
706 // traverse fragment list for tile
707 fgTILE::FragmentIterator current = t->begin();
708 fgTILE::FragmentIterator last = t->end();
710 for ( ; current != last; ++current ) {
711 frag_ptr = &(*current);
713 if ( frag_ptr->display_list >= 0 ) {
714 // Fine (fragment based) culling
715 frag_offset = frag_ptr->center - scenery.center;
717 if ( viewable(frag_offset, frag_ptr->bounding_radius*2) ) {
718 // add to transient per-material property fragment list
719 // frag_ptr->tile_offset.x = t->offset.x;
720 // frag_ptr->tile_offset.y = t->offset.y;
721 // frag_ptr->tile_offset.z = t->offset.z;
723 mtl_ptr = frag_ptr->material_ptr;
724 // printf(" lookup = %s\n", mtl_ptr->texture_name);
725 if ( ! mtl_ptr->append_sort_list( frag_ptr ) ) {
726 FG_LOG( FG_TERRAIN, FG_ALERT,
727 "Overran material sorting array" );
730 // xglCallList(frag_ptr->display_list);
733 // printf("Culled a fragment %.2f %.2f %.2f %.2f\n",
734 // frag_ptr->center.x, frag_ptr->center.y,
735 // frag_ptr->center.z, frag_ptr->bounding_radius);
743 culled += t->fragment_list.size();
747 if ( (drawn + culled) > 0 ) {
748 v->set_vfc_ratio( (double)culled / (double)(drawn + culled) );
750 v->set_vfc_ratio( 0.0 );
752 // printf("drawn = %d culled = %d saved = %.2f\n", drawn, culled,
756 // traverse the transient per-material fragment lists and render
757 // out all fragments for each material property.
759 material_mgr.render_fragments();