]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
AI Modifications: 1) Added a patch that takes ground speed into consideration
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
12 //
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 // General Public License for more details.
17 //
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <plib/ssg.h>
36 #include <plib/netSocket.h>
37
38 #include <simgear/screen/extensions.hxx>
39 #include <simgear/scene/material/matlib.hxx>
40 #include <simgear/scene/model/animation.hxx>
41 #include <simgear/scene/model/model.hxx>
42 #include <simgear/scene/model/modellib.hxx>
43 #include <simgear/scene/model/placement.hxx>
44 #include <simgear/scene/tgdb/pt_lights.hxx>
45 #include <simgear/props/props.hxx>
46 #include <simgear/timing/sg_time.hxx>
47 #include <simgear/ephemeris/ephemeris.hxx>
48 #include <simgear/math/sg_random.h>
49 #ifdef FG_JPEG_SERVER
50 #include <simgear/screen/jpgfactory.hxx>
51 #endif
52
53 #include <simgear/environment/visual_enviro.hxx>
54
55 #include <simgear/scene/model/shadowvolume.hxx>
56
57 #include <Scenery/tileentry.hxx>
58 #include <Time/light.hxx>
59 #include <Time/light.hxx>
60 #include <Aircraft/aircraft.hxx>
61 // #include <Aircraft/replay.hxx>
62 #include <Cockpit/panel.hxx>
63 #include <Cockpit/cockpit.hxx>
64 #include <Cockpit/hud.hxx>
65 #include <Model/panelnode.hxx>
66 #include <Model/modelmgr.hxx>
67 #include <Model/acmodel.hxx>
68 #include <Scenery/scenery.hxx>
69 #include <Scenery/tilemgr.hxx>
70 #include <ATC/ATCdisplay.hxx>
71 #include <GUI/new_gui.hxx>
72 #include <Instrumentation/instrument_mgr.hxx>
73 #include <Instrumentation/HUD/HUD.hxx>
74
75 #include "splash.hxx"
76 #include "renderer.hxx"
77 #include "main.hxx"
78
79
80 extern void sgShaderFrameInit(double delta_time_sec);
81
82 float default_attenuation[3] = {1.0, 0.0, 0.0};
83
84 // Clip plane settings...
85 float scene_nearplane = 0.5f;
86 float scene_farplane = 120000.0f;
87
88 glPointParameterfProc glPointParameterfPtr = 0;
89 glPointParameterfvProc glPointParameterfvPtr = 0;
90 bool glPointParameterIsSupported = false;
91 bool glPointSpriteIsSupported = false;
92
93
94 // fog constants.  I'm a little nervous about putting actual code out
95 // here but it seems to work (?)
96 static const double m_log01 = -log( 0.01 );
97 static const double sqrt_m_log01 = sqrt( m_log01 );
98 static GLfloat fog_exp_density;
99 static GLfloat fog_exp2_density;
100 static GLfloat rwy_exp2_punch_through;
101 static GLfloat taxi_exp2_punch_through;
102 static GLfloat ground_exp2_punch_through;
103
104 // Sky structures
105 SGSky *thesky;
106
107 ssgSharedPtr<ssgSimpleState> default_state;
108 ssgSharedPtr<ssgSimpleState> hud_and_panel;
109 ssgSharedPtr<ssgSimpleState> menus;
110
111 SGShadowVolume *shadows;
112
113 FGRenderer::FGRenderer()
114 {
115 #ifdef FG_JPEG_SERVER
116    jpgRenderFrame = FGRenderer::update;
117 #endif
118 }
119
120 FGRenderer::~FGRenderer()
121 {
122 #ifdef FG_JPEG_SERVER
123    jpgRenderFrame = NULL;
124 #endif
125 }
126
127
128 void
129 FGRenderer::build_states( void ) {
130     default_state = new ssgSimpleState;
131     default_state->disable( GL_TEXTURE_2D );
132     default_state->enable( GL_CULL_FACE );
133     default_state->enable( GL_COLOR_MATERIAL );
134     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
135     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
136     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
137     default_state->disable( GL_BLEND );
138     default_state->disable( GL_ALPHA_TEST );
139     default_state->disable( GL_LIGHTING );
140
141     hud_and_panel = new ssgSimpleState;
142     hud_and_panel->disable( GL_CULL_FACE );
143     hud_and_panel->disable( GL_TEXTURE_2D );
144     hud_and_panel->disable( GL_LIGHTING );
145     hud_and_panel->enable( GL_BLEND );
146
147     menus = new ssgSimpleState;
148     menus->disable( GL_CULL_FACE );
149     menus->disable( GL_TEXTURE_2D );
150     menus->enable( GL_BLEND );
151
152     shadows = new SGShadowVolume( globals->get_scenery()->get_scene_graph() );
153     shadows->init( fgGetNode("/sim/rendering", true) );
154     shadows->addOccluder( globals->get_scenery()->get_aircraft_branch(), SGShadowVolume::occluderTypeAircraft );
155
156 }
157
158
159 // Initialize various GL/view parameters
160 void
161 FGRenderer::init( void ) {
162
163     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
164
165     // Go full screen if requested ...
166     if ( fgGetBool("/sim/startup/fullscreen") ) {
167         fgOSFullScreen();
168     }
169
170     // If enabled, normal vectors specified with glNormal are scaled
171     // to unit length after transformation.  Enabling this has
172     // performance implications.  See the docs for glNormal.
173     // glEnable( GL_NORMALIZE );
174
175     glEnable( GL_LIGHTING );
176     glEnable( GL_LIGHT0 );
177     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
178
179     sgVec3 sunpos;
180     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
181     ssgGetLight( 0 ) -> setPosition( sunpos );
182
183     glFogi (GL_FOG_MODE, GL_EXP2);
184     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
185          (!fgGetBool("/sim/rendering/shading"))) {
186         // if fastest fog requested, or if flat shading force fastest
187         glHint ( GL_FOG_HINT, GL_FASTEST );
188     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
189         glHint ( GL_FOG_HINT, GL_DONT_CARE );
190     }
191     if ( fgGetBool("/sim/rendering/wireframe") ) {
192         // draw wire frame
193         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
194     }
195
196     // This is the default anyways, but it can't hurt
197     glFrontFace ( GL_CCW );
198
199     // Just testing ...
200     if ( SGIsOpenGLExtensionSupported("GL_ARB_point_sprite") ||
201          SGIsOpenGLExtensionSupported("GL_NV_point_sprite") )
202     {
203         GLuint handle = thesky->get_sun_texture_id();
204         glBindTexture ( GL_TEXTURE_2D, handle ) ;
205         glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
206         glEnable(GL_POINT_SPRITE);
207         // glEnable(GL_POINT_SMOOTH);
208         glPointSpriteIsSupported = true;
209     }
210     glEnable(GL_LINE_SMOOTH);
211     // glEnable(GL_POLYGON_SMOOTH);      
212     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
213     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
214     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
215 }
216
217
218
219 // Update all Visuals (redraws anything graphics related)
220 void
221 FGRenderer::update( bool refresh_camera_settings ) {
222     bool scenery_loaded = fgGetBool("sim/sceneryloaded") \
223                           || fgGetBool("sim/sceneryloaded-override");
224
225     if ( idle_state < 1000 || !scenery_loaded ) {
226         // still initializing, draw the splash screen
227         fgSplashUpdate(1.0);
228
229         // Keep resetting sim time while the sim is initializing
230         globals->set_sim_time_sec( 0.0 );
231         SGAnimation::set_sim_time_sec( 0.0 );
232         return;
233     }
234
235     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
236     bool skyblend = fgGetBool("/sim/rendering/skyblend");
237     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
238     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
239     bool distance_attenuation
240         = fgGetBool("/sim/rendering/distance-attenuation");
241     sgConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
242                                   distance_attenuation );
243     bool volumetric_clouds = sgEnviro.get_clouds_enable_state();
244 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
245     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
246                                 !volumetric_clouds &&
247                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
248 #else
249     bool multi_pass_clouds = false;
250 #endif
251     bool draw_clouds = fgGetBool("/environment/clouds/status");
252
253     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
254     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
255
256     // static const SGPropertyNode *longitude
257     //     = fgGetNode("/position/longitude-deg");
258     // static const SGPropertyNode *latitude
259     //     = fgGetNode("/position/latitude-deg");
260     // static const SGPropertyNode *altitude
261     //     = fgGetNode("/position/altitude-ft");
262     static const SGPropertyNode *groundlevel_nearplane
263         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
264
265     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
266     static double last_visibility = -9999;
267
268     // update fog params
269     double actual_visibility;
270     if (fgGetBool("/environment/clouds/status")) {
271         actual_visibility = thesky->get_visibility();
272     } else {
273         actual_visibility = fgGetDouble("/environment/visibility-m");
274     }
275
276         // TODO:TEST only, don't commit that !!
277 //      sgFXperFrameInit();
278
279     sgShaderFrameInit(delta_time_sec);
280
281     if ( actual_visibility != last_visibility ) {
282         last_visibility = actual_visibility;
283
284         fog_exp_density = m_log01 / actual_visibility;
285         fog_exp2_density = sqrt_m_log01 / actual_visibility;
286         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
287         if ( actual_visibility < 8000 ) {
288             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
289             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
290         } else {
291             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
292             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
293         }
294     }
295
296     // double angle;
297     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
298     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
299     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
300     // GLfloat mat_shininess[] = { 10.0 };
301     GLbitfield clear_mask;
302
303     // idle_state is now 1000 meaning we've finished all our
304     // initializations and are running the main loop, so this will
305     // now work without seg faulting the system.
306
307     FGViewer *current__view = globals->get_current_view();
308
309     // calculate our current position in cartesian space
310     Point3D cntr = globals->get_scenery()->get_next_center();
311     globals->get_scenery()->set_center(cntr);
312     // Force update of center dependent values ...
313     current__view->set_dirty();
314
315     if ( refresh_camera_settings ) {
316         // update view port
317         resize( fgGetInt("/sim/startup/xsize"),
318                 fgGetInt("/sim/startup/ysize") );
319
320         // Tell GL we are switching to model view parameters
321         glMatrixMode(GL_MODELVIEW);
322         glLoadIdentity();
323         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
324     }
325
326     clear_mask = GL_DEPTH_BUFFER_BIT;
327     if ( fgGetBool("/sim/rendering/wireframe") ) {
328         clear_mask |= GL_COLOR_BUFFER_BIT;
329     }
330
331     if ( skyblend ) {
332         if ( fgGetBool("/sim/rendering/textures") ) {
333         // glClearColor(black[0], black[1], black[2], black[3]);
334         glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
335                      l->adj_fog_color()[2], l->adj_fog_color()[3]);
336         clear_mask |= GL_COLOR_BUFFER_BIT;
337         }
338     } else {
339         glClearColor(l->sky_color()[0], l->sky_color()[1],
340                      l->sky_color()[2], l->sky_color()[3]);
341         clear_mask |= GL_COLOR_BUFFER_BIT;
342     }
343     if ( multi_pass_clouds && draw_clouds ) {
344         glClearStencil( 0 );
345         clear_mask |= GL_STENCIL_BUFFER_BIT;
346     }
347     glClear( clear_mask );
348
349     // set the opengl state to known default values
350     default_state->force();
351
352     // update fog params if visibility has changed
353     double visibility_meters = fgGetDouble("/environment/visibility-m");
354     thesky->set_visibility(visibility_meters);
355
356     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
357                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
358                         / (double)fgGetInt("/sim/model-hz") );
359
360     // Set correct opengl fog density
361     glFogf (GL_FOG_DENSITY, fog_exp2_density);
362
363     // update the sky dome
364     if ( skyblend ) {
365
366         // The sun and moon distances are scaled down versions
367         // of the actual distance to get both the moon and the sun
368         // within the range of the far clip plane.
369         // Moon distance:    384,467 kilometers
370         // Sun distance: 150,000,000 kilometers
371
372         double sun_horiz_eff, moon_horiz_eff;
373         if (fgGetBool("/sim/rendering/horizon-effect")) {
374            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
375            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
376         } else {
377            sun_horiz_eff = moon_horiz_eff = 1.0;
378         }
379
380         static SGSkyState sstate;
381
382         sstate.view_pos  = current__view->get_view_pos();
383         sstate.zero_elev = current__view->get_zero_elev();
384         sstate.view_up   = current__view->get_world_up();
385         sstate.lon       = current__view->getLongitude_deg()
386                             * SGD_DEGREES_TO_RADIANS;
387         sstate.lat       = current__view->getLatitude_deg()
388                             * SGD_DEGREES_TO_RADIANS;
389         sstate.alt       = current__view->getAltitudeASL_ft()
390                             * SG_FEET_TO_METER;
391         sstate.spin      = l->get_sun_rotation();
392         sstate.gst       = globals->get_time_params()->getGst();
393         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
394         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
395         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
396         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
397         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
398         sstate.moon_dist = 40000.0 * moon_horiz_eff;
399         sstate.sun_angle = l->get_sun_angle();
400
401
402         /*
403          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
404          << l->sky_color()[0] << " "
405          << l->sky_color()[1] << " "
406          << l->sky_color()[2] << " "
407          << l->sky_color()[3] );
408         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
409          << l->fog_color()[0] << " "
410          << l->fog_color()[1] << " "
411          << l->fog_color()[2] << " "
412          << l->fog_color()[3] );
413         SG_LOG( SG_GENERAL, SG_BULK,
414                 "    sun_angle = " << l->sun_angle
415          << "    moon_angle = " << l->moon_angle );
416         */
417
418         static SGSkyColor scolor;
419 //        FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
420
421         scolor.sky_color   = l->sky_color();
422         scolor.fog_color   = l->adj_fog_color();
423         scolor.cloud_color = l->cloud_color();
424         scolor.sun_angle   = l->get_sun_angle();
425         scolor.moon_angle  = l->get_moon_angle();
426         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
427         scolor.nstars      = globals->get_ephem()->getNumStars();
428         scolor.planet_data = globals->get_ephem()->getPlanets();
429         scolor.star_data   = globals->get_ephem()->getStars();
430
431         thesky->reposition( sstate, delta_time_sec );
432         thesky->repaint( scolor );
433
434         /*
435         SG_LOG( SG_GENERAL, SG_BULK,
436                 "thesky->reposition( view_pos = " << view_pos[0] << " "
437          << view_pos[1] << " " << view_pos[2] );
438         SG_LOG( SG_GENERAL, SG_BULK,
439                 "    zero_elev = " << zero_elev[0] << " "
440          << zero_elev[1] << " " << zero_elev[2]
441          << " lon = " << cur_fdm_state->get_Longitude()
442          << " lat = " << cur_fdm_state->get_Latitude() );
443         SG_LOG( SG_GENERAL, SG_BULK,
444                 "    sun_rot = " << l->get_sun_rotation
445          << " gst = " << SGTime::cur_time_params->getGst() );
446         SG_LOG( SG_GENERAL, SG_BULK,
447              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
448           << " sun dec = " << globals->get_ephem()->getSunDeclination()
449           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
450           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
451         */
452
453         shadows->setupShadows(
454           current__view->getLongitude_deg(),
455           current__view->getLatitude_deg(),
456           globals->get_time_params()->getGst(),
457           globals->get_ephem()->getSunRightAscension(),
458           globals->get_ephem()->getSunDeclination(),
459           l->get_sun_angle());
460
461     }
462
463     glEnable( GL_DEPTH_TEST );
464     if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
465         glEnable( GL_FOG );
466         glFogi( GL_FOG_MODE, GL_EXP2 );
467         glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
468     } else
469         glDisable( GL_FOG ); 
470
471     // set sun/lighting parameters
472     ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
473
474     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
475     // we only update GL_AMBIENT for our lights we will never get
476     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
477     // explicitely to black.
478     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
479
480     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
481     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
482     ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
483
484     sgEnviro.setLight(l->adj_fog_color());
485
486     // texture parameters
487     // glEnable( GL_TEXTURE_2D );
488     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
489     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
490
491     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
492       - current__view->getSGLocation()->get_cur_elev_m();
493
494     if ( agl > 10.0 ) {
495         scene_nearplane = 10.0f;
496         scene_farplane = 120000.0f;
497     } else {
498         scene_nearplane = groundlevel_nearplane->getDoubleValue();
499         scene_farplane = 120000.0f;
500     }
501
502     setNearFar( scene_nearplane, scene_farplane );
503
504     sgEnviro.startOfFrame(current__view->get_view_pos(), 
505         current__view->get_world_up(),
506         current__view->getLongitude_deg(),
507         current__view->getLatitude_deg(),
508         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
509         delta_time_sec);
510
511     if ( draw_otw && skyblend ) {
512         // draw the sky backdrop
513
514         // we need a white diffuse light for the phase of the moon
515         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
516         thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
517                          fog_exp2_density );
518         // return to the desired diffuse color
519         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
520     }
521
522     // draw the ssg scene
523     glEnable( GL_DEPTH_TEST );
524
525     if ( fgGetBool("/sim/rendering/wireframe") ) {
526         // draw wire frame
527         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
528     }
529     if ( draw_otw ) {
530         if ( draw_clouds ) {
531
532             // Draw the terrain
533             FGTileMgr::set_tile_filter( true );
534             sgSetModelFilter( false );
535             globals->get_aircraft_model()->select( false );
536             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
537
538             // Disable depth buffer update, draw the clouds
539             glDepthMask( GL_FALSE );
540             if( !volumetric_clouds )
541                 thesky->drawUpperClouds();
542             if ( multi_pass_clouds ) {
543                 thesky->drawLowerClouds();
544             }
545             glDepthMask( GL_TRUE );
546
547             if ( multi_pass_clouds ) {
548                 // Draw the objects except the aircraft
549                 //  and update the stencil buffer with 1
550                 glEnable( GL_STENCIL_TEST );
551                 glStencilFunc( GL_ALWAYS, 1, 1 );
552                 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
553             }
554             FGTileMgr::set_tile_filter( false );
555             sgSetModelFilter( true );
556             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
557         } else {
558             FGTileMgr::set_tile_filter( true );
559             sgSetModelFilter( true );
560             globals->get_aircraft_model()->select( false );
561             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
562         }
563     }
564
565     // This is a bit kludgy.  Every 200 frames, do an extra
566     // traversal of the scene graph without drawing anything, but
567     // with the field-of-view set to 360x360 degrees.  This
568     // ensures that out-of-range random objects that are not in
569     // the current view frustum will still be freed properly.
570     static int counter = 0;
571     counter++;
572     if (counter >= 200) {
573         sgFrustum f;
574         f.setFOV(360, 360);
575                 // No need to put the near plane too close;
576                 // this way, at least the aircraft can be
577                 // culled.
578         f.setNearFar(1000, 1000000);
579         sgMat4 m;
580         ssgGetModelviewMatrix(m);
581         FGTileMgr::set_tile_filter( true );
582         sgSetModelFilter( true );
583         globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
584         counter = 0;
585     }
586
587     // change state for lighting here
588
589     // draw runway lighting
590     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
591
592     // CLO - 02/25/2005 - DO WE NEED THIS extra fgSetNearFar()?
593     // fgSetNearFar( scene_nearplane, scene_farplane );
594
595     if ( use_point_sprites ) {
596         glEnable(GL_POINT_SPRITE);
597     } else {
598         glDisable(GL_POINT_SPRITE);
599     }
600
601     if ( enhanced_lighting ) {
602
603         // Enable states for drawing points with GL_extension
604         glEnable(GL_POINT_SMOOTH);
605
606         if ( distance_attenuation && glPointParameterIsSupported )
607         {
608             // Enable states for drawing points with GL_extension
609             glEnable(GL_POINT_SMOOTH);
610
611             float quadratic[3] = {1.0, 0.001, 0.0000001};
612             // makes the points fade as they move away
613             glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
614             // glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
615         }
616
617         glPointSize(4.0);
618
619         // blending function for runway lights
620         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
621     }
622
623     glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
624     glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
625     glEnable(GL_TEXTURE_GEN_S);
626     glEnable(GL_TEXTURE_GEN_T);
627     glPolygonMode(GL_FRONT, GL_POINT);
628
629     // draw runway lighting
630     if ( draw_otw ) {
631         ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
632         ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
633     }
634
635     // change punch through and then draw taxi lighting
636     glFogf ( GL_FOG_DENSITY, fog_exp2_density );
637     // sgVec3 taxi_fog;
638     // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
639     // glFogfv ( GL_FOG_COLOR, taxi_fog );
640     if ( draw_otw ) {
641         ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
642     }
643
644     // clean up lighting
645     glPolygonMode(GL_FRONT, GL_FILL);
646     glDisable(GL_TEXTURE_GEN_S);
647     glDisable(GL_TEXTURE_GEN_T);
648
649     //static int _frame_count = 0;
650     //if (_frame_count % 30 == 0) {
651     //  printf("SSG: %s\n", ssgShowStats());
652     //}
653     //else {
654     //  ssgShowStats();
655     //}
656     //_frame_count++;
657
658
659     if ( enhanced_lighting ) {
660         if ( distance_attenuation && glPointParameterIsSupported ) {
661             glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
662                                   default_attenuation);
663         }
664
665         glPointSize(1.0);
666         glDisable(GL_POINT_SMOOTH);
667     }
668
669     // draw ground lighting
670     glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
671     if ( draw_otw ) {
672         ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
673     }
674
675     sgEnviro.drawLightning();
676
677     if ( draw_otw && draw_clouds ) {
678         if ( multi_pass_clouds ) {
679             // Disable depth buffer update, draw the clouds where the
680             //  objects overwrite the already drawn clouds, by testing
681             //  the stencil buffer against 1
682             glDepthMask( GL_FALSE );
683             glStencilFunc( GL_EQUAL, 1, 1 );
684             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
685             thesky->drawUpperClouds();
686             thesky->drawLowerClouds();
687             glDepthMask( GL_TRUE );
688             glDisable( GL_STENCIL_TEST );
689         } else {
690             glDepthMask( GL_FALSE );
691             if( volumetric_clouds )
692                 thesky->drawUpperClouds();
693             thesky->drawLowerClouds();
694             glDepthMask( GL_TRUE );
695         }
696     }
697        double current_view_origin_airspeed_horiz_kt =
698         fgGetDouble("/velocities/airspeed-kt", 0.0)
699                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
700                                * SGD_DEGREES_TO_RADIANS);
701        // TODO:find the real view speed, not the AC one
702     sgEnviro.drawPrecipitation(
703         fgGetDouble("/environment/metar/rain-norm", 0.0),
704         fgGetDouble("/environment/metar/snow-norm", 0.0),
705         fgGetDouble("/environment/metar/hail-norm", 0.0),
706         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
707         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
708         - current__view->getHeadingOffset_deg(),
709                current_view_origin_airspeed_horiz_kt
710                );
711
712     // compute shadows and project them on screen
713     bool is_internal = globals->get_current_view()->getInternal();
714     // draw before ac because ac internal rendering clear the depth buffer
715
716         globals->get_aircraft_model()->select( true );
717     if( is_internal )
718         shadows->endOfFrame();
719
720     if ( draw_otw ) {
721         FGTileMgr::set_tile_filter( false );
722         sgSetModelFilter( false );
723         globals->get_aircraft_model()->select( true );
724         globals->get_model_mgr()->draw();
725         globals->get_aircraft_model()->draw();
726
727         FGTileMgr::set_tile_filter( true );
728         sgSetModelFilter( true );
729         globals->get_aircraft_model()->select( true );
730     }
731         // in 'external' view the ac can be culled, so shadows have not been draw in the
732         // posttrav callback, this would be a rare case if the getInternal was acting
733         // as expected (ie in internal view, getExternal returns false)
734         if( !is_internal )
735                 shadows->endOfFrame();
736
737     // display HUD && Panel
738     glDisable( GL_FOG );
739     glDisable( GL_DEPTH_TEST );
740     // glDisable( GL_CULL_FACE );
741     // glDisable( GL_TEXTURE_2D );
742
743     // update the controls subsystem
744     globals->get_controls()->update(delta_time_sec);
745
746     hud_and_panel->apply();
747     fgCockpitUpdate();
748
749     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr *>(globals->get_subsystem("instrumentation"));
750     HUD *hud = static_cast<HUD *>(instr->get_subsystem("hud"));
751     hud->draw();
752
753     // Use the hud_and_panel ssgSimpleState for rendering the ATC output
754     // This only works properly if called before the panel call
755     if((fgGetBool("/sim/atc/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
756         globals->get_ATC_display()->update(delta_time_sec);
757
758     // update the panel subsystem
759     if ( globals->get_current_panel() != NULL ) {
760         globals->get_current_panel()->update(delta_time_sec);
761     }
762     fgUpdate3DPanels();
763
764     // We can do translucent menus, so why not. :-)
765     menus->apply();
766     glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
767     puDisplay();
768     // glDisable ( GL_BLEND ) ;
769
770     glEnable( GL_DEPTH_TEST );
771     glEnable( GL_FOG );
772
773     // Fade out the splash screen over the first three seconds.
774     double t = globals->get_sim_time_sec();
775     if (t <= 2.5)
776         fgSplashUpdate((2.5 - t) / 2.5);
777 }
778
779
780
781 // options.cxx needs to see this for toggle_panel()
782 // Handle new window size or exposure
783 void
784 FGRenderer::resize( int width, int height ) {
785     int view_h;
786
787     if ( (!fgGetBool("/sim/virtual-cockpit"))
788          && fgPanelVisible() && idle_state == 1000 ) {
789         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
790                              globals->get_current_panel()->getYOffset()) / 768.0);
791     } else {
792         view_h = height;
793     }
794
795     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
796
797     static int lastwidth = 0;
798     static int lastheight = 0;
799     if (width != lastwidth)
800         fgSetInt("/sim/startup/xsize", lastwidth = width);
801     if (height != lastheight)
802         fgSetInt("/sim/startup/ysize", lastheight = height);
803
804     guiInitMouse(width, height);
805
806     // for all views
807     FGViewMgr *viewmgr = globals->get_viewmgr();
808     if (viewmgr) {
809       for ( int i = 0; i < viewmgr->size(); ++i ) {
810         viewmgr->get_view(i)->
811           set_aspect_ratio((float)view_h / (float)width);
812       }
813
814       setFOV( viewmgr->get_current_view()->get_h_fov(),
815               viewmgr->get_current_view()->get_v_fov() );
816       // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
817       //      << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
818       //      << endl;
819
820     }
821
822     fgHUDReshape();
823
824 }
825
826
827 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
828 // which will post process and rewrite the resulting frustum if we
829 // want to do asymmetric view frustums.
830
831 static void fgHackFrustum() {
832
833     // specify a percent of the configured view frustum to actually
834     // display.  This is a bit of a hack to achieve asymmetric view
835     // frustums.  For instance, if you want to display two monitors
836     // side by side, you could specify each with a double fov, a 0.5
837     // aspect ratio multiplier, and then the left side monitor would
838     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
839     // and a top_pct = 1.0.  The right side monitor would have a
840     // left_pct = 0.5 and a right_pct = 1.0.
841
842     static SGPropertyNode *left_pct
843         = fgGetNode("/sim/current-view/frustum-left-pct");
844     static SGPropertyNode *right_pct
845         = fgGetNode("/sim/current-view/frustum-right-pct");
846     static SGPropertyNode *bottom_pct
847         = fgGetNode("/sim/current-view/frustum-bottom-pct");
848     static SGPropertyNode *top_pct
849         = fgGetNode("/sim/current-view/frustum-top-pct");
850
851     sgFrustum *f = ssgGetFrustum();
852
853     // cout << " l = " << f->getLeft()
854     //      << " r = " << f->getRight()
855     //      << " b = " << f->getBot()
856     //      << " t = " << f->getTop()
857     //      << " n = " << f->getNear()
858     //      << " f = " << f->getFar()
859     //      << endl;
860
861     double width = f->getRight() - f->getLeft();
862     double height = f->getTop() - f->getBot();
863
864     double l, r, t, b;
865
866     if ( left_pct != NULL ) {
867         l = f->getLeft() + width * left_pct->getDoubleValue();
868     } else {
869         l = f->getLeft();
870     }
871
872     if ( right_pct != NULL ) {
873         r = f->getLeft() + width * right_pct->getDoubleValue();
874     } else {
875         r = f->getRight();
876     }
877
878     if ( bottom_pct != NULL ) {
879         b = f->getBot() + height * bottom_pct->getDoubleValue();
880     } else {
881         b = f->getBot();
882     }
883
884     if ( top_pct != NULL ) {
885         t = f->getBot() + height * top_pct->getDoubleValue();
886     } else {
887         t = f->getTop();
888     }
889
890     ssgSetFrustum(l, r, b, t, f->getNear(), f->getFar());
891 }
892
893
894 // we need some static storage space for these values.  However, we
895 // can't store it in a renderer class object because the functions
896 // that manipulate these are static.  They are static so they can
897 // interface to the display callback system.  There's probably a
898 // better way, there has to be a better way, but I'm not seeing it
899 // right now.
900 static float fov_width = 55.0;
901 static float fov_height = 42.0;
902 static float fov_near = 1.0;
903 static float fov_far = 1000.0;
904
905
906 /** FlightGear code should use this routine to set the FOV rather than
907  *  calling the ssg routine directly
908  */
909 void FGRenderer::setFOV( float w, float h ) {
910     fov_width = w;
911     fov_height = h;
912
913     // fully specify the view frustum before hacking it (so we don't
914     // accumulate hacked effects
915     ssgSetFOV( w, h );
916     ssgSetNearFar( fov_near, fov_far );
917     fgHackFrustum();
918     sgEnviro.setFOV( w, h );
919 }
920
921
922 /** FlightGear code should use this routine to set the Near/Far clip
923  *  planes rather than calling the ssg routine directly
924  */
925 void FGRenderer::setNearFar( float n, float f ) {
926     fov_near = n;
927     fov_far = f;
928
929     // fully specify the view frustum before hacking it (so we don't
930     // accumulate hacked effects
931     ssgSetNearFar( n, f );
932     ssgSetFOV( fov_width, fov_height );
933
934     fgHackFrustum();
935 }
936
937 bool FGRenderer::getPickInfo( sgdVec3 pt, sgdVec3 dir, unsigned x, unsigned y )
938 {
939   // Get the matrices involved in the transform from global to screen
940   // coordinates.
941   sgMat4 pm;
942   ssgGetProjectionMatrix(pm);
943   sgMat4 mv;
944   ssgGetModelviewMatrix(mv);
945   
946   // Compose ...
947   sgMat4 m;
948   sgMultMat4(m, pm, mv);
949   // ... and invert
950   sgInvertMat4(m);
951   
952   // Get the width and height of the display to be able to normalize the
953   // mouse coordinate
954   float width = fgGetInt("/sim/startup/xsize");
955   float height = fgGetInt("/sim/startup/ysize");
956   
957   // Compute some coordinates of in the line from the eyepoint to the
958   // mouse click coodinates.
959   // First build the normalized projection coordinates
960   sgVec4 normPt;
961   sgSetVec4(normPt, (2*x - width)/width, -(2*y - height)/height, 1, 1);
962   // Transform them into the real world
963   sgVec4 worldPt;
964   sgXformPnt4(worldPt, normPt, m);
965   if (worldPt[3] == 0)
966     return false;
967   sgScaleVec3(worldPt, 1/worldPt[3]);
968
969   // Now build a direction from the point
970   FGViewer* view = globals->get_current_view();
971   sgVec4 fDir;
972   sgSubVec3(fDir, worldPt, view->get_view_pos());
973   sgdSetVec3(dir, fDir);
974   sgdNormalizeVec3(dir);
975
976   // Copy the start point
977   sgdCopyVec3(pt, view->get_absolute_view_pos());
978
979   return true;
980 }
981
982 // end of renderer.cxx
983