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