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