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