]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
6b12d10c92641d17203b0c2297e331cbc925c335
[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/props/props.hxx>
41 #include <simgear/timing/sg_time.hxx>
42 #include <simgear/scene/model/animation.hxx>
43 #include <simgear/ephemeris/ephemeris.hxx>
44 #include <simgear/scene/model/placement.hxx>
45 #include <simgear/math/sg_random.h>
46 #include <simgear/scene/model/modellib.hxx>
47 #include <simgear/scene/model/model.hxx>
48 #ifdef FG_JPEG_SERVER
49 #include <simgear/screen/jpgfactory.hxx>
50 #endif
51
52 #include <simgear/environment/visual_enviro.hxx>
53
54 #include <simgear/scene/model/shadowvolume.hxx>
55
56 #include <Scenery/tileentry.hxx>
57 #include <Time/light.hxx>
58 #include <Time/light.hxx>
59 #include <Aircraft/aircraft.hxx>
60 // #include <Aircraft/replay.hxx>
61 #include <Cockpit/panel.hxx>
62 #include <Cockpit/cockpit.hxx>
63 #include <Cockpit/hud.hxx>
64 #include <Model/panelnode.hxx>
65 #include <Model/modelmgr.hxx>
66 #include <Model/acmodel.hxx>
67 #include <Scenery/scenery.hxx>
68 #include <Scenery/tilemgr.hxx>
69 #include <ATC/ATCdisplay.hxx>
70 #include <GUI/new_gui.hxx>
71
72 #include "splash.hxx"
73 #include "renderer.hxx"
74 #include "main.hxx"
75
76
77 extern void sgShaderFrameInit(double delta_time_sec);
78
79 float default_attenuation[3] = {1.0, 0.0, 0.0};
80
81 ssgSharedPtr<ssgSelector> lightpoints_brightness = new ssgSelector;
82 ssgSharedPtr<ssgTransform> lightpoints_transform = new ssgTransform;
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> cloud3d_imposter_state;
108 ssgSharedPtr<ssgSimpleState> default_state;
109 ssgSharedPtr<ssgSimpleState> hud_and_panel;
110 ssgSharedPtr<ssgSimpleState> menus;
111
112 SGShadowVolume *shadows;
113
114 FGRenderer::FGRenderer()
115 {
116 #ifdef FG_JPEG_SERVER
117    jpgRenderFrame = FGRenderer::update;
118 #endif
119 }
120
121 FGRenderer::~FGRenderer()
122 {
123 #ifdef FG_JPEG_SERVER
124    jpgRenderFrame = NULL;
125 #endif
126 }
127
128
129 void
130 FGRenderer::build_states( void ) {
131     default_state = new ssgSimpleState;
132     default_state->disable( GL_TEXTURE_2D );
133     default_state->enable( GL_CULL_FACE );
134     default_state->enable( GL_COLOR_MATERIAL );
135     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
136     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
137     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
138     default_state->disable( GL_BLEND );
139     default_state->disable( GL_ALPHA_TEST );
140     default_state->disable( GL_LIGHTING );
141
142     cloud3d_imposter_state = new ssgSimpleState;
143     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
144     cloud3d_imposter_state->enable( GL_CULL_FACE );
145     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
146     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
147     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
148     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
149     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
150     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
151     cloud3d_imposter_state->enable( GL_BLEND );
152     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
153     cloud3d_imposter_state->disable( GL_LIGHTING );
154
155     hud_and_panel = new ssgSimpleState;
156     hud_and_panel->disable( GL_CULL_FACE );
157     hud_and_panel->disable( GL_TEXTURE_2D );
158     hud_and_panel->disable( GL_LIGHTING );
159     hud_and_panel->enable( GL_BLEND );
160
161     menus = new ssgSimpleState;
162     menus->disable( GL_CULL_FACE );
163     menus->disable( GL_TEXTURE_2D );
164     menus->enable( GL_BLEND );
165
166     shadows = new SGShadowVolume( globals->get_scenery()->get_scene_graph() );
167     shadows->init( fgGetNode("/sim/rendering", true) );
168     shadows->addOccluder( globals->get_scenery()->get_aircraft_branch(), SGShadowVolume::occluderTypeAircraft );
169
170 }
171
172
173 // Initialize various GL/view parameters
174 void
175 FGRenderer::init( void ) {
176
177     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
178
179     // Go full screen if requested ...
180     if ( fgGetBool("/sim/startup/fullscreen") ) {
181         fgOSFullScreen();
182     }
183
184     // If enabled, normal vectors specified with glNormal are scaled
185     // to unit length after transformation.  Enabling this has
186     // performance implications.  See the docs for glNormal.
187     // glEnable( GL_NORMALIZE );
188
189     glEnable( GL_LIGHTING );
190     glEnable( GL_LIGHT0 );
191     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
192
193     sgVec3 sunpos;
194     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
195     ssgGetLight( 0 ) -> setPosition( sunpos );
196
197     glFogi (GL_FOG_MODE, GL_EXP2);
198     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
199          (!fgGetBool("/sim/rendering/shading"))) {
200         // if fastest fog requested, or if flat shading force fastest
201         glHint ( GL_FOG_HINT, GL_FASTEST );
202     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
203         glHint ( GL_FOG_HINT, GL_DONT_CARE );
204     }
205     if ( fgGetBool("/sim/rendering/wireframe") ) {
206         // draw wire frame
207         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
208     }
209
210     // This is the default anyways, but it can't hurt
211     glFrontFace ( GL_CCW );
212
213     // Just testing ...
214     if ( SGIsOpenGLExtensionSupported("GL_ARB_point_sprite") ||
215          SGIsOpenGLExtensionSupported("GL_NV_point_sprite") )
216     {
217         GLuint handle = thesky->get_sun_texture_id();
218         glBindTexture ( GL_TEXTURE_2D, handle ) ;
219         glTexEnvf(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE);
220         glEnable(GL_POINT_SPRITE);
221         // glEnable(GL_POINT_SMOOTH);
222         glPointSpriteIsSupported = true;
223     }
224     glEnable(GL_LINE_SMOOTH);
225     // glEnable(GL_POLYGON_SMOOTH);      
226     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
227     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
228     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
229 }
230
231
232
233 // Update all Visuals (redraws anything graphics related)
234 void
235 FGRenderer::update( bool refresh_camera_settings ) {
236     bool scenery_loaded = fgGetBool("sim/sceneryloaded") \
237                           || fgGetBool("sim/sceneryloaded-override");
238
239     if ( idle_state < 1000 || !scenery_loaded ) {
240         // still initializing, draw the splash screen
241         fgSplashUpdate(1.0);
242
243         // Keep resetting sim time while the sim is initializing
244         globals->set_sim_time_sec( 0.0 );
245         SGAnimation::set_sim_time_sec( 0.0 );
246         return;
247     }
248
249     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
250     bool skyblend = fgGetBool("/sim/rendering/skyblend");
251     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
252     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
253     bool volumetric_clouds = sgEnviro.get_clouds_enable_state();
254 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
255     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
256                                 !volumetric_clouds &&
257                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
258 #else
259     bool multi_pass_clouds = false;
260 #endif
261     bool draw_clouds = fgGetBool("/environment/clouds/status");
262
263     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
264     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
265
266     // static const SGPropertyNode *longitude
267     //     = fgGetNode("/position/longitude-deg");
268     // static const SGPropertyNode *latitude
269     //     = fgGetNode("/position/latitude-deg");
270     // static const SGPropertyNode *altitude
271     //     = fgGetNode("/position/altitude-ft");
272     static const SGPropertyNode *groundlevel_nearplane
273         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
274
275     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
276     static double last_visibility = -9999;
277
278     // update fog params
279     double actual_visibility;
280     if (fgGetBool("/environment/clouds/status")) {
281         actual_visibility = thesky->get_visibility();
282     } else {
283         actual_visibility = fgGetDouble("/environment/visibility-m");
284     }
285
286         // TODO:TEST only, don't commit that !!
287 //      sgFXperFrameInit();
288
289     sgShaderFrameInit(delta_time_sec);
290
291     if ( actual_visibility != last_visibility ) {
292         last_visibility = actual_visibility;
293
294         fog_exp_density = m_log01 / actual_visibility;
295         fog_exp2_density = sqrt_m_log01 / actual_visibility;
296         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
297         if ( actual_visibility < 8000 ) {
298             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
299             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
300         } else {
301             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
302             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
303         }
304     }
305
306     // double angle;
307     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
308     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
309     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
310     // GLfloat mat_shininess[] = { 10.0 };
311     GLbitfield clear_mask;
312
313     // idle_state is now 1000 meaning we've finished all our
314     // initializations and are running the main loop, so this will
315     // now work without seg faulting the system.
316
317     FGViewer *current__view = globals->get_current_view();
318
319     // calculate our current position in cartesian space
320     Point3D cntr = globals->get_scenery()->get_next_center();
321     globals->get_scenery()->set_center(cntr);
322     // Force update of center dependent values ...
323     current__view->set_dirty();
324
325     if ( refresh_camera_settings ) {
326         // update view port
327         resize( fgGetInt("/sim/startup/xsize"),
328                 fgGetInt("/sim/startup/ysize") );
329
330         // Tell GL we are switching to model view parameters
331         glMatrixMode(GL_MODELVIEW);
332         glLoadIdentity();
333         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
334     }
335
336     clear_mask = GL_DEPTH_BUFFER_BIT;
337     if ( fgGetBool("/sim/rendering/wireframe") ) {
338         clear_mask |= GL_COLOR_BUFFER_BIT;
339     }
340
341     if ( skyblend ) {
342         if ( fgGetBool("/sim/rendering/textures") ) {
343         // glClearColor(black[0], black[1], black[2], black[3]);
344         glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
345                      l->adj_fog_color()[2], l->adj_fog_color()[3]);
346         clear_mask |= GL_COLOR_BUFFER_BIT;
347         }
348     } else {
349         glClearColor(l->sky_color()[0], l->sky_color()[1],
350                      l->sky_color()[2], l->sky_color()[3]);
351         clear_mask |= GL_COLOR_BUFFER_BIT;
352     }
353     if ( multi_pass_clouds && draw_clouds ) {
354         glClearStencil( 0 );
355         clear_mask |= GL_STENCIL_BUFFER_BIT;
356     }
357     glClear( clear_mask );
358
359     // set the opengl state to known default values
360     default_state->force();
361
362     // update fog params if visibility has changed
363     double visibility_meters = fgGetDouble("/environment/visibility-m");
364     thesky->set_visibility(visibility_meters);
365
366     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
367                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
368                         / (double)fgGetInt("/sim/model-hz") );
369
370     // Set correct opengl fog density
371     glFogf (GL_FOG_DENSITY, fog_exp2_density);
372
373     // update the sky dome
374     if ( skyblend ) {
375         /*
376          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
377          << l->sky_color()[0] << " "
378          << l->sky_color()[1] << " "
379          << l->sky_color()[2] << " "
380          << l->sky_color()[3] );
381         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
382          << l->fog_color()[0] << " "
383          << l->fog_color()[1] << " "
384          << l->fog_color()[2] << " "
385          << l->fog_color()[3] ); 
386         SG_LOG( SG_GENERAL, SG_BULK,
387                 "    sun_angle = " << l->sun_angle
388          << "    moon_angle = " << l->moon_angle );
389         */
390
391         static SGSkyColor scolor;
392 //        FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
393
394         scolor.sky_color   = l->sky_color();
395         scolor.fog_color   = l->adj_fog_color();
396         scolor.cloud_color = l->cloud_color();
397         scolor.sun_angle   = l->get_sun_angle();
398         scolor.moon_angle  = l->get_moon_angle();
399         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
400         scolor.nstars      = globals->get_ephem()->getNumStars();
401         scolor.planet_data = globals->get_ephem()->getPlanets();
402         scolor.star_data   = globals->get_ephem()->getStars();
403
404         thesky->repaint( scolor );
405
406         /*
407         SG_LOG( SG_GENERAL, SG_BULK,
408                 "thesky->reposition( view_pos = " << view_pos[0] << " "
409          << view_pos[1] << " " << view_pos[2] );
410         SG_LOG( SG_GENERAL, SG_BULK,
411                 "    zero_elev = " << zero_elev[0] << " "
412          << zero_elev[1] << " " << zero_elev[2]
413          << " lon = " << cur_fdm_state->get_Longitude()
414          << " lat = " << cur_fdm_state->get_Latitude() );
415         SG_LOG( SG_GENERAL, SG_BULK,
416                 "    sun_rot = " << l->get_sun_rotation
417          << " gst = " << SGTime::cur_time_params->getGst() );
418         SG_LOG( SG_GENERAL, SG_BULK,
419              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
420           << " sun dec = " << globals->get_ephem()->getSunDeclination()
421           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
422           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
423         */
424
425         // The sun and moon distances are scaled down versions
426         // of the actual distance to get both the moon and the sun
427         // within the range of the far clip plane.
428         // Moon distance:    384,467 kilometers
429         // Sun distance: 150,000,000 kilometers
430         double sun_horiz_eff, moon_horiz_eff;
431         if (fgGetBool("/sim/rendering/horizon-effect")) {
432         sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
433         moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
434         } else {
435            sun_horiz_eff = moon_horiz_eff = 1.0;
436         }
437
438         static SGSkyState sstate;
439
440         sstate.view_pos  = current__view->get_view_pos();
441         sstate.zero_elev = current__view->get_zero_elev();
442         sstate.view_up   = current__view->get_world_up();
443         sstate.lon       = current__view->getLongitude_deg()
444                             * SGD_DEGREES_TO_RADIANS;
445         sstate.lat       = current__view->getLatitude_deg()
446                             * SGD_DEGREES_TO_RADIANS;
447         sstate.alt       = current__view->getAltitudeASL_ft()
448                             * SG_FEET_TO_METER;
449         sstate.spin      = l->get_sun_rotation();
450         sstate.gst       = globals->get_time_params()->getGst();
451         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
452         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
453         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
454         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
455         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
456         sstate.moon_dist = 40000.0 * moon_horiz_eff;
457
458         thesky->reposition( sstate, delta_time_sec );
459
460         shadows->setupShadows( 
461           current__view->getLongitude_deg(),
462           current__view->getLatitude_deg(),
463           globals->get_time_params()->getGst(),
464           globals->get_ephem()->getSunRightAscension(),
465           globals->get_ephem()->getSunDeclination(),
466           l->get_sun_angle());
467     }
468
469     glEnable( GL_DEPTH_TEST );
470     if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
471         glEnable( GL_FOG );
472         glFogi( GL_FOG_MODE, GL_EXP2 );
473         glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
474     } else
475         glDisable( GL_FOG ); 
476
477     // set sun/lighting parameters
478     ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
479
480     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
481     // we only update GL_AMBIENT for our lights we will never get
482     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
483     // explicitely to black.
484     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
485
486     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
487     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
488     ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
489
490     sgEnviro.setLight(l->adj_fog_color());
491
492     // texture parameters
493     // glEnable( GL_TEXTURE_2D );
494     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
495     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
496
497     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
498       - current__view->getSGLocation()->get_cur_elev_m();
499
500     if ( agl > 10.0 ) {
501         scene_nearplane = 10.0f;
502         scene_farplane = 120000.0f;
503     } else {
504         scene_nearplane = groundlevel_nearplane->getDoubleValue();
505         scene_farplane = 120000.0f;
506     }
507
508     setNearFar( scene_nearplane, scene_farplane );
509
510     sgEnviro.startOfFrame(current__view->get_view_pos(), 
511         current__view->get_world_up(),
512         current__view->getLongitude_deg(),
513         current__view->getLatitude_deg(),
514         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
515         delta_time_sec);
516
517     if ( draw_otw && skyblend ) {
518         // draw the sky backdrop
519
520         // we need a white diffuse light for the phase of the moon
521         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
522         thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
523                          fog_exp2_density );
524         // return to the desired diffuse color
525         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
526     }
527
528     // draw the ssg scene
529     glEnable( GL_DEPTH_TEST );
530
531     if ( fgGetBool("/sim/rendering/wireframe") ) {
532         // draw wire frame
533         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
534     }
535     if ( draw_otw ) {
536         if ( draw_clouds ) {
537
538             // Draw the terrain
539             FGTileMgr::set_tile_filter( true );
540             sgSetModelFilter( false );
541             globals->get_aircraft_model()->select( false );
542             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
543
544             // Disable depth buffer update, draw the clouds
545             glDepthMask( GL_FALSE );
546             if( !volumetric_clouds )
547                 thesky->drawUpperClouds();
548             if ( multi_pass_clouds ) {
549                 thesky->drawLowerClouds();
550             }
551             glDepthMask( GL_TRUE );
552
553             if ( multi_pass_clouds ) {
554                 // Draw the objects except the aircraft
555                 //  and update the stencil buffer with 1
556                 glEnable( GL_STENCIL_TEST );
557                 glStencilFunc( GL_ALWAYS, 1, 1 );
558                 glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
559             }
560             FGTileMgr::set_tile_filter( false );
561             sgSetModelFilter( true );
562             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
563         } else {
564             FGTileMgr::set_tile_filter( true );
565             sgSetModelFilter( true );
566             globals->get_aircraft_model()->select( false );
567             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
568         }
569     }
570
571     // This is a bit kludgy.  Every 200 frames, do an extra
572     // traversal of the scene graph without drawing anything, but
573     // with the field-of-view set to 360x360 degrees.  This
574     // ensures that out-of-range random objects that are not in
575     // the current view frustum will still be freed properly.
576     static int counter = 0;
577     counter++;
578     if (counter >= 200) {
579         sgFrustum f;
580         f.setFOV(360, 360);
581                 // No need to put the near plane too close;
582                 // this way, at least the aircraft can be
583                 // culled.
584         f.setNearFar(1000, 1000000);
585         sgMat4 m;
586         ssgGetModelviewMatrix(m);
587         FGTileMgr::set_tile_filter( true );
588         sgSetModelFilter( true );
589         globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
590         counter = 0;
591     }
592
593     // change state for lighting here
594
595     // draw runway lighting
596     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
597
598     // CLO - 02/25/2005 - DO WE NEED THIS extra fgSetNearFar()?
599     // fgSetNearFar( scene_nearplane, scene_farplane );
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     // Use the hud_and_panel ssgSimpleState for rendering the ATC output
750     // This only works properly if called before the panel call
751     if((fgGetBool("/sim/atc/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
752         globals->get_ATC_display()->update(delta_time_sec);
753
754     // update the panel subsystem
755     if ( globals->get_current_panel() != NULL ) {
756         globals->get_current_panel()->update(delta_time_sec);
757     }
758     fgUpdate3DPanels();
759
760     // We can do translucent menus, so why not. :-)
761     menus->apply();
762     glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
763     puDisplay();
764     // glDisable ( GL_BLEND ) ;
765
766     glEnable( GL_DEPTH_TEST );
767     glEnable( GL_FOG );
768
769     // Fade out the splash screen over the first three seconds.
770     double t = globals->get_sim_time_sec();
771     if (t <= 2.5)
772         fgSplashUpdate((2.5 - t) / 2.5);
773 }
774
775
776
777 // options.cxx needs to see this for toggle_panel()
778 // Handle new window size or exposure
779 void
780 FGRenderer::resize( int width, int height ) {
781     int view_h;
782
783     if ( (!fgGetBool("/sim/virtual-cockpit"))
784          && fgPanelVisible() && idle_state == 1000 ) {
785         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
786                              globals->get_current_panel()->getYOffset()) / 768.0);
787     } else {
788         view_h = height;
789     }
790
791     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
792
793     static int lastwidth = width;
794     static int lastheight = height;
795     if (width != lastwidth)
796         fgSetInt("/sim/startup/xsize", lastwidth = width);
797     if (height != lastheight)
798         fgSetInt("/sim/startup/ysize", lastheight = height);
799
800     guiInitMouse(width, height);
801
802     // for all views
803     FGViewMgr *viewmgr = globals->get_viewmgr();
804     if (viewmgr) {
805       for ( int i = 0; i < viewmgr->size(); ++i ) {
806         viewmgr->get_view(i)->
807           set_aspect_ratio((float)view_h / (float)width);
808       }
809
810       setFOV( viewmgr->get_current_view()->get_h_fov(),
811               viewmgr->get_current_view()->get_v_fov() );
812       // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
813       //      << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
814       //      << endl;
815
816     }
817
818     fgHUDReshape();
819
820 }
821
822
823 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
824 // which will post process and rewrite the resulting frustum if we
825 // want to do asymmetric view frustums.
826
827 static void fgHackFrustum() {
828
829     // specify a percent of the configured view frustum to actually
830     // display.  This is a bit of a hack to achieve asymmetric view
831     // frustums.  For instance, if you want to display two monitors
832     // side by side, you could specify each with a double fov, a 0.5
833     // aspect ratio multiplier, and then the left side monitor would
834     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
835     // and a top_pct = 1.0.  The right side monitor would have a
836     // left_pct = 0.5 and a right_pct = 1.0.
837
838     static SGPropertyNode *left_pct
839         = fgGetNode("/sim/current-view/frustum-left-pct");
840     static SGPropertyNode *right_pct
841         = fgGetNode("/sim/current-view/frustum-right-pct");
842     static SGPropertyNode *bottom_pct
843         = fgGetNode("/sim/current-view/frustum-bottom-pct");
844     static SGPropertyNode *top_pct
845         = fgGetNode("/sim/current-view/frustum-top-pct");
846
847     sgFrustum *f = ssgGetFrustum();
848
849     // cout << " l = " << f->getLeft()
850     //      << " r = " << f->getRight()
851     //      << " b = " << f->getBot()
852     //      << " t = " << f->getTop()
853     //      << " n = " << f->getNear()
854     //      << " f = " << f->getFar()
855     //      << endl;
856
857     double width = f->getRight() - f->getLeft();
858     double height = f->getTop() - f->getBot();
859
860     double l, r, t, b;
861
862     if ( left_pct != NULL ) {
863         l = f->getLeft() + width * left_pct->getDoubleValue();
864     } else {
865         l = f->getLeft();
866     }
867
868     if ( right_pct != NULL ) {
869         r = f->getLeft() + width * right_pct->getDoubleValue();
870     } else {
871         r = f->getRight();
872     }
873
874     if ( bottom_pct != NULL ) {
875         b = f->getBot() + height * bottom_pct->getDoubleValue();
876     } else {
877         b = f->getBot();
878     }
879
880     if ( top_pct != NULL ) {
881         t = f->getBot() + height * top_pct->getDoubleValue();
882     } else {
883         t = f->getTop();
884     }
885
886     ssgSetFrustum(l, r, b, t, f->getNear(), f->getFar());
887 }
888
889
890 // we need some static storage space for these values.  However, we
891 // can't store it in a renderer class object because the functions
892 // that manipulate these are static.  They are static so they can
893 // interface to the display callback system.  There's probably a
894 // better way, there has to be a better way, but I'm not seeing it
895 // right now.
896 static float fov_width = 55.0;
897 static float fov_height = 42.0;
898 static float fov_near = 1.0;
899 static float fov_far = 1000.0;
900
901
902 /** FlightGear code should use this routine to set the FOV rather than
903  *  calling the ssg routine directly
904  */
905 void FGRenderer::setFOV( float w, float h ) {
906     fov_width = w;
907     fov_height = h;
908
909     // fully specify the view frustum before hacking it (so we don't
910     // accumulate hacked effects
911     ssgSetFOV( w, h );
912     ssgSetNearFar( fov_near, fov_far );
913     fgHackFrustum();
914     sgEnviro.setFOV( w, h );
915 }
916
917
918 /** FlightGear code should use this routine to set the Near/Far clip
919  *  planes rather than calling the ssg routine directly
920  */
921 void FGRenderer::setNearFar( float n, float f ) {
922     fov_near = n;
923     fov_far = f;
924
925     // fully specify the view frustum before hacking it (so we don't
926     // accumulate hacked effects
927     ssgSetNearFar( n, f );
928     ssgSetFOV( fov_width, fov_height );
929
930     fgHackFrustum();
931 }
932
933 bool FGRenderer::getPickInfo( sgdVec3 pt, sgdVec3 dir, unsigned x, unsigned y )
934 {
935   // Get the matrices involved in the transform from global to screen
936   // coordinates.
937   sgMat4 pm;
938   ssgGetProjectionMatrix(pm);
939   sgMat4 mv;
940   ssgGetModelviewMatrix(mv);
941   
942   // Compose ...
943   sgMat4 m;
944   sgMultMat4(m, pm, mv);
945   // ... and invert
946   sgInvertMat4(m);
947   
948   // Get the width and height of the display to be able to normalize the
949   // mouse coordinate
950   float width = fgGetInt("/sim/startup/xsize");
951   float height = fgGetInt("/sim/startup/ysize");
952   
953   // Compute some coordinates of in the line from the eyepoint to the
954   // mouse click coodinates.
955   // First build the normalized projection coordinates
956   sgVec4 normPt;
957   sgSetVec4(normPt, (2*x - width)/width, -(2*y - height)/height, 1, 1);
958   // Transform them into the real world
959   sgVec4 worldPt;
960   sgXformPnt4(worldPt, normPt, m);
961   if (worldPt[3] == 0)
962     return false;
963   sgScaleVec3(worldPt, 1/worldPt[3]);
964
965   // Now build a direction from the point
966   FGViewer* view = globals->get_current_view();
967   sgVec4 fDir;
968   sgSubVec3(fDir, worldPt, view->get_view_pos());
969   sgdSetVec3(dir, fDir);
970   sgdNormalizeVec3(dir);
971
972   // Copy the start point
973   sgdCopyVec3(pt, view->get_absolute_view_pos());
974
975   return true;
976 }
977
978 // end of renderer.cxx
979