]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
02d3d5b8129dab74de8b7a2ea858f0b2c8cc9d0d
[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  - curt@flightgear.org
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
49 #ifdef FG_USE_CLOUDS_3D
50 #  include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
51 #  include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
52 #endif
53
54 #include <Scenery/tileentry.hxx>
55 #include <Time/light.hxx>
56 #include <Time/light.hxx>
57 #include <Aircraft/aircraft.hxx>
58 #include <Cockpit/panel.hxx>
59 #include <Cockpit/cockpit.hxx>
60 #include <Cockpit/radiostack.hxx>
61 #include <Cockpit/hud.hxx>
62 #include <Model/panelnode.hxx>
63 #include <Model/modelmgr.hxx>
64 #include <Model/acmodel.hxx>
65 #include <Scenery/scenery.hxx>
66 #include <Scenery/tilemgr.hxx>
67 #include <ATC/ATCdisplay.hxx>
68 #include <Replay/replay.hxx>
69 #include <GUI/new_gui.hxx>
70
71 #ifdef FG_MPLAYER_AS
72 #include <MultiPlayer/multiplaytxmgr.hxx>
73 #include <MultiPlayer/multiplayrxmgr.hxx>
74 #endif
75
76 #include "splash.hxx"
77 #include "renderer.hxx"
78 #include "main.hxx"
79
80
81 float default_attenuation[3] = {1.0, 0.0, 0.0};
82
83 ssgSelector *lightpoints_brightness = new ssgSelector;
84 ssgTransform *lightpoints_transform = new ssgTransform;
85 FGTileEntry *dummy_tile;
86 sgVec3 rway_ols;
87
88 // Clip plane settings...
89 float scene_nearplane = 0.5f;
90 float scene_farplane = 120000.0f;
91
92 glPointParameterfProc glPointParameterfPtr = 0;
93 glPointParameterfvProc glPointParameterfvPtr = 0;
94 bool glPointParameterIsSupported = 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 #ifdef FG_USE_CLOUDS_3D
111   SkySceneLoader *sgClouds3d;
112   bool _bcloud_orig = true;
113 #endif
114
115 // hack
116 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
117 {
118   {  1.0f,  0.0f,  0.0f,  0.0f },
119   {  0.0f,  0.0f, -1.0f,  0.0f },
120   {  0.0f,  1.0f,  0.0f,  0.0f },
121   {  0.0f,  0.0f,  0.0f,  1.0f }
122 };
123
124 ssgSimpleState *cloud3d_imposter_state;
125 ssgSimpleState *default_state;
126 ssgSimpleState *hud_and_panel;
127 ssgSimpleState *menus;
128
129
130 void fgRenderFrame() {
131 #ifdef FG_MPLAYER_AS
132     // Update any multiplayer models
133     globals->get_multiplayer_rx_mgr()->Update();
134 #endif
135     globals->get_renderer()->update(delta_time_sec);
136 }
137
138 void
139 FGRenderer::build_states( void ) {
140     default_state = new ssgSimpleState;
141     default_state->ref();
142     default_state->disable( GL_TEXTURE_2D );
143     default_state->enable( GL_CULL_FACE );
144     default_state->enable( GL_COLOR_MATERIAL );
145     default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
146     default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
147     default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
148     default_state->disable( GL_BLEND );
149     default_state->disable( GL_ALPHA_TEST );
150     default_state->disable( GL_LIGHTING );
151
152     cloud3d_imposter_state = new ssgSimpleState;
153     cloud3d_imposter_state->ref();
154     cloud3d_imposter_state->enable( GL_TEXTURE_2D );
155     cloud3d_imposter_state->enable( GL_CULL_FACE );
156     cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
157     cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
158     cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
159     cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
160     cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
161     cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
162     cloud3d_imposter_state->enable( GL_BLEND );
163     cloud3d_imposter_state->enable( GL_ALPHA_TEST );
164     cloud3d_imposter_state->disable( GL_LIGHTING );
165
166     hud_and_panel = new ssgSimpleState;
167     hud_and_panel->ref();
168     hud_and_panel->disable( GL_CULL_FACE );
169     hud_and_panel->disable( GL_TEXTURE_2D );
170     hud_and_panel->disable( GL_LIGHTING );
171     hud_and_panel->enable( GL_BLEND );
172
173     menus = new ssgSimpleState;
174     menus->ref();
175     menus->disable( GL_CULL_FACE );
176     menus->disable( GL_TEXTURE_2D );
177     menus->enable( GL_BLEND );
178 }
179
180
181 // Initialize various GL/view parameters
182 void
183 FGRenderer::init( void ) {
184
185     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
186
187     // Go full screen if requested ...
188     if ( fgGetBool("/sim/startup/fullscreen") ) {
189         fgOSFullScreen();
190     }
191
192     // If enabled, normal vectors specified with glNormal are scaled
193     // to unit length after transformation.  Enabling this has
194     // performance implications.  See the docs for glNormal.
195     // glEnable( GL_NORMALIZE );
196
197     glEnable( GL_LIGHTING );
198     glEnable( GL_LIGHT0 );
199     // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );  // done later with ssg
200
201     sgVec3 sunpos;
202     sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
203     ssgGetLight( 0 ) -> setPosition( sunpos );
204
205     glFogi (GL_FOG_MODE, GL_EXP2);
206     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
207          (!fgGetBool("/sim/rendering/shading"))) {
208         // if fastest fog requested, or if flat shading force fastest
209         glHint ( GL_FOG_HINT, GL_FASTEST );
210     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
211         glHint ( GL_FOG_HINT, GL_NICEST );
212     }
213     if ( fgGetBool("/sim/rendering/wireframe") ) {
214         // draw wire frame
215         glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
216     }
217
218     // This is the default anyways, but it can't hurt
219     glFrontFace ( GL_CCW );
220
221     // Just testing ...
222     // glEnable(GL_POINT_SMOOTH);
223     // glEnable(GL_LINE_SMOOTH);
224     // glEnable(GL_POLYGON_SMOOTH);      
225 }
226
227
228 // For HiRes screen Dumps using Brian Pauls TR Library
229 void
230 FGRenderer::screendump( void ) {
231 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
232     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") &&
233                             !SGCloudLayer::enable_bump_mapping; // ugly artefact now
234 #else
235     bool multi_pass_clouds = false;
236 #endif
237     bool draw_clouds = fgGetBool("/environment/clouds/status");
238
239     if ( fgPanelVisible() ) {
240         GLfloat height = fgGetInt("/sim/startup/ysize");
241         GLfloat view_h =
242             (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
243             * (height / 768.0) + 1;
244         glTranslatef( 0.0, view_h, 0.0 );
245     }
246
247     static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
248     static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
249
250     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
251
252     glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1], 
253                  l->adj_fog_color()[2], l->adj_fog_color()[3]);
254
255     glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
256
257     // set the opengl state to known default values
258     default_state->force();
259
260     glEnable( GL_FOG );
261     glFogf  ( GL_FOG_DENSITY, fog_exp2_density);
262     glFogi  ( GL_FOG_MODE,    GL_EXP2 );
263     glFogfv ( GL_FOG_COLOR,   l->adj_fog_color() );
264
265     // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
266     // we only update GL_AMBIENT for our lights we will never get
267     // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
268     // explicitely to black.
269     glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
270     glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
271
272     ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
273
274     // texture parameters
275     glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
276     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
277
278     // we need a white diffuse light for the phase of the moon
279     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
280     thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
281                      fog_exp2_density );
282
283     // draw the ssg scene
284     // return to the desired diffuse color
285     ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
286     glEnable( GL_DEPTH_TEST );
287     ssgSetNearFar( scene_nearplane, scene_farplane );
288     if ( draw_clouds ) {
289         // Draw the terrain
290         FGTileMgr::set_tile_filter( true );
291         sgSetModelFilter( false );
292         globals->get_aircraft_model()->select( false );
293         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
294         // Disable depth buffer update, draw the clouds
295         glDepthMask( GL_FALSE );
296         thesky->drawUpperClouds();
297         if ( multi_pass_clouds ) {
298             thesky->drawLowerClouds();
299         }
300         glDepthMask( GL_TRUE );
301         if ( multi_pass_clouds ) {
302             // Draw the objects except the aircraft
303             //  and update the stencil buffer with 1
304             glEnable( GL_STENCIL_TEST );
305             glStencilFunc( GL_ALWAYS, 1, 1 );
306             glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
307         }
308         FGTileMgr::set_tile_filter( false );
309         sgSetModelFilter( true );
310         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
311     } else {
312         FGTileMgr::set_tile_filter( true );
313         sgSetModelFilter( true );
314         globals->get_aircraft_model()->select( false );
315         ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
316     }
317
318     // draw the lights
319     glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
320     ssgSetNearFar( scene_nearplane, scene_farplane );
321     ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
322     ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
323
324     ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
325
326     if ( draw_clouds ) {
327         if ( multi_pass_clouds ) {
328             // Disable depth buffer update, draw the clouds where the
329             //  objects overwrite the already drawn clouds, by testing
330             //  the stencil buffer against 1
331             glDepthMask( GL_FALSE );
332             glStencilFunc( GL_EQUAL, 1, 1 );
333             glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
334             thesky->drawUpperClouds();
335             thesky->drawLowerClouds();
336             glDepthMask( GL_TRUE );
337             glDisable( GL_STENCIL_TEST );
338         } else {
339             glDepthMask( GL_FALSE );
340             thesky->drawLowerClouds();
341             glDepthMask( GL_TRUE );
342         }
343     }
344
345     globals->get_aircraft_model()->select( true );
346     globals->get_model_mgr()->draw();
347     globals->get_aircraft_model()->draw();
348 }
349
350
351 // Update all Visuals (redraws anything graphics related)
352 void
353 FGRenderer::update(double dt) {
354     bool scenery_loaded = fgGetBool("sim/sceneryloaded") || fgGetBool("sim/sceneryloaded-override");
355     bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
356     bool skyblend = fgGetBool("/sim/rendering/skyblend");
357     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
358     bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
359 #ifdef FG_ENABLE_MULTIPASS_CLOUDS
360     bool multi_pass_clouds = fgGetBool("/sim/rendering/multi-pass-clouds") && 
361                                 !SGCloudLayer::enable_bump_mapping;  // ugly artefact now
362 #else
363     bool multi_pass_clouds = false;
364 #endif
365     bool draw_clouds = fgGetBool("/environment/clouds/status");
366
367     GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
368     GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
369
370     // static const SGPropertyNode *longitude
371     //     = fgGetNode("/position/longitude-deg");
372     // static const SGPropertyNode *latitude
373     //     = fgGetNode("/position/latitude-deg");
374     // static const SGPropertyNode *altitude
375     //     = fgGetNode("/position/altitude-ft");
376     static const SGPropertyNode *groundlevel_nearplane
377         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
378
379     FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
380     static double last_visibility = -9999;
381
382     // update fog params
383     double actual_visibility;
384     if (fgGetBool("/environment/clouds/status"))
385         actual_visibility = thesky->get_visibility();
386     else
387         actual_visibility = fgGetDouble("/environment/visibility-m");
388     if ( actual_visibility != last_visibility ) {
389         last_visibility = actual_visibility;
390
391         fog_exp_density = m_log01 / actual_visibility;
392         fog_exp2_density = sqrt_m_log01 / actual_visibility;
393         ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
394         if ( actual_visibility < 8000 ) {
395             rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
396             taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
397         } else {
398             rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
399             taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
400         }
401     }
402
403     // double angle;
404     // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
405     // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
406     // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
407     // GLfloat mat_shininess[] = { 10.0 };
408     GLbitfield clear_mask;
409
410     if ( idle_state != 1000 || !scenery_loaded ) {
411         // still initializing, draw the splash screen
412         if ( fgGetBool("/sim/startup/splash-screen") ) {
413             fgSplashUpdate(0.0, 1.0);
414         }
415         // Keep resetting sim time while the sim is initializing
416         globals->set_sim_time_sec( 0.0 );
417         SGAnimation::set_sim_time_sec( 0.0 );
418     } else {
419         // idle_state is now 1000 meaning we've finished all our
420         // initializations and are running the main loop, so this will
421         // now work without seg faulting the system.
422
423         FGViewer *current__view = globals->get_current_view();
424
425         // calculate our current position in cartesian space
426         globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
427
428         // update view port
429         fgReshape( fgGetInt("/sim/startup/xsize"),
430                    fgGetInt("/sim/startup/ysize") );
431
432         if ( fgGetBool("/sim/rendering/clouds3d") ) {
433             glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
434             cloud3d_imposter_state->force();
435             glDisable( GL_FOG );
436             glColor4f( 1.0, 1.0, 1.0, 1.0 );
437             glEnable(GL_DEPTH_TEST);
438             glEnable(GL_BLEND);
439             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
440
441 #ifdef FG_USE_CLOUDS_3D
442             if ( _bcloud_orig ) {
443                 Point3D c = globals->get_scenery()->get_center();
444                 sgClouds3d->Set_Cloud_Orig( &c );
445                 _bcloud_orig = false;
446             }
447             sgClouds3d->Update( current__view->get_absolute_view_pos() );
448 #endif
449             glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
450             glDisable(GL_DEPTH_TEST);
451         }
452
453         clear_mask = GL_DEPTH_BUFFER_BIT;
454         if ( fgGetBool("/sim/rendering/wireframe") ) {
455             clear_mask |= GL_COLOR_BUFFER_BIT;
456         }
457
458         if ( skyblend ) {
459             if ( fgGetBool("/sim/rendering/textures") ) {
460             // glClearColor(black[0], black[1], black[2], black[3]);
461             glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
462                          l->adj_fog_color()[2], l->adj_fog_color()[3]);
463             clear_mask |= GL_COLOR_BUFFER_BIT;
464             }
465         } else {
466             glClearColor(l->sky_color()[0], l->sky_color()[1],
467                          l->sky_color()[2], l->sky_color()[3]);
468             clear_mask |= GL_COLOR_BUFFER_BIT;
469         }
470         if ( multi_pass_clouds && draw_clouds ) {
471             glClearStencil( 0 );
472             clear_mask |= GL_STENCIL_BUFFER_BIT;
473         }
474         glClear( clear_mask );
475
476         // Tell GL we are switching to model view parameters
477
478         // I really should create a derived ssg node or use a call
479         // back or something so that I can draw the sky within the
480         // ssgCullAndDraw() function, but for now I just mimic what
481         // ssg does to set up the model view matrix
482         glMatrixMode(GL_MODELVIEW);
483         glLoadIdentity();
484         ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
485
486         // set the opengl state to known default values
487         default_state->force();
488
489         // update fog params if visibility has changed
490         double visibility_meters = fgGetDouble("/environment/visibility-m");
491         thesky->set_visibility(visibility_meters);
492
493         thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
494                             ( global_multi_loop * fgGetInt("/sim/speed-up") )
495                             / (double)fgGetInt("/sim/model-hz") );
496
497         // Set correct opengl fog density
498         glFogf (GL_FOG_DENSITY, fog_exp2_density);
499
500         // update the sky dome
501         if ( skyblend ) {
502             /*
503              SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
504              << l->sky_color()[0] << " "
505              << l->sky_color()[1] << " "
506              << l->sky_color()[2] << " "
507              << l->sky_color()[3] );
508             SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
509              << l->fog_color()[0] << " "
510              << l->fog_color()[1] << " "
511              << l->fog_color()[2] << " "
512              << l->fog_color()[3] ); 
513             SG_LOG( SG_GENERAL, SG_BULK,
514                     "    sun_angle = " << l->sun_angle
515              << "    moon_angle = " << l->moon_angle );
516             */
517
518             static SGSkyColor scolor;
519             FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
520
521             scolor.sky_color   = l->sky_color();
522             scolor.fog_color   = l->adj_fog_color();
523             scolor.cloud_color = l->cloud_color();
524             scolor.sun_angle   = l->get_sun_angle();
525             scolor.moon_angle  = l->get_moon_angle();
526             scolor.nplanets    = globals->get_ephem()->getNumPlanets();
527             scolor.nstars      = globals->get_ephem()->getNumStars();
528             scolor.planet_data = globals->get_ephem()->getPlanets();
529             scolor.star_data   = globals->get_ephem()->getStars();
530
531             thesky->repaint( scolor );
532
533             /*
534             SG_LOG( SG_GENERAL, SG_BULK,
535                     "thesky->reposition( view_pos = " << view_pos[0] << " "
536              << view_pos[1] << " " << view_pos[2] );
537             SG_LOG( SG_GENERAL, SG_BULK,
538                     "    zero_elev = " << zero_elev[0] << " "
539              << zero_elev[1] << " " << zero_elev[2]
540              << " lon = " << cur_fdm_state->get_Longitude()
541              << " lat = " << cur_fdm_state->get_Latitude() );
542             SG_LOG( SG_GENERAL, SG_BULK,
543                     "    sun_rot = " << l->get_sun_rotation
544              << " gst = " << SGTime::cur_time_params->getGst() );
545             SG_LOG( SG_GENERAL, SG_BULK,
546                  "    sun ra = " << globals->get_ephem()->getSunRightAscension()
547               << " sun dec = " << globals->get_ephem()->getSunDeclination()
548               << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
549               << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
550             */
551
552             // The sun and moon distances are scaled down versions
553             // of the actual distance to get both the moon and the sun
554             // within the range of the far clip plane.
555             // Moon distance:    384,467 kilometers
556             // Sun distance: 150,000,000 kilometers
557             double sun_horiz_eff, moon_horiz_eff;
558             if (fgGetBool("/sim/rendering/horizon-effect")) {
559             sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
560             moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
561             } else {
562                sun_horiz_eff = moon_horiz_eff = 1.0;
563             }
564
565             static SGSkyState sstate;
566
567             sstate.view_pos  = current__view->get_view_pos();
568             sstate.zero_elev = current__view->get_zero_elev();
569             sstate.view_up   = current__view->get_world_up();
570             sstate.lon       = current__view->getLongitude_deg()
571                                 * SGD_DEGREES_TO_RADIANS;
572             sstate.lat       = current__view->getLatitude_deg()
573                                 * SGD_DEGREES_TO_RADIANS;
574             sstate.alt       = current__view->getAltitudeASL_ft()
575                                 * SG_FEET_TO_METER;
576             sstate.spin      = l->get_sun_rotation();
577             sstate.gst       = globals->get_time_params()->getGst();
578             sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
579             sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
580             sstate.sun_dist  = 50000.0 * sun_horiz_eff;
581             sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
582             sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
583             sstate.moon_dist = 40000.0 * moon_horiz_eff;
584
585             thesky->reposition( sstate, delta_time_sec );
586         }
587
588         glEnable( GL_DEPTH_TEST );
589         if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
590             glEnable( GL_FOG );
591             glFogi( GL_FOG_MODE, GL_EXP2 );
592             glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
593         }
594
595         // set sun/lighting parameters
596         ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
597
598         // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
599         // we only update GL_AMBIENT for our lights we will never get
600         // a completely dark scene.  So, we set GL_LIGHT_MODEL_AMBIENT
601         // explicitely to black.
602         glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
603
604         ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
605         ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
606         ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
607
608         // texture parameters
609         // glEnable( GL_TEXTURE_2D );
610         glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
611         glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
612
613         // glMatrixMode( GL_PROJECTION );
614         // glLoadIdentity();
615         ssgSetFOV( current__view->get_h_fov(),
616                    current__view->get_v_fov() );
617
618         double agl =
619             current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
620             - globals->get_scenery()->get_cur_elev();
621
622         if ( agl > 10.0 ) {
623             scene_nearplane = 10.0f;
624             scene_farplane = 120000.0f;
625         } else {
626             scene_nearplane = groundlevel_nearplane->getDoubleValue();
627             scene_farplane = 120000.0f;
628         }
629
630         ssgSetNearFar( scene_nearplane, scene_farplane );
631
632         if ( draw_otw && skyblend ) {
633             // draw the sky backdrop
634
635             // we need a white diffuse light for the phase of the moon
636             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
637             thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
638                              fog_exp2_density );
639             // return to the desired diffuse color
640             ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
641         }
642
643         // draw the ssg scene
644         glEnable( GL_DEPTH_TEST );
645
646         ssgSetNearFar( scene_nearplane, scene_farplane );
647
648         if ( fgGetBool("/sim/rendering/wireframe") ) {
649             // draw wire frame
650             glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
651         }
652         if ( draw_otw ) {
653             if ( draw_clouds ) {
654
655                 // Draw the terrain
656                 FGTileMgr::set_tile_filter( true );
657                 sgSetModelFilter( false );
658                 globals->get_aircraft_model()->select( false );
659                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
660
661                 // Disable depth buffer update, draw the clouds
662                 glDepthMask( GL_FALSE );
663                 thesky->drawUpperClouds();
664                 if ( multi_pass_clouds ) {
665                     thesky->drawLowerClouds();
666                 }
667                 glDepthMask( GL_TRUE );
668
669                 if ( multi_pass_clouds ) {
670                     // Draw the objects except the aircraft
671                     //  and update the stencil buffer with 1
672                     glEnable( GL_STENCIL_TEST );
673                     glStencilFunc( GL_ALWAYS, 1, 1 );
674                     glStencilOp( GL_KEEP, GL_KEEP, GL_REPLACE );
675                 }
676                 FGTileMgr::set_tile_filter( false );
677                 sgSetModelFilter( true );
678                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
679             } else {
680                 FGTileMgr::set_tile_filter( true );
681                 sgSetModelFilter( true );
682                 globals->get_aircraft_model()->select( false );
683                 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
684             }
685         }
686
687         // This is a bit kludgy.  Every 200 frames, do an extra
688         // traversal of the scene graph without drawing anything, but
689         // with the field-of-view set to 360x360 degrees.  This
690         // ensures that out-of-range random objects that are not in
691         // the current view frustum will still be freed properly.
692         static int counter = 0;
693         counter++;
694         if (counter == 200) {
695             sgFrustum f;
696             f.setFOV(360, 360);
697                     // No need to put the near plane too close;
698                     // this way, at least the aircraft can be
699                     // culled.
700             f.setNearFar(1000, 1000000);
701             sgMat4 m;
702             ssgGetModelviewMatrix(m);
703             FGTileMgr::set_tile_filter( true );
704             sgSetModelFilter( true );
705             globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
706             counter = 0;
707         }
708
709         // change state for lighting here
710
711         // draw runway lighting
712         glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
713         ssgSetNearFar( scene_nearplane, scene_farplane );
714
715         if ( enhanced_lighting ) {
716
717             // Enable states for drawing points with GL_extension
718             glEnable(GL_POINT_SMOOTH);
719
720             if ( distance_attenuation && glPointParameterIsSupported )
721             {
722                 // Enable states for drawing points with GL_extension
723                 glEnable(GL_POINT_SMOOTH);
724
725                 float quadratic[3] = {1.0, 0.001, 0.0000001};
726                 // makes the points fade as they move away
727                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
728                 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0); 
729             }
730
731             glPointSize(4.0);
732
733             // blending function for runway lights
734             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
735         }
736
737         glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
738         glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
739         glEnable(GL_TEXTURE_GEN_S);
740         glEnable(GL_TEXTURE_GEN_T);
741         glPolygonMode(GL_FRONT, GL_POINT);
742
743         // draw runway lighting
744         if ( draw_otw ) {
745             ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
746             ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
747         }
748
749         // change punch through and then draw taxi lighting
750         glFogf ( GL_FOG_DENSITY, fog_exp2_density );
751         // sgVec3 taxi_fog;
752         // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
753         // glFogfv ( GL_FOG_COLOR, taxi_fog );
754         if ( draw_otw ) {
755             ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
756         }
757
758         // clean up lighting
759         glPolygonMode(GL_FRONT, GL_FILL);
760         glDisable(GL_TEXTURE_GEN_S);
761         glDisable(GL_TEXTURE_GEN_T);
762
763         //static int _frame_count = 0;
764         //if (_frame_count % 30 == 0) {
765         //  printf("SSG: %s\n", ssgShowStats());
766         //}
767         //else {
768         //  ssgShowStats();
769         //}
770         //_frame_count++;
771
772
773         if ( enhanced_lighting ) {
774             if ( distance_attenuation && glPointParameterIsSupported ) {
775                 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
776                                       default_attenuation);
777             }
778
779             glPointSize(1.0);
780             glDisable(GL_POINT_SMOOTH);
781         }
782
783         // draw ground lighting
784         glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
785         if ( draw_otw ) {
786             ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
787         }
788
789         if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") ) {
790             glDisable( GL_FOG );
791             glDisable( GL_LIGHTING );
792             // cout << "drawing new clouds" << endl;
793
794             glEnable(GL_DEPTH_TEST);
795             glEnable(GL_BLEND);
796             glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
797
798             /*
799             glEnable( GL_TEXTURE_2D );
800             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
801             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
802             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
803             glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
804             */
805
806 #ifdef FG_USE_CLOUDS_3D
807             sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
808 #endif
809             glEnable( GL_FOG );
810             glEnable( GL_LIGHTING );
811             glEnable( GL_DEPTH_TEST );
812             glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
813         }
814
815         if ( draw_otw && draw_clouds ) {
816             if ( multi_pass_clouds ) {
817                 // Disable depth buffer update, draw the clouds where the
818                 //  objects overwrite the already drawn clouds, by testing
819                 //  the stencil buffer against 1
820                 glDepthMask( GL_FALSE );
821                 glStencilFunc( GL_EQUAL, 1, 1 );
822                 glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
823                 thesky->drawUpperClouds();
824                 thesky->drawLowerClouds();
825                 glDepthMask( GL_TRUE );
826                 glDisable( GL_STENCIL_TEST );
827             } else {
828                 glDepthMask( GL_FALSE );
829                 thesky->drawLowerClouds();
830                 glDepthMask( GL_TRUE );
831             }
832         }
833
834         if ( draw_otw ) {
835             FGTileMgr::set_tile_filter( false );
836             sgSetModelFilter( false );
837             globals->get_aircraft_model()->select( true );
838             globals->get_model_mgr()->draw();
839             globals->get_aircraft_model()->draw();
840             // If the view is internal, the previous line draw the 
841             //  cockpit with modified near/far clip planes and deselect
842             //  the aircraft in the global scenegraph
843             // Otherwise, it just enables the aircraft: The scenegraph
844             //  must be drawn again to see the plane.
845             ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
846             FGTileMgr::set_tile_filter( true );
847             sgSetModelFilter( true );
848             globals->get_aircraft_model()->select( true );
849         }
850
851         // display HUD && Panel
852         glDisable( GL_FOG );
853         glDisable( GL_DEPTH_TEST );
854         // glDisable( GL_CULL_FACE );
855         // glDisable( GL_TEXTURE_2D );
856
857         // update the controls subsystem
858         globals->get_controls()->update(delta_time_sec);
859
860         hud_and_panel->apply();
861         fgCockpitUpdate();
862
863         // Use the hud_and_panel ssgSimpleState for rendering the ATC output
864         // This only works properly if called before the panel call
865         if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
866             globals->get_ATC_display()->update(delta_time_sec);
867
868         // update the panel subsystem
869         if ( globals->get_current_panel() != NULL ) {
870             globals->get_current_panel()->update(delta_time_sec);
871         }
872         fgUpdate3DPanels();
873
874         // We can do translucent menus, so why not. :-)
875         menus->apply();
876         glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
877         puDisplay();
878         // glDisable ( GL_BLEND ) ;
879
880         glEnable( GL_DEPTH_TEST );
881         glEnable( GL_FOG );
882
883         // Fade out the splash screen over the first three seconds.
884         double t = globals->get_sim_time_sec();
885         if ( t <= 1.0 ) {
886             fgSplashUpdate(0.0, 1.0);
887         } else if ( t <= 3.0) {
888             fgSplashUpdate(0.0, (3.0 - t) / 2.0);
889         }
890     }
891 }
892
893
894
895 // options.cxx needs to see this for toggle_panel()
896 // Handle new window size or exposure
897 void
898 FGRenderer::resize( int width, int height ) {
899     int view_h;
900
901     if ( (!fgGetBool("/sim/virtual-cockpit"))
902          && fgPanelVisible() && idle_state == 1000 ) {
903         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
904                              globals->get_current_panel()->getYOffset()) / 768.0);
905     } else {
906         view_h = height;
907     }
908
909     glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
910
911     fgSetInt("/sim/startup/xsize", width);
912     fgSetInt("/sim/startup/ysize", height);
913     guiInitMouse(width, height);
914
915     // for all views
916     FGViewMgr *viewmgr = globals->get_viewmgr();
917     if (viewmgr) {
918       for ( int i = 0; i < viewmgr->size(); ++i ) {
919         viewmgr->get_view(i)->
920           set_aspect_ratio((float)view_h / (float)width);
921       }
922
923       ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
924                viewmgr->get_current_view()->get_v_fov() );
925
926 #ifdef FG_USE_CLOUDS_3D
927       sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
928                viewmgr->get_current_view()->get_v_fov() );
929 #endif
930     }
931
932     fgHUDReshape();
933
934 }
935
936
937 // end of renderer.cxx