1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 - 2002 Curtis L. Olson - curt@flightgear.org
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // General Public License for more details.
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #include <simgear/compiler.h>
30 #if defined(__linux__) && defined(__i386__)
31 # include <fpu_control.h>
35 #ifdef SG_MATH_EXCEPTION_CLASH
45 #include <plib/netSocket.h>
47 #include <simgear/screen/extensions.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/props/props.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51 #include <simgear/timing/sg_time.hxx>
52 #include <simgear/scene/model/animation.hxx>
53 #include <simgear/ephemeris/ephemeris.hxx>
54 #include <simgear/scene/model/placement.hxx>
55 #include <simgear/math/sg_random.h>
56 #include <simgear/scene/model/modellib.hxx>
58 #ifdef FG_USE_CLOUDS_3D
59 # include <simgear/scene/sky/clouds3d/SkySceneLoader.hpp>
60 # include <simgear/scene/sky/clouds3d/SkyUtil.hpp>
63 #include <Include/general.hxx>
64 #include <Scenery/tileentry.hxx>
65 #include <Time/light.hxx>
66 #include <Time/light.hxx>
67 #include <Aircraft/aircraft.hxx>
68 #include <Cockpit/panel.hxx>
69 #include <Cockpit/cockpit.hxx>
70 #include <Cockpit/radiostack.hxx>
71 #include <Cockpit/hud.hxx>
72 #include <Model/panelnode.hxx>
73 #include <Model/modelmgr.hxx>
74 #include <Model/acmodel.hxx>
75 #include <Scenery/scenery.hxx>
76 #include <Scenery/tilemgr.hxx>
77 #include <FDM/flight.hxx>
78 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
79 #include <FDM/ADA.hxx>
80 #include <ATC/ATCdisplay.hxx>
81 #include <ATC/ATCmgr.hxx>
82 #include <ATC/AIMgr.hxx>
83 #include <Replay/replay.hxx>
84 #include <Time/tmp.hxx>
85 #include <Time/fg_timer.hxx>
86 #include <Environment/environment_mgr.hxx>
89 #include <MultiPlayer/multiplaytxmgr.hxx>
90 #include <MultiPlayer/multiplayrxmgr.hxx>
94 #include "fg_commands.hxx"
98 float default_attenuation[3] = {1.0, 0.0, 0.0};
99 ssgSelector *ship_sel=NULL;
100 // upto 32 instances of a same object can be loaded.
101 ssgTransform *ship_pos[32];
102 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
104 ssgSelector *lightpoints_brightness = new ssgSelector;
105 ssgTransform *lightpoints_transform = new ssgTransform;
106 FGTileEntry *dummy_tile;
109 // Clip plane settings...
110 float scene_nearplane = 0.5f;
111 float scene_farplane = 120000.0f;
113 static double real_delta_time_sec = 0.0;
114 static double delta_time_sec = 0.0;
116 glPointParameterfProc glPointParameterfPtr = 0;
117 glPointParameterfvProc glPointParameterfvPtr = 0;
118 bool glPointParameterIsSupported = false;
122 # include <console.h> // -dw- for command line dialog
125 // This is a record containing a bit of global housekeeping information
128 // Specify our current idle function state. This is used to run all
129 // our initializations out of the idle callback so that we can get a
130 // splash screen up and running right away.
131 static int idle_state = 0;
132 static long global_multi_loop;
134 // fog constants. I'm a little nervous about putting actual code out
135 // here but it seems to work (?)
136 static const double m_log01 = -log( 0.01 );
137 static const double sqrt_m_log01 = sqrt( m_log01 );
138 static GLfloat fog_exp_density;
139 static GLfloat fog_exp2_density;
140 static GLfloat rwy_exp2_punch_through;
141 static GLfloat taxi_exp2_punch_through;
142 static GLfloat ground_exp2_punch_through;
147 #ifdef FG_USE_CLOUDS_3D
148 SkySceneLoader *sgClouds3d;
149 bool _bcloud_orig = true;
153 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
155 { 1.0f, 0.0f, 0.0f, 0.0f },
156 { 0.0f, 0.0f, -1.0f, 0.0f },
157 { 0.0f, 1.0f, 0.0f, 0.0f },
158 { 0.0f, 0.0f, 0.0f, 1.0f }
161 ssgSimpleState *cloud3d_imposter_state;
162 ssgSimpleState *default_state;
163 ssgSimpleState *hud_and_panel;
164 ssgSimpleState *menus;
166 SGTimeStamp last_time_stamp;
167 SGTimeStamp current_time_stamp;
170 void fgBuildRenderStates( void ) {
171 default_state = new ssgSimpleState;
172 default_state->ref();
173 default_state->disable( GL_TEXTURE_2D );
174 default_state->enable( GL_CULL_FACE );
175 default_state->enable( GL_COLOR_MATERIAL );
176 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
177 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
178 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
179 default_state->disable( GL_BLEND );
180 default_state->disable( GL_ALPHA_TEST );
181 default_state->disable( GL_LIGHTING );
183 cloud3d_imposter_state = new ssgSimpleState;
184 cloud3d_imposter_state->ref();
185 cloud3d_imposter_state->enable( GL_TEXTURE_2D );
186 cloud3d_imposter_state->enable( GL_CULL_FACE );
187 cloud3d_imposter_state->enable( GL_COLOR_MATERIAL );
188 cloud3d_imposter_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
189 cloud3d_imposter_state->setMaterial( GL_DIFFUSE, 1, 1, 1, 1 );
190 cloud3d_imposter_state->setMaterial( GL_AMBIENT, 1, 1, 1, 1 );
191 cloud3d_imposter_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
192 cloud3d_imposter_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
193 cloud3d_imposter_state->enable( GL_BLEND );
194 cloud3d_imposter_state->enable( GL_ALPHA_TEST );
195 cloud3d_imposter_state->disable( GL_LIGHTING );
197 hud_and_panel = new ssgSimpleState;
198 hud_and_panel->ref();
199 hud_and_panel->disable( GL_CULL_FACE );
200 hud_and_panel->disable( GL_TEXTURE_2D );
201 hud_and_panel->disable( GL_LIGHTING );
202 hud_and_panel->enable( GL_BLEND );
204 menus = new ssgSimpleState;
206 menus->disable( GL_CULL_FACE );
207 menus->disable( GL_TEXTURE_2D );
208 menus->enable( GL_BLEND );
212 // fgInitVisuals() -- Initialize various GL/view parameters
213 void fgInitVisuals( void ) {
215 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
217 // Go full screen if requested ...
218 if ( fgGetBool("/sim/startup/fullscreen") ) {
222 // If enabled, normal vectors specified with glNormal are scaled
223 // to unit length after transformation. Enabling this has
224 // performance implications. See the docs for glNormal.
225 // glEnable( GL_NORMALIZE );
227 glEnable( GL_LIGHTING );
228 glEnable( GL_LIGHT0 );
229 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
232 sgSetVec3( sunpos, l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2] );
233 ssgGetLight( 0 ) -> setPosition( sunpos );
235 glFogi (GL_FOG_MODE, GL_EXP2);
236 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
237 (!fgGetBool("/sim/rendering/shading"))) {
238 // if fastest fog requested, or if flat shading force fastest
239 glHint ( GL_FOG_HINT, GL_FASTEST );
240 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
241 glHint ( GL_FOG_HINT, GL_NICEST );
243 if ( fgGetBool("/sim/rendering/wireframe") ) {
245 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
248 // This is the default anyways, but it can't hurt
249 glFrontFace ( GL_CCW );
252 // glEnable(GL_POINT_SMOOTH);
253 // glEnable(GL_LINE_SMOOTH);
254 // glEnable(GL_POLYGON_SMOOTH);
258 // For HiRes screen Dumps using Brian Pauls TR Library
259 void trRenderFrame( void ) {
261 if ( fgPanelVisible() ) {
262 GLfloat height = fgGetInt("/sim/startup/ysize");
264 (globals->get_current_panel()->getViewHeight() - globals->get_current_panel()->getYOffset())
265 * (height / 768.0) + 1;
266 glTranslatef( 0.0, view_h, 0.0 );
269 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
270 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
272 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
274 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
275 l->adj_fog_color()[2], l->adj_fog_color()[3]);
277 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
279 // set the opengl state to known default values
280 default_state->force();
283 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
284 glFogi ( GL_FOG_MODE, GL_EXP2 );
285 glFogfv ( GL_FOG_COLOR, l->adj_fog_color() );
287 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
288 // we only update GL_AMBIENT for our lights we will never get
289 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
290 // explicitely to black.
291 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
292 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
294 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
296 // texture parameters
297 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
298 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
300 // we need a white diffuse light for the phase of the moon
301 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
302 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
304 // draw the ssg scene
305 // return to the desired diffuse color
306 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
307 glEnable( GL_DEPTH_TEST );
308 ssgSetNearFar( scene_nearplane, scene_farplane );
309 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
312 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
313 ssgSetNearFar( scene_nearplane, scene_farplane );
314 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
315 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
317 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
319 if (fgGetBool("/environment/clouds/status"))
320 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
322 globals->get_model_mgr()->draw();
323 globals->get_aircraft_model()->draw();
327 // Update all Visuals (redraws anything graphics related)
328 void fgRenderFrame() {
329 bool draw_otw = fgGetBool("/sim/rendering/draw-otw");
330 bool skyblend = fgGetBool("/sim/rendering/skyblend");
331 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
332 bool distance_attenuation = fgGetBool("/sim/rendering/distance-attenuation");
334 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
335 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
337 // static const SGPropertyNode *longitude
338 // = fgGetNode("/position/longitude-deg");
339 // static const SGPropertyNode *latitude
340 // = fgGetNode("/position/latitude-deg");
341 // static const SGPropertyNode *altitude
342 // = fgGetNode("/position/altitude-ft");
343 static const SGPropertyNode *groundlevel_nearplane
344 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
346 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
347 static double last_visibility = -9999;
350 double actual_visibility;
351 if (fgGetBool("/environment/clouds/status"))
352 actual_visibility = thesky->get_visibility();
354 actual_visibility = fgGetDouble("/environment/visibility-m");
355 if ( actual_visibility != last_visibility ) {
356 last_visibility = actual_visibility;
358 fog_exp_density = m_log01 / actual_visibility;
359 fog_exp2_density = sqrt_m_log01 / actual_visibility;
360 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
361 if ( actual_visibility < 8000 ) {
362 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
363 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
365 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
366 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
371 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
372 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
373 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
374 // GLfloat mat_shininess[] = { 10.0 };
375 GLbitfield clear_mask;
377 if ( idle_state != 1000 ) {
378 // still initializing, draw the splash screen
379 if ( fgGetBool("/sim/startup/splash-screen") ) {
380 fgSplashUpdate(0.0, 1.0);
382 // Keep resetting sim time while the sim is initializing
383 globals->set_sim_time_sec( 0.0 );
384 SGAnimation::set_sim_time_sec( 0.0 );
386 // idle_state is now 1000 meaning we've finished all our
387 // initializations and are running the main loop, so this will
388 // now work without seg faulting the system.
390 FGViewer *current__view = globals->get_current_view();
392 // calculate our current position in cartesian space
393 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
396 fgReshape( fgGetInt("/sim/startup/xsize"),
397 fgGetInt("/sim/startup/ysize") );
399 if ( fgGetBool("/sim/rendering/clouds3d") ) {
400 glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT );
401 cloud3d_imposter_state->force();
403 glColor4f( 1.0, 1.0, 1.0, 1.0 );
404 glEnable(GL_DEPTH_TEST);
406 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
408 #ifdef FG_USE_CLOUDS_3D
409 if ( _bcloud_orig ) {
410 Point3D c = globals->get_scenery()->get_center();
411 sgClouds3d->Set_Cloud_Orig( &c );
412 _bcloud_orig = false;
414 sgClouds3d->Update( current__view->get_absolute_view_pos() );
416 glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
417 glDisable(GL_DEPTH_TEST);
420 clear_mask = GL_DEPTH_BUFFER_BIT;
421 if ( fgGetBool("/sim/rendering/wireframe") ) {
422 clear_mask |= GL_COLOR_BUFFER_BIT;
426 if ( fgGetBool("/sim/rendering/textures") ) {
427 // glClearColor(black[0], black[1], black[2], black[3]);
428 glClearColor(l->adj_fog_color()[0], l->adj_fog_color()[1],
429 l->adj_fog_color()[2], l->adj_fog_color()[3]);
430 clear_mask |= GL_COLOR_BUFFER_BIT;
433 glClearColor(l->sky_color()[0], l->sky_color()[1],
434 l->sky_color()[2], l->sky_color()[3]);
435 clear_mask |= GL_COLOR_BUFFER_BIT;
437 glClear( clear_mask );
439 // Tell GL we are switching to model view parameters
441 // I really should create a derived ssg node or use a call
442 // back or something so that I can draw the sky within the
443 // ssgCullAndDraw() function, but for now I just mimic what
444 // ssg does to set up the model view matrix
445 glMatrixMode(GL_MODELVIEW);
447 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
449 // set the opengl state to known default values
450 default_state->force();
452 // update fog params if visibility has changed
453 double visibility_meters = fgGetDouble("/environment/visibility-m");
454 thesky->set_visibility(visibility_meters);
456 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
457 ( global_multi_loop * fgGetInt("/sim/speed-up") )
458 / (double)fgGetInt("/sim/model-hz") );
460 // Set correct opengl fog density
461 glFogf (GL_FOG_DENSITY, fog_exp2_density);
463 // update the sky dome
466 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
467 << l->sky_color()[0] << " "
468 << l->sky_color()[1] << " "
469 << l->sky_color()[2] << " "
470 << l->sky_color()[3] );
471 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
472 << l->fog_color()[0] << " "
473 << l->fog_color()[1] << " "
474 << l->fog_color()[2] << " "
475 << l->fog_color()[3] );
476 SG_LOG( SG_GENERAL, SG_BULK,
477 " sun_angle = " << l->sun_angle
478 << " moon_angle = " << l->moon_angle );
481 static SGSkyColor scolor;
482 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
484 scolor.sky_color = l->sky_color();
485 scolor.fog_color = l->adj_fog_color();
486 scolor.cloud_color = l->cloud_color();
487 scolor.sun_angle = l->get_sun_angle();
488 scolor.moon_angle = l->get_moon_angle();
489 scolor.nplanets = globals->get_ephem()->getNumPlanets();
490 scolor.nstars = globals->get_ephem()->getNumStars();
491 scolor.planet_data = globals->get_ephem()->getPlanets();
492 scolor.star_data = globals->get_ephem()->getStars();
494 thesky->repaint( scolor );
497 SG_LOG( SG_GENERAL, SG_BULK,
498 "thesky->reposition( view_pos = " << view_pos[0] << " "
499 << view_pos[1] << " " << view_pos[2] );
500 SG_LOG( SG_GENERAL, SG_BULK,
501 " zero_elev = " << zero_elev[0] << " "
502 << zero_elev[1] << " " << zero_elev[2]
503 << " lon = " << cur_fdm_state->get_Longitude()
504 << " lat = " << cur_fdm_state->get_Latitude() );
505 SG_LOG( SG_GENERAL, SG_BULK,
506 " sun_rot = " << l->get_sun_rotation
507 << " gst = " << SGTime::cur_time_params->getGst() );
508 SG_LOG( SG_GENERAL, SG_BULK,
509 " sun ra = " << globals->get_ephem()->getSunRightAscension()
510 << " sun dec = " << globals->get_ephem()->getSunDeclination()
511 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
512 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
515 // The sun and moon distances are scaled down versions
516 // of the actual distance to get both the moon and the sun
517 // within the range of the far clip plane.
518 // Moon distance: 384,467 kilometers
519 // Sun distance: 150,000,000 kilometers
520 double sun_horiz_eff, moon_horiz_eff;
521 if (fgGetBool("/sim/rendering/horizon-effect")) {
522 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
523 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
525 sun_horiz_eff = moon_horiz_eff = 1.0;
528 static SGSkyState sstate;
530 sstate.view_pos = current__view->get_view_pos();
531 sstate.zero_elev = current__view->get_zero_elev();
532 sstate.view_up = current__view->get_world_up();
533 sstate.lon = current__view->getLongitude_deg()
534 * SGD_DEGREES_TO_RADIANS;
535 sstate.lat = current__view->getLatitude_deg()
536 * SGD_DEGREES_TO_RADIANS;
537 sstate.alt = current__view->getAltitudeASL_ft()
539 sstate.spin = l->get_sun_rotation();
540 sstate.gst = globals->get_time_params()->getGst();
541 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
542 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
543 sstate.sun_dist = 50000.0 * sun_horiz_eff;
544 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
545 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
546 sstate.moon_dist = 40000.0 * moon_horiz_eff;
548 thesky->reposition( sstate, delta_time_sec );
551 glEnable( GL_DEPTH_TEST );
552 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
554 glFogi( GL_FOG_MODE, GL_EXP2 );
555 glFogfv( GL_FOG_COLOR, l->adj_fog_color() );
558 // set sun/lighting parameters
559 ssgGetLight( 0 ) -> setPosition( l->sun_vec() );
561 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
562 // we only update GL_AMBIENT for our lights we will never get
563 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
564 // explicitely to black.
565 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
567 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient() );
568 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
569 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular() );
571 // texture parameters
572 // glEnable( GL_TEXTURE_2D );
573 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
574 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
576 // glMatrixMode( GL_PROJECTION );
578 ssgSetFOV( current__view->get_h_fov(),
579 current__view->get_v_fov() );
582 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
583 - globals->get_scenery()->get_cur_elev();
586 scene_nearplane = 10.0f;
587 scene_farplane = 120000.0f;
589 scene_nearplane = groundlevel_nearplane->getDoubleValue();
590 scene_farplane = 120000.0f;
593 ssgSetNearFar( scene_nearplane, scene_farplane );
596 // Update any multiplayer models
597 globals->get_multiplayer_rx_mgr()->Update();
600 if ( draw_otw && skyblend )
602 // draw the sky backdrop
604 // we need a white diffuse light for the phase of the moon
605 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
607 thesky->preDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER, fog_exp2_density );
609 // return to the desired diffuse color
610 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse() );
613 // draw the ssg scene
614 glEnable( GL_DEPTH_TEST );
616 ssgSetNearFar( scene_nearplane, scene_farplane );
618 if ( fgGetBool("/sim/rendering/wireframe") ) {
620 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
623 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
626 // This is a bit kludgy. Every 200 frames, do an extra
627 // traversal of the scene graph without drawing anything, but
628 // with the field-of-view set to 360x360 degrees. This
629 // ensures that out-of-range random objects that are not in
630 // the current view frustum will still be freed properly.
631 static int counter = 0;
633 if (counter == 200) {
636 // No need to put the near plane too close;
637 // this way, at least the aircraft can be
639 f.setNearFar(1000, 1000000);
641 ssgGetModelviewMatrix(m);
642 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
646 // change state for lighting here
648 // draw runway lighting
649 glFogf (GL_FOG_DENSITY, rwy_exp2_punch_through);
650 ssgSetNearFar( scene_nearplane, scene_farplane );
652 if ( enhanced_lighting ) {
654 // Enable states for drawing points with GL_extension
655 glEnable(GL_POINT_SMOOTH);
657 if ( distance_attenuation && glPointParameterIsSupported )
659 // Enable states for drawing points with GL_extension
660 glEnable(GL_POINT_SMOOTH);
662 float quadratic[3] = {1.0, 0.001, 0.0000001};
663 // makes the points fade as they move away
664 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT, quadratic);
665 glPointParameterfPtr(GL_POINT_SIZE_MIN_EXT, 1.0);
670 // blending function for runway lights
671 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
674 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
675 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
676 glEnable(GL_TEXTURE_GEN_S);
677 glEnable(GL_TEXTURE_GEN_T);
678 glPolygonMode(GL_FRONT, GL_POINT);
680 // draw runway lighting
682 ssgCullAndDraw( globals->get_scenery()->get_vasi_lights_root() );
683 ssgCullAndDraw( globals->get_scenery()->get_rwy_lights_root() );
686 // change punch through and then draw taxi lighting
687 glFogf ( GL_FOG_DENSITY, fog_exp2_density );
689 // sgSetVec3( taxi_fog, 0.0, 0.0, 0.0 );
690 // glFogfv ( GL_FOG_COLOR, taxi_fog );
692 ssgCullAndDraw( globals->get_scenery()->get_taxi_lights_root() );
696 glPolygonMode(GL_FRONT, GL_FILL);
697 glDisable(GL_TEXTURE_GEN_S);
698 glDisable(GL_TEXTURE_GEN_T);
700 //static int _frame_count = 0;
701 //if (_frame_count % 30 == 0) {
702 // printf("SSG: %s\n", ssgShowStats());
710 if ( enhanced_lighting ) {
711 if ( distance_attenuation && glPointParameterIsSupported )
713 glPointParameterfvPtr(GL_DISTANCE_ATTENUATION_EXT,
714 default_attenuation);
718 glDisable(GL_POINT_SMOOTH);
721 // draw ground lighting
722 glFogf (GL_FOG_DENSITY, ground_exp2_punch_through);
724 ssgCullAndDraw( globals->get_scenery()->get_gnd_lights_root() );
728 // draw the sky cloud layers
729 if ( draw_otw && fgGetBool("/environment/clouds/status") )
731 thesky->postDraw( cur_fdm_state->get_Altitude()
732 * SG_FEET_TO_METER );
736 if ( draw_otw && fgGetBool("/sim/rendering/clouds3d") )
739 glDisable( GL_LIGHTING );
740 // cout << "drawing new clouds" << endl;
742 glEnable(GL_DEPTH_TEST);
744 glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA ) ;
747 glEnable( GL_TEXTURE_2D );
748 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
749 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
750 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
751 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
754 #ifdef FG_USE_CLOUDS_3D
755 sgClouds3d->Draw((sgVec4 *)current__view->get_VIEW());
758 glEnable( GL_LIGHTING );
759 glEnable( GL_DEPTH_TEST );
760 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
764 globals->get_model_mgr()->draw();
765 globals->get_aircraft_model()->draw();
768 // display HUD && Panel
770 glDisable( GL_DEPTH_TEST );
771 // glDisable( GL_CULL_FACE );
772 // glDisable( GL_TEXTURE_2D );
774 // update the controls subsystem
775 globals->get_controls()->update(delta_time_sec);
777 hud_and_panel->apply();
780 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
781 // This only works properly if called before the panel call
782 if((fgGetBool("/sim/ATC/enabled")) || (fgGetBool("/sim/ai-traffic/enabled")))
783 globals->get_ATC_display()->update(delta_time_sec);
785 // update the panel subsystem
786 if ( globals->get_current_panel() != NULL ) {
787 globals->get_current_panel()->update(delta_time_sec);
791 // We can do translucent menus, so why not. :-)
793 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
795 // glDisable ( GL_BLEND ) ;
797 glEnable( GL_DEPTH_TEST );
800 // Fade out the splash screen over the first three seconds.
801 double t = globals->get_sim_time_sec();
803 fgSplashUpdate(0.0, 1.0);
804 } else if ( t <= 3.0) {
805 fgSplashUpdate(0.0, (3.0 - t) / 2.0);
811 // Update internal time dependent calculations (i.e. flight model)
812 // FIXME: this distinction is obsolete; all subsystems now get delta
814 void fgUpdateTimeDepCalcs() {
815 static bool inited = false;
817 static const SGPropertyNode *replay_master
818 = fgGetNode( "/sim/freeze/replay", true );
819 static SGPropertyNode *replay_time
820 = fgGetNode( "/sim/replay/time", true );
821 // static const SGPropertyNode *replay_end_time
822 // = fgGetNode( "/sim/replay/end-time", true );
824 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
826 // Initialize the FDM here if it hasn't been and if we have a
827 // scenery elevation hit.
829 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
830 // << " cur_elev = " << scenery.get_cur_elev() << endl;
832 if ( !cur_fdm_state->get_inited() &&
833 globals->get_scenery()->get_cur_elev() > -9990 )
835 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
836 cur_fdm_state->init();
837 if ( cur_fdm_state->get_bound() ) {
838 cur_fdm_state->unbind();
840 cur_fdm_state->bind();
843 // conceptually, the following block could be done for each fdm
845 if ( cur_fdm_state->get_inited() ) {
846 // we have been inited, and we are good to go ...
852 if ( ! replay_master->getBoolValue() ) {
853 cur_fdm_state->update( delta_time_sec );
855 FGReplay *r = (FGReplay *)(globals->get_subsystem( "replay" ));
856 r->replay( replay_time->getDoubleValue() );
857 replay_time->setDoubleValue( replay_time->getDoubleValue()
859 * fgGetInt("/sim/speed-up") ) );
862 // do nothing, fdm isn't inited yet
865 globals->get_model_mgr()->update(delta_time_sec);
866 globals->get_aircraft_model()->update(delta_time_sec);
868 // update the view angle
869 globals->get_viewmgr()->update(delta_time_sec);
871 // Update solar system
872 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
873 globals->get_time_params()->getLst(),
874 cur_fdm_state->get_Latitude() );
876 // Update radio stack model
877 current_radiostack->update(delta_time_sec);
881 void fgInitTimeDepCalcs( void ) {
886 static const double alt_adjust_ft = 3.758099;
887 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
890 // What should we do when we have nothing else to do? Let's get ready
891 // for the next move and update the display?
892 static void fgMainLoop( void ) {
893 int model_hz = fgGetInt("/sim/model-hz");
895 static const SGPropertyNode *longitude
896 = fgGetNode("/position/longitude-deg");
897 static const SGPropertyNode *latitude
898 = fgGetNode("/position/latitude-deg");
899 static const SGPropertyNode *altitude
900 = fgGetNode("/position/altitude-ft");
901 static const SGPropertyNode *clock_freeze
902 = fgGetNode("/sim/freeze/clock", true);
903 static const SGPropertyNode *cur_time_override
904 = fgGetNode("/sim/time/cur-time-override", true);
905 // static const SGPropertyNode *replay_master
906 // = fgGetNode("/sim/freeze/replay", true);
908 // Update the elapsed time.
909 static bool first_time = true;
911 last_time_stamp.stamp();
915 double throttle_hz = fgGetDouble("/sim/frame-rate-throttle-hz", 0.0);
916 if ( throttle_hz > 0.0 ) {
917 // simple frame rate throttle
918 double dt = 1000000.0 / throttle_hz;
919 current_time_stamp.stamp();
920 while ( current_time_stamp - last_time_stamp < dt ) {
921 current_time_stamp.stamp();
924 // run as fast as the app will go
925 current_time_stamp.stamp();
929 = double(current_time_stamp - last_time_stamp) / 1000000.0;
930 if ( clock_freeze->getBoolValue() ) {
933 delta_time_sec = real_delta_time_sec;
935 last_time_stamp = current_time_stamp;
936 globals->inc_sim_time_sec( delta_time_sec );
937 SGAnimation::set_sim_time_sec( globals->get_sim_time_sec() );
939 // These are useful, especially for Nasal scripts.
940 fgSetDouble("/sim/time/delta-realtime-sec", real_delta_time_sec);
941 fgSetDouble("/sim/time/delta-sec", delta_time_sec);
943 static long remainder = 0;
945 #ifdef FANCY_FRAME_COUNTER
949 static time_t last_time = 0;
950 static int frames = 0;
951 #endif // FANCY_FRAME_COUNTER
953 SGTime *t = globals->get_time_params();
955 globals->get_event_mgr()->update(delta_time_sec);
957 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
958 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
960 #if defined( ENABLE_PLIB_JOYSTICK )
961 // Read joystick and update control settings
962 // if ( fgGetString("/sim/control-mode") == "joystick" )
968 // Fix elevation. I'm just sticking this here for now, it should
969 // probably move eventually
971 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
972 scenery.get_cur_elev(),
973 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
974 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
976 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
977 scenery.get_cur_elev(),
978 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
979 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
981 // cout << "Warp = " << globals->get_warp() << endl;
984 static bool last_clock_freeze = false;
986 if ( clock_freeze->getBoolValue() ) {
987 // clock freeze requested
988 if ( cur_time_override->getLongValue() == 0 ) {
989 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
990 globals->set_warp( 0 );
993 // no clock freeze requested
994 if ( last_clock_freeze == true ) {
995 // clock just unfroze, let's set warp as the difference
996 // between frozen time and current time so we don't get a
997 // time jump (and corresponding sky object and lighting
999 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1000 fgSetLong( "/sim/time/cur-time-override", 0 );
1002 if ( globals->get_warp_delta() != 0 ) {
1003 globals->inc_warp( globals->get_warp_delta() );
1007 last_clock_freeze = clock_freeze->getBoolValue();
1009 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1010 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1011 cur_time_override->getLongValue(),
1012 globals->get_warp() );
1014 if (globals->get_warp_delta() != 0) {
1015 FGLight *l = (FGLight *)(globals->get_subsystem("lighting"));
1019 // update magvar model
1020 globals->get_mag()->update( longitude->getDoubleValue()
1021 * SGD_DEGREES_TO_RADIANS,
1022 latitude->getDoubleValue()
1023 * SGD_DEGREES_TO_RADIANS,
1024 altitude->getDoubleValue() * SG_FEET_TO_METER,
1025 globals->get_time_params()->getJD() );
1027 // Get elapsed time (in usec) for this past frame
1028 elapsed = fgGetTimeInterval();
1029 SG_LOG( SG_ALL, SG_DEBUG,
1030 "Elapsed time interval is = " << elapsed
1031 << ", previous remainder is = " << remainder );
1033 // Calculate frame rate average
1034 #ifdef FANCY_FRAME_COUNTER
1035 /* old fps calculation */
1036 if ( elapsed > 0 ) {
1039 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1040 tmp = general.get_frame(i);
1042 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1043 general.set_frame(i+1,tmp);
1045 tmp = 1000000.0 / (float)elapsed;
1046 general.set_frame(0,tmp);
1047 // printf("frame[0] = %.2f\n", general.frames[0]);
1049 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1050 // printf("ave = %.2f\n", general.frame_rate);
1053 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1054 general.set_frame_rate( frames );
1055 fgSetInt("/sim/frame-rate", frames);
1056 SG_LOG( SG_ALL, SG_DEBUG,
1057 "--> Frame rate is = " << general.get_frame_rate() );
1060 last_time = t->get_cur_time();
1064 // Run ATC subsystem
1065 if (fgGetBool("/sim/ATC/enabled"))
1066 globals->get_ATC_mgr()->update(delta_time_sec);
1068 // Run the AI subsystem
1069 if (fgGetBool("/sim/ai-traffic/enabled"))
1070 globals->get_AI_mgr()->update(delta_time_sec);
1074 // Calculate model iterations needed for next frame
1075 elapsed += remainder;
1077 global_multi_loop = (long)(((double)elapsed * 0.000001) * model_hz );
1078 remainder = elapsed - ( (global_multi_loop*1000000) / model_hz );
1079 SG_LOG( SG_ALL, SG_DEBUG,
1080 "Model iterations needed = " << global_multi_loop
1081 << ", new remainder = " << remainder );
1083 // chop max interations to something reasonable if the sim was
1084 // delayed for an excesive amount of time
1085 if ( global_multi_loop > 2.0 * model_hz ) {
1086 global_multi_loop = (int)(2.0 * model_hz );
1091 if ( global_multi_loop > 0 ) {
1092 fgUpdateTimeDepCalcs();
1094 SG_LOG( SG_ALL, SG_DEBUG,
1095 "Elapsed time is zero ... we're zinging" );
1098 // Do any I/O channel work that might need to be done
1099 globals->get_io()->update( real_delta_time_sec );
1101 // see if we need to load any deferred-load textures
1102 globals->get_matlib()->load_next_deferred();
1104 // Run audio scheduler
1105 #ifdef ENABLE_AUDIO_SUPPORT
1106 if ( fgGetBool("/sim/sound/audible")
1107 && globals->get_soundmgr()->is_working() ) {
1108 globals->get_soundmgr()->update( delta_time_sec );
1112 globals->get_subsystem_mgr()->update(delta_time_sec);
1115 // Tile Manager updates - see if we need to load any new scenery tiles.
1116 // this code ties together the fdm, viewer and scenery classes...
1117 // we may want to move this to it's own class at some point
1119 double visibility_meters = fgGetDouble("/environment/visibility-m");
1120 FGViewer *current_view = globals->get_current_view();
1122 // get the location data for the primary FDM (now hardcoded to ac model)...
1123 SGLocation * acmodel_location = 0;
1124 acmodel_location = (SGLocation *) globals->get_aircraft_model()->get3DModel()->getSGLocation();
1126 // update tile manager for FDM...
1127 // ...only if location is different than the current-view location (to avoid duplicating effort)
1128 if( !fgGetBool("/sim/current-view/config/from-model") ) {
1129 if( acmodel_location != 0 ) {
1130 globals->get_tile_mgr()->prep_ssg_nodes( acmodel_location,
1131 visibility_meters );
1132 globals->get_tile_mgr()->
1133 update( acmodel_location, visibility_meters,
1134 acmodel_location->get_absolute_view_pos(globals->get_scenery()->get_center()) );
1135 // save results of update in SGLocation for fdm...
1136 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1138 set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1139 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1142 set_tile_center( globals->get_scenery()->get_next_center() );
1146 globals->get_tile_mgr()->prep_ssg_nodes( current_view->getSGLocation(),
1147 visibility_meters );
1148 // update tile manager for view...
1149 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1150 // after the FDM's until all of Flight Gear code references the viewer's location
1151 // for elevation instead of the "scenery's" current elevation.
1152 SGLocation *view_location = globals->get_current_view()->getSGLocation();
1153 globals->get_tile_mgr()->update( view_location, visibility_meters,
1154 current_view->get_absolute_view_pos() );
1155 // save results of update in SGLocation for fdm...
1156 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1157 current_view->getSGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1159 current_view->getSGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1161 // If fdm location is same as viewer's then we didn't do the update for fdm location
1162 // above so we need to save the viewer results in the fdm SGLocation as well...
1163 if( fgGetBool("/sim/current-view/config/from-model") ) {
1164 if( acmodel_location != 0 ) {
1165 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1166 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1167 fgSetDouble("/position/ground-elev-m", globals->get_scenery()->get_cur_elev());
1169 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1173 // END Tile Manager udpates
1175 if (fgGetBool("/sim/rendering/specular-highlight")) {
1176 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SEPARATE_SPECULAR_COLOR);
1177 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
1179 glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL, GL_SINGLE_COLOR);
1180 // glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
1185 SG_LOG( SG_ALL, SG_DEBUG, "" );
1189 // This is the top level master main function that is registered as
1190 // our idle funciton
1192 // The first few passes take care of initialization things (a couple
1193 // per pass) and once everything has been initialized fgMainLoop from
1196 static void fgIdleFunction ( void ) {
1197 // printf("idle state == %d\n", idle_state);
1199 if ( idle_state == 0 ) {
1200 // Initialize the splash screen right away
1201 if ( fgGetBool("/sim/startup/splash-screen") ) {
1202 fgSplashInit(fgGetString("/sim/startup/splash-texture"));
1206 } else if ( idle_state == 1 ) {
1207 // Initialize audio support
1208 #ifdef ENABLE_AUDIO_SUPPORT
1210 // Start the intro music
1211 if ( fgGetBool("/sim/startup/intro-music") ) {
1212 SGPath mp3file( globals->get_fg_root() );
1213 mp3file.append( "Sounds/intro.mp3" );
1215 SG_LOG( SG_GENERAL, SG_INFO,
1216 "Starting intro music: " << mp3file.str() );
1218 #if defined( __CYGWIN__ )
1219 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1220 #elif defined( WIN32 )
1221 string command = "start /m " + mp3file.str();
1223 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1226 system ( command.c_str() );
1231 } else if ( idle_state == 2 ) {
1232 // These are a few miscellaneous things that aren't really
1233 // "subsystems" but still need to be initialized.
1236 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1237 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1242 } else if ( idle_state == 3 ) {
1243 // This is the top level init routine which calls all the
1244 // other subsystem initialization routines. If you are adding
1245 // a subsystem to flightgear, its initialization call should
1246 // located in this routine.
1247 if( !fgInitSubsystems()) {
1248 SG_LOG( SG_GENERAL, SG_ALERT,
1249 "Subsystem initializations failed ..." );
1254 } else if ( idle_state == 4 ) {
1255 // Initialize the time offset (warp) after fgInitSubsystem
1256 // (which initializes the lighting interpolation tables.)
1259 // setup OpenGL view parameters
1262 // Read the list of available aircrafts
1266 } else if ( idle_state == 5 ) {
1269 } else if ( idle_state == 6 ) {
1274 SG_LOG( SG_GENERAL, SG_INFO, "Panel visible = " << fgPanelVisible() );
1275 fgReshape( fgGetInt("/sim/startup/xsize"),
1276 fgGetInt("/sim/startup/ysize") );
1280 if ( idle_state == 1000 ) {
1281 // We've finished all our initialization steps, from now on we
1282 // run the main loop.
1284 fgRegisterIdleHandler(fgMainLoop);
1286 if ( fgGetBool("/sim/startup/splash-screen") ) {
1287 fgSplashUpdate(0.0, 1.0);
1292 // options.cxx needs to see this for toggle_panel()
1293 // Handle new window size or exposure
1294 void fgReshape( int width, int height ) {
1297 if ( (!fgGetBool("/sim/virtual-cockpit"))
1298 && fgPanelVisible() && idle_state == 1000 ) {
1299 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
1300 globals->get_current_panel()->getYOffset()) / 768.0);
1305 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1307 fgSetInt("/sim/startup/xsize", width);
1308 fgSetInt("/sim/startup/ysize", height);
1309 guiInitMouse(width, height);
1312 FGViewMgr *viewmgr = globals->get_viewmgr();
1314 for ( int i = 0; i < viewmgr->size(); ++i ) {
1315 viewmgr->get_view(i)->
1316 set_aspect_ratio((float)view_h / (float)width);
1319 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1320 viewmgr->get_current_view()->get_v_fov() );
1322 #ifdef FG_USE_CLOUDS_3D
1323 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1324 viewmgr->get_current_view()->get_v_fov() );
1332 // Main top level initialization
1333 bool fgMainInit( int argc, char **argv ) {
1335 #if defined( macintosh )
1336 freopen ("stdout.txt", "w", stdout );
1337 freopen ("stderr.txt", "w", stderr );
1338 argc = ccommand( &argv );
1341 // set default log levels
1342 sglog().setLogLevels( SG_ALL, SG_ALERT );
1345 #ifdef FLIGHTGEAR_VERSION
1346 version = FLIGHTGEAR_VERSION;
1348 version = "unknown version";
1350 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1352 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1354 // Allocate global data structures. This needs to happen before
1355 // we parse command line options
1357 globals = new FGGlobals;
1359 // seed the random number generater
1362 FGControls *controls = new FGControls;
1363 globals->set_controls( controls );
1365 string_list *col = new string_list;
1366 globals->set_channel_options_list( col );
1368 // Scan the config file(s) and command line options to see if
1369 // fg_root was specified (ignore all other options for now)
1370 fgInitFGRoot(argc, argv);
1372 // Check for the correct base package version
1373 static char required_version[] = "0.9.4";
1374 string base_version = fgBasePackageVersion();
1375 if ( !(base_version == required_version) ) {
1376 // tell the operator how to use this application
1378 SG_LOG( SG_GENERAL, SG_ALERT, endl << "Base package check failed ... " \
1379 << "Found version " << base_version << " at: " \
1380 << globals->get_fg_root() );
1381 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version: " << required_version );
1383 SG_LOG( SG_GENERAL, SG_ALERT, "Hit a key to continue..." );
1389 // Initialize the Aircraft directory to "" (UIUC)
1392 // Load the configuration parameters. (Command line options
1393 // overrides config file options. Config file options override
1395 if ( !fgInitConfig(argc, argv) ) {
1396 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1400 // Initialize the Window/Graphics environment.
1401 #if !defined(__APPLE__) || defined(OSX_BUNDLE)
1402 // Mac OS X command line ("non-bundle") applications call this
1403 // from main(), in bootstrap.cxx. Andy doesn't know why, someone
1404 // feel free to add comments...
1405 fgOSInit(&argc, argv);
1408 fgRegisterWindowResizeHandler( fgReshape );
1409 fgRegisterIdleHandler( fgIdleFunction );
1410 fgRegisterDrawHandler( fgRenderFrame );
1412 // Clouds3D requires an alpha channel
1413 fgOSOpenWindow( fgGetInt("/sim/startup/xsize"),
1414 fgGetInt("/sim/startup/ysize"),
1415 fgGetBool("/sim/rendering/clouds3d") );
1417 // This seems to be the absolute earliest in the init sequence
1418 // that these calls will return valid info. Too bad it's after
1419 // we've already created and sized out window. :-(
1420 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1421 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1422 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1423 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1426 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1427 general.set_glMaxTexSize( tmp );
1428 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1430 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1431 general.set_glDepthBits( tmp );
1432 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1434 // Initialize plib net interface
1435 netInit( &argc, argv );
1437 // Initialize ssg (from plib). Needs to come before we do any
1438 // other ssg stuff, but after opengl has been initialized.
1441 // Initialize the user interface (we need to do this before
1442 // passing off control to the OS main loop and before
1443 // fgInitGeneral to get our fonts !!!
1446 // Read the list of available aircrafts
1449 #ifdef GL_EXT_texture_lod_bias
1450 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1453 // get the address of our OpenGL extensions
1454 if ( fgGetBool("/sim/rendering/distance-attenuation") )
1456 if (SGIsOpenGLExtensionSupported("GL_EXT_point_parameters") ) {
1457 glPointParameterIsSupported = true;
1458 glPointParameterfPtr = (glPointParameterfProc)
1459 SGLookupFunction("glPointParameterfEXT");
1460 glPointParameterfvPtr = (glPointParameterfvProc)
1461 SGLookupFunction("glPointParameterfvEXT");
1463 } else if ( SGIsOpenGLExtensionSupported("GL_ARB_point_parameters") ) {
1464 glPointParameterIsSupported = true;
1465 glPointParameterfPtr = (glPointParameterfProc)
1466 SGLookupFunction("glPointParameterfARB");
1467 glPointParameterfvPtr = (glPointParameterfvProc)
1468 SGLookupFunction("glPointParameterfvARB");
1470 glPointParameterIsSupported = false;
1473 // based on the requested presets, calculate the true starting
1478 SGTime *t = fgInitTime();
1479 globals->set_time_params( t );
1481 // Do some quick general initializations
1482 if( !fgInitGeneral()) {
1483 SG_LOG( SG_GENERAL, SG_ALERT,
1484 "General initializations failed ..." );
1488 ////////////////////////////////////////////////////////////////////
1489 // Initialize the property-based built-in commands
1490 ////////////////////////////////////////////////////////////////////
1493 ////////////////////////////////////////////////////////////////////
1494 // Initialize the material manager
1495 ////////////////////////////////////////////////////////////////////
1496 globals->set_matlib( new SGMaterialLib );
1498 globals->set_model_lib(new SGModelLib);
1500 ////////////////////////////////////////////////////////////////////
1501 // Initialize the TG scenery subsystem.
1502 ////////////////////////////////////////////////////////////////////
1503 globals->set_scenery( new FGScenery );
1504 globals->get_scenery()->init();
1505 globals->get_scenery()->bind();
1506 globals->set_tile_mgr( new FGTileMgr );
1508 ////////////////////////////////////////////////////////////////////
1509 // Initialize the general model subsystem.
1510 ////////////////////////////////////////////////////////////////////
1511 globals->set_model_mgr(new FGModelMgr);
1512 globals->get_model_mgr()->init();
1513 globals->get_model_mgr()->bind();
1515 ////////////////////////////////////////////////////////////////////
1516 // Initialize the 3D aircraft model subsystem (has a dependency on
1517 // the scenery subsystem.)
1518 ////////////////////////////////////////////////////////////////////
1519 globals->set_aircraft_model(new FGAircraftModel);
1520 globals->get_aircraft_model()->init();
1521 globals->get_aircraft_model()->bind();
1523 ////////////////////////////////////////////////////////////////////
1524 // Initialize the view manager subsystem.
1525 ////////////////////////////////////////////////////////////////////
1526 FGViewMgr *viewmgr = new FGViewMgr;
1527 globals->set_viewmgr( viewmgr );
1532 // Initialize the sky
1533 SGPath ephem_data_path( globals->get_fg_root() );
1534 ephem_data_path.append( "Astro" );
1535 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1536 ephem->update( globals->get_time_params()->getMjd(),
1537 globals->get_time_params()->getLst(),
1539 globals->set_ephem( ephem );
1541 // TODO: move to environment mgr
1543 SGPath texture_path(globals->get_fg_root());
1544 texture_path.append("Textures");
1545 texture_path.append("Sky");
1546 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1547 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1548 thesky->add_cloud_layer(layer);
1551 SGPath sky_tex_path( globals->get_fg_root() );
1552 sky_tex_path.append( "Textures" );
1553 sky_tex_path.append( "Sky" );
1554 thesky->texture_path( sky_tex_path.str() );
1556 // The sun and moon diameters are scaled down numbers of the
1557 // actual diameters. This was needed to fit bot the sun and the
1558 // moon within the distance to the far clip plane.
1559 // Moon diameter: 3,476 kilometers
1560 // Sun diameter: 1,390,000 kilometers
1561 thesky->build( 80000.0, 80000.0,
1563 globals->get_ephem()->getNumPlanets(),
1564 globals->get_ephem()->getPlanets(),
1565 globals->get_ephem()->getNumStars(),
1566 globals->get_ephem()->getStars() );
1568 // Initialize MagVar model
1569 SGMagVar *magvar = new SGMagVar();
1570 globals->set_mag( magvar );
1573 // kludge to initialize mag compass
1574 // (should only be done for in-flight
1576 // update magvar model
1577 globals->get_mag()->update( fgGetDouble("/position/longitude-deg")
1578 * SGD_DEGREES_TO_RADIANS,
1579 fgGetDouble("/position/latitude-deg")
1580 * SGD_DEGREES_TO_RADIANS,
1581 fgGetDouble("/position/altitude-ft")
1583 globals->get_time_params()->getJD() );
1584 double var = globals->get_mag()->get_magvar() * SGD_RADIANS_TO_DEGREES;
1585 fgSetDouble("/instrumentation/heading-indicator/offset-deg", -var);
1587 // airport = new ssgBranch;
1588 // airport->setName( "Airport Lighting" );
1589 // lighting->addKid( airport );
1591 // build our custom render states
1592 fgBuildRenderStates();
1594 // pass control off to the master event handler
1597 // we never actually get here ... but to avoid compiler warnings,