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