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 #if defined(__linux__) && defined(__i386__)
29 # include <fpu_control.h>
33 #include <simgear/compiler.h>
36 #ifndef SG_HAVE_NATIVE_SGI_COMPILERS
41 #include <simgear/misc/exception.hxx>
42 #include <simgear/ephemeris/ephemeris.hxx>
43 #include <simgear/route/route.hxx>
45 #ifdef SG_MATH_EXCEPTION_CLASH
58 #include <string.h> // for strcmp()
65 #ifdef HAVE_SYS_STAT_H
66 # include <sys/stat.h> // for stat()
70 # include <unistd.h> // for stat()
73 #include <plib/netChat.h>
78 #include <simgear/constants.h> // for VERSION
79 #include <simgear/debug/logstream.hxx>
80 #include <simgear/math/polar3d.hxx>
81 #include <simgear/math/sg_random.h>
82 #include <simgear/misc/sg_path.hxx>
83 #include <simgear/sky/clouds3d/SkySceneLoader.hpp>
84 #include <simgear/sky/clouds3d/SkyUtil.hpp>
85 #include <simgear/sky/sky.hxx>
86 #include <simgear/timing/sg_time.hxx>
88 #include <Include/general.hxx>
90 #include <Aircraft/aircraft.hxx>
92 #include <ATC/ATCmgr.hxx>
93 #include <ATC/ATCdisplay.hxx>
94 //#include <ATC/AIMgr.hxx>
97 #include <Autopilot/newauto.hxx>
99 #include <Cockpit/cockpit.hxx>
100 #include <Cockpit/radiostack.hxx>
101 #include <Cockpit/steam.hxx>
103 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
105 #include <Model/acmodel.hxx>
106 #include <Model/loader.hxx>
107 #include <Model/model.hxx>
108 #include <Model/modelmgr.hxx>
109 #include <Main/location.hxx>
110 #ifdef FG_NETWORK_OLK
111 #include <NetworkOLK/network.h>
113 #include <Objects/matlib.hxx>
114 #include <Scenery/scenery.hxx>
115 #include <Scenery/tilemgr.hxx>
116 #ifdef ENABLE_AUDIO_SUPPORT
117 # include <Sound/soundmgr.hxx>
118 # include <Sound/fg_fx.hxx>
119 # include <Sound/morse.hxx>
121 #include <Time/FGEventMgr.hxx>
122 #include <Time/fg_timer.hxx>
123 #include <Time/light.hxx>
124 #include <Time/sunpos.hxx>
125 #include <Time/tmp.hxx>
127 #include <Input/input.hxx>
130 #include <simgear/misc/sgstream.hxx>
131 #include <simgear/math/point3d.hxx>
132 #include <FDM/flight.hxx>
133 #include <FDM/ADA.hxx>
134 #include <Scenery/tileentry.hxx>
137 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
138 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
140 float default_attenuation[3] = {1.0, 0.0, 0.0};
141 //Required for using GL_extensions
142 void fgLoadDCS (void);
143 void fgUpdateDCS (void);
144 ssgSelector *ship_sel=NULL;
145 // upto 32 instances of a same object can be loaded.
146 ssgTransform *ship_pos[32];
147 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
149 ssgSelector *lightpoints_brightness = new ssgSelector;
150 ssgTransform *lightpoints_transform = new ssgTransform;
151 FGTileEntry *dummy_tile;
154 // Clip plane settings...
155 float scene_nearplane = 0.5f;
156 float scene_farplane = 120000.0f;
158 static double delta_time_sec = 0;
162 # include <WeatherCM/FGLocalWeatherDatabase.h>
164 # include <Environment/environment_mgr.hxx>
169 #include "fg_init.hxx"
171 #include "fg_props.hxx"
172 #include "globals.hxx"
173 #include "splash.hxx"
174 #include "viewmgr.hxx"
175 #include "options.hxx"
176 #include "logger.hxx"
179 # include <console.h> // -dw- for command line dialog
183 FGEventMgr global_events;
185 // This is a record containing a bit of global housekeeping information
188 // Specify our current idle function state. This is used to run all
189 // our initializations out of the glutIdleLoop() so that we can get a
190 // splash screen up and running right away.
191 static int idle_state = 0;
192 static long global_multi_loop;
194 // forward declaration
195 void fgReshape( int width, int height );
197 // fog constants. I'm a little nervous about putting actual code out
198 // here but it seems to work (?)
199 static const double m_log01 = -log( 0.01 );
200 static const double sqrt_m_log01 = sqrt( m_log01 );
201 static GLfloat fog_exp_density;
202 static GLfloat fog_exp2_density;
203 static GLfloat fog_exp2_punch_through;
205 #ifdef FG_NETWORK_OLK
206 ssgSelector *fgd_sel = NULL;
207 ssgTransform *fgd_pos = NULL;
212 SkySceneLoader *sgClouds3d;
213 bool _bcloud_orig = true;
215 Point3D *_posit = &posit;
218 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
220 { 1.0f, 0.0f, 0.0f, 0.0f },
221 { 0.0f, 0.0f, -1.0f, 0.0f },
222 { 0.0f, 1.0f, 0.0f, 0.0f },
223 { 0.0f, 0.0f, 0.0f, 1.0f }
226 // The following defines flightgear options. Because glutlib will also
227 // want to parse its own options, those options must not be included here
228 // or they will get parsed by the main program option parser. Hence case
229 // is significant for any option added that might be in conflict with
232 // glutlib parses for:
234 // -direct (invalid in Win32)
238 // -indirect (invalid in Win32)
241 // Note that glutlib depends upon strings while this program's
242 // option parser wants only initial characters followed by numbers
247 ssgSimpleState *default_state;
248 ssgSimpleState *hud_and_panel;
249 ssgSimpleState *menus;
251 SGTimeStamp last_time_stamp;
252 SGTimeStamp current_time_stamp;
254 void fgBuildRenderStates( void ) {
255 default_state = new ssgSimpleState;
256 default_state->ref();
257 default_state->disable( GL_TEXTURE_2D );
258 default_state->enable( GL_CULL_FACE );
259 default_state->enable( GL_COLOR_MATERIAL );
260 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
261 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
262 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
263 default_state->disable( GL_BLEND );
264 default_state->disable( GL_ALPHA_TEST );
265 default_state->disable( GL_LIGHTING );
267 hud_and_panel = new ssgSimpleState;
268 hud_and_panel->ref();
269 hud_and_panel->disable( GL_CULL_FACE );
270 hud_and_panel->disable( GL_TEXTURE_2D );
271 hud_and_panel->disable( GL_LIGHTING );
272 hud_and_panel->enable( GL_BLEND );
274 menus = new ssgSimpleState;
276 menus->disable( GL_CULL_FACE );
277 menus->disable( GL_TEXTURE_2D );
278 menus->enable( GL_BLEND );
282 // fgInitVisuals() -- Initialize various GL/view parameters
283 void fgInitVisuals( void ) {
286 l = &cur_light_params;
288 #ifndef GLUT_WRONG_VERSION
289 // Go full screen if requested ...
290 if ( fgGetBool("/sim/startup/fullscreen") ) {
295 // If enabled, normal vectors specified with glNormal are scaled
296 // to unit length after transformation. Enabling this has
297 // performance implications. See the docs for glNormal.
298 // glEnable( GL_NORMALIZE );
300 glEnable( GL_LIGHTING );
301 glEnable( GL_LIGHT0 );
302 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec ); // done later with ssg
305 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
306 ssgGetLight( 0 ) -> setPosition( sunpos );
308 glFogi (GL_FOG_MODE, GL_EXP2);
309 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
310 (!fgGetBool("/sim/rendering/shading"))) {
311 // if fastest fog requested, or if flat shading force fastest
312 glHint ( GL_FOG_HINT, GL_FASTEST );
313 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
314 glHint ( GL_FOG_HINT, GL_NICEST );
316 if ( fgGetBool("/sim/rendering/wireframe") ) {
318 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
321 // This is the default anyways, but it can't hurt
322 glFrontFace ( GL_CCW );
325 // glEnable(GL_POINT_SMOOTH);
326 // glEnable(GL_LINE_SMOOTH);
327 // glEnable(GL_POLYGON_SMOOTH);
331 // For HiRes screen Dumps using Brian Pauls TR Library
332 void trRenderFrame( void ) {
334 if ( fgPanelVisible() ) {
335 GLfloat height = fgGetInt("/sim/startup/ysize");
337 (current_panel->getViewHeight() - current_panel->getYOffset())
338 * (height / 768.0) + 1;
339 glTranslatef( 0.0, view_h, 0.0 );
342 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
343 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
345 fgLIGHT *l = &cur_light_params;
347 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
348 l->adj_fog_color[2], l->adj_fog_color[3]);
350 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
352 // set the opengl state to known default values
353 default_state->force();
356 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
357 glFogi ( GL_FOG_MODE, GL_EXP2 );
358 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
360 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
361 // we only update GL_AMBIENT for our lights we will never get
362 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
363 // explicitely to black.
364 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
365 glLightModeli( GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE );
367 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
369 // texture parameters
370 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
371 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
373 // we need a white diffuse light for the phase of the moon
374 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
377 // draw the ssg scene
378 // return to the desired diffuse color
379 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
380 glEnable( GL_DEPTH_TEST );
381 ssgSetNearFar( scene_nearplane, scene_farplane );
382 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
385 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
386 ssgSetNearFar( scene_nearplane, scene_farplane );
387 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
389 if (fgGetBool("/environment/clouds/status"))
390 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
392 globals->get_model_mgr()->draw();
393 globals->get_aircraft_model()->draw();
395 // need to do this here as hud_and_panel state is static to
396 // main.cxx and HUD and Panel routines have to be called with
397 // knowledge of the the TR struct < see gui.cxx::HighResDump()
398 hud_and_panel->apply();
402 // Update all Visuals (redraws anything graphics related)
403 void fgRenderFrame() {
405 // Process/manage pending events
406 global_events.update( delta_time_sec );
408 static const SGPropertyNode *longitude
409 = fgGetNode("/position/longitude-deg");
410 static const SGPropertyNode *latitude
411 = fgGetNode("/position/latitude-deg");
412 static const SGPropertyNode *altitude
413 = fgGetNode("/position/altitude-ft");
414 static const SGPropertyNode *groundlevel_nearplane
415 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
417 // Update the default (kludged) properties.
420 FGViewer *current__view = globals->get_current_view();
422 fgLIGHT *l = &cur_light_params;
423 static double last_visibility = -9999;
426 double actual_visibility = thesky->get_visibility();
427 if ( actual_visibility != last_visibility ) {
428 last_visibility = actual_visibility;
430 fog_exp_density = m_log01 / actual_visibility;
431 fog_exp2_density = sqrt_m_log01 / actual_visibility;
432 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
436 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
437 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
438 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
439 // GLfloat mat_shininess[] = { 10.0 };
440 GLbitfield clear_mask;
442 if ( idle_state != 1000 ) {
443 // still initializing, draw the splash screen
444 if ( fgGetBool("/sim/startup/splash-screen") ) {
447 // Keep resetting sim time while the sim is initializing
448 globals->set_sim_time_sec( 0.0 );
450 // idle_state is now 1000 meaning we've finished all our
451 // initializations and are running the main loop, so this will
452 // now work without seg faulting the system.
454 // calculate our current position in cartesian space
455 globals->get_scenery()->set_center( globals->get_scenery()->get_next_center() );
457 if ( fgGetBool("/sim/rendering/clouds3d") ) {
458 posit = globals->get_scenery()->get_center();
459 if ( _bcloud_orig ) {
460 sgClouds3d->Set_Cloud_Orig( _posit );
461 _bcloud_orig = false;
463 /* sgClouds3d->Update( (sgVec4 *)current__view->get_cloud_VIEW(),
469 fgReshape( fgGetInt("/sim/startup/xsize"),
470 fgGetInt("/sim/startup/ysize") );
472 // set the sun position (done later with ssg calls)
473 // glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
475 clear_mask = GL_DEPTH_BUFFER_BIT;
476 if ( fgGetBool("/sim/rendering/wireframe") ) {
477 clear_mask |= GL_COLOR_BUFFER_BIT;
480 if ( fgGetBool("/sim/rendering/skyblend") ) {
481 if ( fgGetBool("/sim/rendering/textures") ) {
482 // glClearColor(black[0], black[1], black[2], black[3]);
483 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
484 l->adj_fog_color[2], l->adj_fog_color[3]);
485 clear_mask |= GL_COLOR_BUFFER_BIT;
488 glClearColor(l->sky_color[0], l->sky_color[1],
489 l->sky_color[2], l->sky_color[3]);
490 clear_mask |= GL_COLOR_BUFFER_BIT;
492 glClear( clear_mask );
494 // Tell GL we are switching to model view parameters
496 // I really should create a derived ssg node or use a call
497 // back or something so that I can draw the sky within the
498 // ssgCullAndDraw() function, but for now I just mimic what
499 // ssg does to set up the model view matrix
500 glMatrixMode(GL_MODELVIEW);
502 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
504 // set the opengl state to known default values
505 default_state->force();
507 // update fog params if visibility has changed
508 double visibility_meters = fgGetDouble("/environment/visibility-m");
509 thesky->set_visibility(visibility_meters);
511 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
512 ( global_multi_loop * fgGetInt("/sim/speed-up") )
513 / (double)fgGetInt("/sim/model-hz") );
515 // Set correct opengl fog density
516 glFogf (GL_FOG_DENSITY, fog_exp2_density);
518 // update the sky dome
519 if ( fgGetBool("/sim/rendering/skyblend") ) {
520 /* cout << "thesky->repaint() sky_color = "
521 << cur_light_params.sky_color[0] << " "
522 << cur_light_params.sky_color[1] << " "
523 << cur_light_params.sky_color[2] << " "
524 << cur_light_params.sky_color[3] << endl;
526 << cur_light_params.fog_color[0] << " "
527 << cur_light_params.fog_color[1] << " "
528 << cur_light_params.fog_color[2] << " "
529 << cur_light_params.fog_color[3] << endl;
530 cout << " sun_angle = " << cur_light_params.sun_angle
531 << " moon_angle = " << cur_light_params.moon_angle
533 thesky->repaint( cur_light_params.sky_color,
534 cur_light_params.adj_fog_color,
535 cur_light_params.sun_angle,
536 cur_light_params.moon_angle,
537 globals->get_ephem()->getNumPlanets(),
538 globals->get_ephem()->getPlanets(),
539 globals->get_ephem()->getNumStars(),
540 globals->get_ephem()->getStars() );
542 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
543 << view_pos[1] << " " << view_pos[2] << endl;
544 cout << " zero_elev = " << zero_elev[0] << " "
545 << zero_elev[1] << " " << zero_elev[2]
546 << " lon = " << cur_fdm_state->get_Longitude()
547 << " lat = " << cur_fdm_state->get_Latitude() << endl;
548 cout << " sun_rot = " << cur_light_params.sun_rotation
549 << " gst = " << SGTime::cur_time_params->getGst() << endl;
550 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
551 << " sun dec = " << globals->get_ephem()->getSunDeclination()
552 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
553 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
555 thesky->reposition( current__view->get_view_pos(),
556 current__view->get_zero_elev(),
557 current__view->get_world_up(),
558 current__view->getLongitude_deg()
559 * SGD_DEGREES_TO_RADIANS,
560 current__view->getLatitude_deg()
561 * SGD_DEGREES_TO_RADIANS,
562 current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
563 cur_light_params.sun_rotation,
564 globals->get_time_params()->getGst(),
565 globals->get_ephem()->getSunRightAscension(),
566 globals->get_ephem()->getSunDeclination(),
568 globals->get_ephem()->getMoonRightAscension(),
569 globals->get_ephem()->getMoonDeclination(),
573 glEnable( GL_DEPTH_TEST );
574 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
576 glFogi( GL_FOG_MODE, GL_EXP2 );
577 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
580 // set sun/lighting parameters
581 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
583 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
584 // we only update GL_AMBIENT for our lights we will never get
585 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
586 // explicitely to black.
587 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
588 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
589 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
591 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
592 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
593 ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_specular );
595 // texture parameters
596 // glEnable( GL_TEXTURE_2D );
597 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
598 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
600 // glMatrixMode( GL_PROJECTION );
602 ssgSetFOV( current__view->get_h_fov(),
603 current__view->get_v_fov() );
606 current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
607 - globals->get_scenery()->get_cur_elev();
610 scene_nearplane = 10.0f;
611 scene_farplane = 120000.0f;
613 scene_nearplane = groundlevel_nearplane->getDoubleValue();
614 scene_farplane = 120000.0f;
617 ssgSetNearFar( scene_nearplane, scene_farplane );
619 // $$$ begin - added VS Renganthan 17 Oct 2K
622 // $$$ end - added VS Renganthan 17 Oct 2K
624 # ifdef FG_NETWORK_OLK
625 if ( fgGetBool("/sim/networking/network-olk") ) {
627 other = head->next; /* put listpointer to start */
628 while ( other != tail) { /* display all except myself */
629 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
630 other->fgd_sel->select(1);
631 sgSetCoord( &fgdpos, other->sgFGD_COORD );
632 other->fgd_pos->setTransform( &fgdpos );
637 // fgd_sel->select(1);
638 // sgCopyMat4( sgTUX, current_view.sgVIEW);
640 // sgSetCoord( &fgdpos, sgFGD_VIEW );
641 // fgd_pos->setTransform( &fgdpos);
645 // position tile nodes and update range selectors
647 // this is done in the main loop now...
648 // global_tile_mgr.prep_ssg_nodes(visibility_meters);
650 if ( fgGetBool("/sim/rendering/skyblend") ) {
651 // draw the sky backdrop
653 // we need a white diffuse light for the phase of the moon
654 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
658 // return to the desired diffuse color
659 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
662 // draw the ssg scene
663 glEnable( GL_DEPTH_TEST );
665 ssgSetNearFar( scene_nearplane, scene_farplane );
666 ssgCullAndDraw( globals->get_scenery()->get_scene_graph() );
668 // This is a bit kludgy. Every 200 frames, do an extra
669 // traversal of the scene graph without drawing anything, but
670 // with the field-of-view set to 360x360 degrees. This
671 // ensures that out-of-range random objects that are not in
672 // the current view frustum will still be freed properly.
673 static int counter = 0;
675 if (counter == 200) {
678 // No need to put the near plane too close;
679 // this way, at least the aircraft can be
681 f.setNearFar(1000, 1000000);
683 ssgGetModelviewMatrix(m);
684 globals->get_scenery()->get_scene_graph()->cull(&f, m, true);
688 // change state for lighting here
691 // Set punch through fog density
692 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
694 #ifdef FG_EXPERIMENTAL_LIGHTING
695 // Enable states for drawing points with GL_extension
696 if (glutExtensionSupported("GL_EXT_point_parameters")) {
697 glEnable(GL_POINT_SMOOTH);
698 float quadratic[3] = {1.0, 0.01, 0.0001};
699 // get the address of our OpenGL extensions
701 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
702 wglGetProcAddress("glPointParameterfEXT");
703 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
704 wglGetProcAddress("glPointParameterfvEXT");
706 // makes the points fade as they move away
707 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
708 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
711 // Enable states for drawing runway lights with spherical mapping
712 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
713 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
714 glEnable(GL_TEXTURE_GEN_S);
715 glEnable(GL_TEXTURE_GEN_T);
717 //Maybe this is not the best way, but it works !!
718 glPolygonMode(GL_FRONT, GL_POINT);
720 glEnable(GL_CULL_FACE);
723 glDisable( GL_LIGHTING );
724 // blending function for runway lights
725 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
729 ssgSetNearFar( scene_nearplane, scene_farplane );
730 ssgCullAndDraw( globals->get_scenery()->get_lighting() );
732 //static int _frame_count = 0;
733 //if (_frame_count % 30 == 0) {
734 // printf("SSG: %s\n", ssgShowStats());
742 #ifdef FG_EXPERIMENTAL_LIGHTING
743 if (glutExtensionSupported("GL_EXT_point_parameters")) {
744 // Disable states used for runway lighting
745 glPolygonMode(GL_FRONT, GL_FILL);
747 glDisable(GL_TEXTURE_GEN_S);
748 glDisable(GL_TEXTURE_GEN_T);
749 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
750 default_attenuation);
756 if ( fgGetBool("/sim/rendering/skyblend") ) {
757 // draw the sky cloud layers
758 if (fgGetBool("/environment/clouds/status")) {
759 thesky->postDraw( cur_fdm_state->get_Altitude()
760 * SG_FEET_TO_METER );
764 globals->get_model_mgr()->draw();
765 globals->get_aircraft_model()->draw();
767 // draw the 3D clouds
768 if ( fgGetBool("/sim/rendering/clouds3d") ) sgClouds3d->Draw();
770 // display HUD && Panel
772 glDisable( GL_DEPTH_TEST );
773 // glDisable( GL_CULL_FACE );
774 // glDisable( GL_TEXTURE_2D );
776 // update the input subsystem
777 current_input.update(delta_time_sec);
779 // update the controls subsystem
780 globals->get_controls()->update(delta_time_sec);
782 hud_and_panel->apply();
785 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
786 // This only works properly if called before the panel call
787 globals->get_ATC_display()->update(delta_time_sec);
789 // update the panel subsystem
790 if ( current_panel != NULL ) {
791 current_panel->update(delta_time_sec);
794 // We can do translucent menus, so why not. :-)
796 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
798 // glDisable ( GL_BLEND ) ;
800 // glEnable( GL_FOG );
802 globals->get_logger()->update(delta_time_sec);
809 // Update internal time dependent calculations (i.e. flight model)
810 // FIXME: this distinction is obsolete; all subsystems now get delta
812 void fgUpdateTimeDepCalcs() {
813 static bool inited = false;
815 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
817 fgLIGHT *l = &cur_light_params;
822 // Initialize the FDM here if it hasn't been and if we have a
823 // scenery elevation hit.
825 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
826 // << " cur_elev = " << scenery.get_cur_elev() << endl;
828 if ( !cur_fdm_state->get_inited() &&
829 globals->get_scenery()->get_cur_elev() > -9990 )
831 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
833 cur_fdm_state->init();
834 if ( cur_fdm_state->get_bound() ) {
835 cur_fdm_state->unbind();
837 cur_fdm_state->bind();
840 // conceptually, the following block could be done for each fdm
842 if ( !cur_fdm_state->get_inited() ) {
843 // do nothing, fdm isn't inited yet
845 // we have been inited, and we are good to go ...
851 globals->get_autopilot()->update(delta_time_sec);
852 cur_fdm_state->update(delta_time_sec);
853 globals->get_steam()->update(delta_time_sec);
856 globals->get_model_mgr()->update(delta_time_sec);
857 globals->get_aircraft_model()->update(delta_time_sec);
859 // update the view angle
860 globals->get_viewmgr()->update(delta_time_sec);
864 // Update solar system
865 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
866 globals->get_time_params()->getLst(),
867 cur_fdm_state->get_Latitude() );
869 // Update radio stack model
870 current_radiostack->update(delta_time_sec);
874 void fgInitTimeDepCalcs( void ) {
879 static const double alt_adjust_ft = 3.758099;
880 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
883 // What should we do when we have nothing else to do? Let's get ready
884 // for the next move and update the display?
885 static void fgMainLoop( void ) {
887 // Update the elapsed time.
888 static bool first_time = true;
890 last_time_stamp.stamp();
893 current_time_stamp.stamp();
894 delta_time_sec = double(current_time_stamp - last_time_stamp) / 1000000.0;
895 last_time_stamp = current_time_stamp;
896 globals->inc_sim_time_sec( delta_time_sec );
898 static const SGPropertyNode *longitude
899 = fgGetNode("/position/longitude-deg");
900 static const SGPropertyNode *latitude
901 = fgGetNode("/position/latitude-deg");
902 static const SGPropertyNode *altitude
903 = fgGetNode("/position/altitude-ft");
904 static const SGPropertyNode *clock_freeze
905 = fgGetNode("/sim/freeze/clock", true);
906 static const SGPropertyNode *cur_time_override
907 = fgGetNode("/sim/time/cur-time-override", true);
909 static long remainder = 0;
911 #ifdef FANCY_FRAME_COUNTER
915 static time_t last_time = 0;
916 static int frames = 0;
917 #endif // FANCY_FRAME_COUNTER
919 SGTime *t = globals->get_time_params();
921 FGLocation * acmodel_location = 0;
922 if(cur_fdm_state->getACModel() != 0) {
923 acmodel_location = (FGLocation *) cur_fdm_state->getACModel()->get3DModel()->getFGLocation();
926 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
927 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
929 #ifdef FG_NETWORK_OLK
930 if ( fgGetBool("/sim/networking/network-olk") ) {
931 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
932 // printf("FGD: Netupdate\n");
933 fgd_send_com( "A", FGFS_host); // Send Mat4 data
934 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
939 #if defined( ENABLE_PLIB_JOYSTICK )
940 // Read joystick and update control settings
941 // if ( fgGetString("/sim/control-mode") == "joystick" )
945 #elif defined( ENABLE_GLUT_JOYSTICK )
946 // Glut joystick support works by feeding a joystick handler
947 // function to glut. This is taken care of once in the joystick
948 // init routine and we don't have to worry about it again.
952 globals->get_environment_mgr()->update(delta_time_sec);
955 // Fix elevation. I'm just sticking this here for now, it should
956 // probably move eventually
958 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
959 scenery.get_cur_elev(),
960 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
961 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
963 // Curt is this code used? I don't see any problems when I comment it out.
964 if ( acmodel_location != 0 ) {
965 if ( acmodel_location->get_cur_elev_m() > -9990 && cur_fdm_state->get_inited() ) {
966 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
967 (acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0) ) {
968 // now set aircraft altitude above ground
969 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
970 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
971 acmodel_location->get_cur_elev_m() + alt_adjust_m - 3.0,
972 acmodel_location->get_cur_elev_m() + alt_adjust_m );
973 cur_fdm_state->set_Altitude( (acmodel_location->get_cur_elev_m()
974 + alt_adjust_m) * SG_METER_TO_FEET );
975 SG_LOG( SG_ALL, SG_DEBUG,
976 "<*> resetting altitude to "
977 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
982 // End of code in question. (see Curt is this code used? above)
984 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
985 scenery.get_cur_elev(),
986 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
987 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
989 // cout << "Warp = " << globals->get_warp() << endl;
992 static bool last_clock_freeze = false;
994 if ( clock_freeze->getBoolValue() ) {
995 // clock freeze requested
996 if ( cur_time_override->getLongValue() == 0 ) {
997 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
998 globals->set_warp( 0 );
1001 // no clock freeze requested
1002 if ( last_clock_freeze == true ) {
1003 // clock just unfroze, let's set warp as the difference
1004 // between frozen time and current time so we don't get a
1005 // time jump (and corresponding sky object and lighting
1007 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1008 fgSetLong( "/sim/time/cur-time-override", 0 );
1010 if ( globals->get_warp_delta() != 0 ) {
1011 globals->inc_warp( globals->get_warp_delta() );
1015 last_clock_freeze = clock_freeze->getBoolValue();
1017 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1018 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1019 cur_time_override->getLongValue(),
1020 globals->get_warp() );
1022 if ( globals->get_warp_delta() != 0 ) {
1023 fgUpdateSkyAndLightingParams();
1026 // update magvar model
1027 globals->get_mag()->update( longitude->getDoubleValue()
1028 * SGD_DEGREES_TO_RADIANS,
1029 latitude->getDoubleValue()
1030 * SGD_DEGREES_TO_RADIANS,
1031 altitude->getDoubleValue() * SG_FEET_TO_METER,
1032 globals->get_time_params()->getJD() );
1034 // Get elapsed time (in usec) for this past frame
1035 elapsed = fgGetTimeInterval();
1036 SG_LOG( SG_ALL, SG_DEBUG,
1037 "Elapsed time interval is = " << elapsed
1038 << ", previous remainder is = " << remainder );
1040 // Calculate frame rate average
1041 #ifdef FANCY_FRAME_COUNTER
1042 /* old fps calculation */
1043 if ( elapsed > 0 ) {
1046 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1047 tmp = general.get_frame(i);
1049 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1050 general.set_frame(i+1,tmp);
1052 tmp = 1000000.0 / (float)elapsed;
1053 general.set_frame(0,tmp);
1054 // printf("frame[0] = %.2f\n", general.frames[0]);
1056 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1057 // printf("ave = %.2f\n", general.frame_rate);
1060 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1061 general.set_frame_rate( frames );
1062 SG_LOG( SG_ALL, SG_DEBUG,
1063 "--> Frame rate is = " << general.get_frame_rate() );
1066 last_time = t->get_cur_time();
1070 // Run ATC subsystem
1071 globals->get_ATC_mgr()->update(delta_time_sec);
1073 // Run the AI subsystem
1074 // globals->get_AI_mgr()->update(delta_time_sec);
1078 // Calculate model iterations needed for next frame
1079 elapsed += remainder;
1081 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1082 fgGetInt("/sim/model-hz"));
1083 remainder = elapsed - ( (global_multi_loop*1000000) /
1084 fgGetInt("/sim/model-hz") );
1085 SG_LOG( SG_ALL, SG_DEBUG,
1086 "Model iterations needed = " << global_multi_loop
1087 << ", new remainder = " << remainder );
1089 // chop max interations to something reasonable if the sim was
1090 // delayed for an excesive amount of time
1091 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1092 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1097 if ( global_multi_loop > 0 ) {
1098 fgUpdateTimeDepCalcs();
1100 SG_LOG( SG_ALL, SG_DEBUG,
1101 "Elapsed time is zero ... we're zinging" );
1104 // Do any I/O channel work that might need to be done
1105 globals->get_io()->update( delta_time_sec );
1107 // see if we need to load any deferred-load textures
1108 material_lib.load_next_deferred();
1110 // Run audio scheduler
1111 #ifdef ENABLE_AUDIO_SUPPORT
1112 if ( fgGetBool("/sim/sound/audible")
1113 && globals->get_soundmgr()->is_working() ) {
1114 globals->get_fx()->update( delta_time_sec );
1115 globals->get_soundmgr()->update( delta_time_sec );
1120 // Tile Manager updates - see if we need to load any new scenery tiles.
1121 // this code ties together the fdm, viewer and scenery classes...
1122 // we may want to move this to it's own class at some point
1124 double visibility_meters = fgGetDouble("/environment/visibility-m");
1125 FGViewer *current_view = globals->get_current_view();
1127 // update tile manager for FDM...
1128 // ...only if location is different than the viewer (to avoid duplicating effort)
1129 if( acmodel_location != current_view->getFGLocation() ) {
1130 if( acmodel_location != 0 ) {
1131 global_tile_mgr.prep_ssg_nodes(visibility_meters,
1132 acmodel_location->get_world_up(),
1133 acmodel_location->get_tile_center());
1134 global_tile_mgr.update( acmodel_location->getLongitude_deg(),
1135 acmodel_location->getLatitude_deg(),
1137 acmodel_location->get_absolute_view_pos(),
1138 acmodel_location->get_current_bucket(),
1139 acmodel_location->get_previous_bucket(),
1140 acmodel_location->get_tile_center()
1142 // save results of update in FGLocation for fdm...
1143 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1144 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1146 acmodel_location->set_current_bucket( global_tile_mgr.get_current_bucket() );
1147 acmodel_location->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1148 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1152 global_tile_mgr.prep_ssg_nodes(visibility_meters,
1153 current_view->getFGLocation()->get_world_up(),
1154 current_view->getFGLocation()->get_tile_center());
1155 // update tile manager for view...
1156 // IMPORTANT!!! the tilemgr update for view location _must_ be done last
1157 // after the FDM's until all of Flight Gear code references the viewer's location
1158 // for elevation instead of the "scenery's" current elevation.
1159 global_tile_mgr.update( current_view->getLongitude_deg(),
1160 current_view->getLatitude_deg(),
1162 current_view->get_absolute_view_pos(),
1163 current_view->getFGLocation()->get_current_bucket(),
1164 current_view->getFGLocation()->get_previous_bucket(),
1165 current_view->getFGLocation()->get_tile_center()
1167 // save results of update in FGLocation for fdm...
1168 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1169 current_view->getFGLocation()->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1171 current_view->getFGLocation()->set_current_bucket( global_tile_mgr.get_current_bucket() );
1172 current_view->getFGLocation()->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1173 current_view->getFGLocation()->set_tile_center( globals->get_scenery()->get_next_center() );
1175 // If fdm location is same as viewer's then we didn't do the update for fdm location
1176 // above so we need to save the viewer results in the fdm FGLocation as well...
1177 if( acmodel_location == current_view->getFGLocation() ) {
1178 if( acmodel_location != 0 ) {
1179 if ( globals->get_scenery()->get_cur_elev() > -9990 ) {
1180 acmodel_location->set_cur_elev_m( globals->get_scenery()->get_cur_elev() );
1182 acmodel_location->set_current_bucket( global_tile_mgr.get_current_bucket() );
1183 acmodel_location->set_previous_bucket( global_tile_mgr.get_previous_bucket() );
1184 acmodel_location->set_tile_center( globals->get_scenery()->get_next_center() );
1188 // END Tile Manager udpates
1193 SG_LOG( SG_ALL, SG_DEBUG, "" );
1197 // This is the top level master main function that is registered as
1198 // our idle funciton
1200 // The first few passes take care of initialization things (a couple
1201 // per pass) and once everything has been initialized fgMainLoop from
1204 static void fgIdleFunction ( void ) {
1205 // printf("idle state == %d\n", idle_state);
1207 if ( idle_state == 0 ) {
1208 // Initialize the splash screen right away
1209 if ( fgGetBool("/sim/startup/splash-screen") ) {
1214 } else if ( idle_state == 1 ) {
1215 // Initialize audio support
1216 #ifdef ENABLE_AUDIO_SUPPORT
1218 // Start the intro music
1219 if ( fgGetBool("/sim/startup/intro-music") ) {
1220 SGPath mp3file( globals->get_fg_root() );
1221 mp3file.append( "Sounds/intro.mp3" );
1223 SG_LOG( SG_GENERAL, SG_INFO,
1224 "Starting intro music: " << mp3file.str() );
1226 #if defined( __CYGWIN__ )
1227 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1228 #elif defined( WIN32 )
1229 string command = "start /m " + mp3file.str();
1231 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1234 system ( command.c_str() );
1239 } else if ( idle_state == 2 ) {
1240 // These are a few miscellaneous things that aren't really
1241 // "subsystems" but still need to be initialized.
1244 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1245 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1250 } else if ( idle_state == 3 ) {
1251 // This is the top level init routine which calls all the
1252 // other subsystem initialization routines. If you are adding
1253 // a subsystem to flightgear, its initialization call should
1254 // located in this routine.
1255 if( !fgInitSubsystems()) {
1256 SG_LOG( SG_GENERAL, SG_ALERT,
1257 "Subsystem initializations failed ..." );
1262 } else if ( idle_state == 4 ) {
1263 // setup OpenGL view parameters
1267 } else if ( idle_state == 5 ) {
1270 } else if ( idle_state == 6 ) {
1274 cout << "Panel visible = " << fgPanelVisible() << endl;
1275 fgReshape( fgGetInt("/sim/startup/xsize"),
1276 fgGetInt("/sim/startup/ysize") );
1279 if ( idle_state == 1000 ) {
1280 // We've finished all our initialization steps, from now on we
1281 // run the main loop.
1283 glutIdleFunc(fgMainLoop);
1285 if ( fgGetBool("/sim/startup/splash-screen") ) {
1286 fgSplashUpdate(0.0);
1291 // options.cxx needs to see this for toggle_panel()
1292 // Handle new window size or exposure
1293 void fgReshape( int width, int height ) {
1296 if ( (!fgGetBool("/sim/virtual-cockpit"))
1297 && fgPanelVisible() && idle_state == 1000 ) {
1298 view_h = (int)(height * (current_panel->getViewHeight() -
1299 current_panel->getYOffset()) / 768.0);
1305 FGViewMgr *viewmgr = globals->get_viewmgr();
1306 for ( int i = 0; i < viewmgr->size(); ++i ) {
1307 viewmgr->get_view(i)->
1308 set_aspect_ratio((float)view_h / (float)width);
1311 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1313 fgSetInt("/sim/startup/xsize", width);
1314 fgSetInt("/sim/startup/ysize", height);
1315 guiInitMouse(width, height);
1317 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1318 viewmgr->get_current_view()->get_v_fov() );
1321 sgClouds3d->Resize( viewmgr->get_current_view()->get_h_fov(),
1322 viewmgr->get_current_view()->get_v_fov() );
1325 // Initialize GLUT and define a main window
1326 int fgGlutInit( int *argc, char **argv ) {
1328 #if !defined( macintosh )
1329 // GLUT will extract all glut specific options so later on we only
1330 // need wory about our own.
1331 glutInit(argc, argv);
1334 // Define Display Parameters
1335 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE | GLUT_ALPHA);
1337 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1338 fgGetInt("/sim/startup/xsize") << "x"
1339 << fgGetInt("/sim/startup/ysize") );
1341 // Define initial window size
1342 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1343 fgGetInt("/sim/startup/ysize") );
1345 // Initialize windows
1346 if ( !fgGetBool("/sim/startup/game-mode")) {
1347 // Open the regular window
1348 glutCreateWindow("FlightGear");
1349 #ifndef GLUT_WRONG_VERSION
1351 // Open the cool new 'game mode' window
1352 char game_mode_str[256];
1353 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1354 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1355 #ifndef ENUM_CURRENT_SETTINGS
1356 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1357 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1361 dm.dmSize = sizeof(DEVMODE);
1362 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1363 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1364 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1365 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1366 fgGetInt("/sim/startup/ysize") );
1367 sprintf( game_mode_str, "%dx%d:%d@%d",
1371 dm.dmDisplayFrequency );
1373 // Open the cool new 'game mode' window
1374 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1375 fgGetInt("/sim/startup/xsize"),
1376 fgGetInt("/sim/startup/ysize"),
1377 fgGetInt("/sim/rendering/bits-per-pixel"));
1379 #endif // HAVE_WINDOWS_H
1380 SG_LOG( SG_GENERAL, SG_INFO,
1381 "game mode params = " << game_mode_str );
1382 glutGameModeString( game_mode_str );
1383 glutEnterGameMode();
1384 #endif // GLUT_WRONG_VERSION
1387 // This seems to be the absolute earliest in the init sequence
1388 // that these calls will return valid info. Too bad it's after
1389 // we've already created and sized out window. :-(
1390 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1391 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1392 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1393 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1396 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1397 general.set_glMaxTexSize( tmp );
1398 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1400 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1401 general.set_glDepthBits( tmp );
1402 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1408 // Initialize GLUT event handlers
1409 int fgGlutInitEvents( void ) {
1410 // call fgReshape() on window resizes
1411 glutReshapeFunc( fgReshape );
1413 // keyboard and mouse callbacks are set in FGInput::init
1415 // call fgMainLoop() whenever there is
1416 // nothing else to do
1417 glutIdleFunc( fgIdleFunction );
1420 glutDisplayFunc( fgRenderFrame );
1427 int mainLoop( int argc, char **argv ) {
1429 #if defined( macintosh )
1430 freopen ("stdout.txt", "w", stdout );
1431 freopen ("stderr.txt", "w", stderr );
1432 argc = ccommand( &argv );
1435 // set default log levels
1436 sglog().setLogLevels( SG_ALL, SG_INFO );
1439 #ifdef FLIGHTGEAR_VERSION
1440 version = FLIGHTGEAR_VERSION;
1442 version = "unknown version";
1444 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1446 SG_LOG( SG_GENERAL, SG_INFO, "Built with " << SG_COMPILER_STR << endl );
1448 // Allocate global data structures. This needs to happen before
1449 // we parse command line options
1451 globals = new FGGlobals;
1453 #ifndef FG_WEATHERCM
1454 globals->set_environment_mgr(new FGEnvironmentMgr);
1457 // seed the random number generater
1460 SGRoute *route = new SGRoute;
1461 globals->set_route( route );
1463 FGControls *controls = new FGControls;
1464 globals->set_controls( controls );
1466 FGSteam *steam = new FGSteam;
1467 globals->set_steam( steam );
1469 string_list *col = new string_list;
1470 globals->set_channel_options_list( col );
1472 // Scan the config file(s) and command line options to see if
1473 // fg_root was specified (ignore all other options for now)
1474 fgInitFGRoot(argc, argv);
1476 // Check for the correct base package version
1477 static char required_version[] = "0.9.0";
1478 string base_version = fgBasePackageVersion();
1479 if ( !(base_version == required_version) ) {
1480 // tell the operator how to use this application
1483 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1484 << "Found version " << base_version << " at: "
1485 << globals->get_fg_root() );
1486 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version"
1487 << required_version);
1491 // Initialize the Aircraft directory to "" (UIUC)
1494 // Load the configuration parameters
1495 if ( !fgInitConfig(argc, argv) ) {
1496 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1500 // Initialize the Window/Graphics environment.
1501 if( !fgGlutInit(&argc, argv) ) {
1502 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1506 // Initialize the various GLUT Event Handlers.
1507 if( !fgGlutInitEvents() ) {
1508 SG_LOG( SG_GENERAL, SG_ALERT,
1509 "GLUT event handler initialization failed ..." );
1513 // Initialize plib net interface
1514 netInit( &argc, argv );
1516 // Initialize ssg (from plib). Needs to come before we do any
1517 // other ssg stuff, but after opengl/glut has been initialized.
1520 // Initialize the user interface (we need to do this before
1521 // passing off control to glut and before fgInitGeneral to get our
1525 #ifdef GL_EXT_texture_lod_bias
1526 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1529 // Set position relative to glide slope if requested
1530 fgSetPosFromGlideSlope();
1532 // If we have an explicit, in-range lon/lat, use it.
1533 // If not, check for an airport-id and use that.
1534 // If not, default to the middle of the KSFO field.
1535 // The default values for lon/lat are deliberately out of range
1536 // so that the airport-id can take effect; valid lon/lat will
1537 // override airport-id, however.
1538 double lon_deg = fgGetDouble("/position/longitude-deg");
1539 double lat_deg = fgGetDouble("/position/latitude-deg");
1540 if (lon_deg < -180 || lon_deg > 180 || lat_deg < -90 || lat_deg > 90) {
1541 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1542 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1543 fgGetDouble("/orientation/heading-deg") );
1544 // set tower position (a little off the heading for single
1546 fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"),
1547 fgGetDouble("orientation/heading") );
1549 // Default to middle of KSFO field
1550 fgSetDouble("/position/longitude-deg", -122.374843);
1551 fgSetDouble("/position/latitude-deg", 37.619002);
1555 SGTime *t = fgInitTime();
1556 globals->set_time_params( t );
1558 // Do some quick general initializations
1559 if( !fgInitGeneral()) {
1560 SG_LOG( SG_GENERAL, SG_ALERT,
1561 "General initializations failed ..." );
1565 SGPath modelpath( globals->get_fg_root() );
1566 ssgModelPath( (char *)modelpath.c_str() );
1568 // Initialize the global scenery manager
1569 globals->set_scenery( new FGScenery );
1570 globals->get_scenery()->init();
1571 globals->get_scenery()->bind();
1573 ////////////////////////////////////////////////////////////////////
1574 // Initialize the general model subsystem.
1575 ////////////////////////////////////////////////////////////////////
1577 globals->set_model_loader(new FGModelLoader);
1578 globals->set_texture_loader(new FGTextureLoader);
1579 globals->set_model_mgr(new FGModelMgr);
1580 globals->get_model_mgr()->init();
1581 globals->get_model_mgr()->bind();
1583 ////////////////////////////////////////////////////////////////////
1584 // Initialize the 3D aircraft model subsystem.
1585 ////////////////////////////////////////////////////////////////////
1587 globals->set_aircraft_model(new FGAircraftModel);
1588 globals->get_aircraft_model()->init();
1589 globals->get_aircraft_model()->bind();
1591 ////////////////////////////////////////////////////////////////////
1592 // Initialize the view manager subsystem.
1593 ////////////////////////////////////////////////////////////////////
1595 FGViewMgr *viewmgr = new FGViewMgr;
1596 globals->set_viewmgr( viewmgr );
1601 // Initialize the sky
1602 SGPath ephem_data_path( globals->get_fg_root() );
1603 ephem_data_path.append( "Astro" );
1604 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1605 ephem->update( globals->get_time_params()->getMjd(),
1606 globals->get_time_params()->getLst(),
1608 globals->set_ephem( ephem );
1610 // TODO: move to environment mgr
1612 SGPath texture_path(globals->get_fg_root());
1613 texture_path.append("Textures");
1614 texture_path.append("Sky");
1615 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
1616 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
1617 thesky->add_cloud_layer(layer);
1621 SGPath sky_tex_path( globals->get_fg_root() );
1622 sky_tex_path.append( "Textures" );
1623 sky_tex_path.append( "Sky" );
1624 thesky->texture_path( sky_tex_path.str() );
1626 thesky->build( 550.0, 550.0,
1627 globals->get_ephem()->getNumPlanets(),
1628 globals->get_ephem()->getPlanets(), 60000.0,
1629 globals->get_ephem()->getNumStars(),
1630 globals->get_ephem()->getStars(), 60000.0 );
1632 // Initialize MagVar model
1633 SGMagVar *magvar = new SGMagVar();
1634 globals->set_mag( magvar );
1636 // airport = new ssgBranch;
1637 // airport->setName( "Airport Lighting" );
1638 // lighting->addKid( airport );
1644 #ifdef FG_NETWORK_OLK
1645 // Do the network intialization
1646 if ( fgGetBool("/sim/networking/network-olk") ) {
1647 printf("Multipilot mode %s\n",
1648 fg_net_init( globals->get_scenery()->get_scene_graph() ) );
1652 // build our custom render states
1653 fgBuildRenderStates();
1655 // pass control off to the master GLUT event handler
1658 // we never actually get here ... but to avoid compiler warnings,
1664 // $$$ end - added VS Renganathan, 15 Oct 2K
1665 // - added Venky , 12 Nov 2K
1667 #if defined(__linux__) && defined(__i386__)
1669 static void handleFPE (int);
1674 fpu_control_t fpe_flags = 0;
1675 _FPU_GETCW(fpe_flags);
1676 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1677 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1678 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1679 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1680 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1681 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1682 _FPU_SETCW(fpe_flags);
1683 signal(SIGFPE, handleFPE);
1690 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1703 short CPSGetCurrentProcess(PSN *psn);
1704 short CPSSetProcessName (PSN *psn, char *processname);
1705 short CPSEnableForegroundOperation(PSN *psn, int _arg2, int _arg3, int _arg4, int _arg5);
1706 short CPSSetFrontProcess(PSN *psn);
1709 #define CPSEnableFG(psn) CPSEnableForegroundOperation(psn,0x03,0x3C,0x2C,0x1103)
1713 // Main entry point; catch any exceptions that have made it this far.
1714 int main ( int argc, char **argv ) {
1716 // Enable floating-point exceptions for Linux/x86
1717 #if defined(__linux__) && defined(__i386__)
1721 // Enable floating-point exceptions for Windows
1722 #if defined( _MSC_VER ) && defined( DEBUG )
1723 // Christian, we should document what this does
1724 _control87( _EM_INEXACT, _MCW_EM );
1727 #if defined( HAVE_BC5PLUS )
1728 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1731 // Keyboard focus hack
1736 glutInit (&argc, argv);
1738 CPSGetCurrentProcess(&psn);
1739 CPSSetProcessName(&psn, "FlightGear");
1741 CPSSetFrontProcess(&psn);
1745 // FIXME: add other, more specific
1748 mainLoop(argc, argv);
1749 } catch (sg_throwable &t) {
1750 // We must use cerr rather than
1751 // logging, since logging may be
1753 cerr << "Fatal error: " << t.getFormattedMessage()
1754 << "\n (received from " << t.getOrigin() << ')' << endl;
1762 void fgLoadDCS(void) {
1764 ssgEntity *ship_obj = NULL;
1766 char obj_filename[25];
1768 for ( int k = 0; k < 32; k++ ) {
1772 SGPath tile_path( globals->get_fg_root());
1773 tile_path.append( "Scenery" );
1774 tile_path.append( "Objects.txt" );
1775 sg_gzifstream in( tile_path.str() );
1776 if ( ! in.is_open() ) {
1777 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1780 SGPath modelpath( globals->get_fg_root() );
1781 modelpath.append( "Models" );
1782 modelpath.append( "Geometry" );
1784 SGPath texturepath( globals->get_fg_root() );
1785 texturepath.append( "Models" );
1786 texturepath.append( "Textures" );
1788 ssgModelPath( (char *)modelpath.c_str() );
1789 ssgTexturePath( (char *)texturepath.c_str() );
1791 ship_sel = new ssgSelector;
1794 while ( ! in.eof() ) {
1796 if ( in.get( c ) && c == '#' ) {
1800 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1801 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1802 int chj=getchar();*/
1804 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1805 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1807 ship_pos[objc] = new ssgTransform;
1809 // type "repeat" in objects.txt to load one more
1810 // instance of the last object.
1812 if ( strcmp(obj_filename,"repeat") != 0) {
1814 globals->get_model_loader()->load_model( obj_filename );
1817 if ( ship_obj != NULL ) {
1818 ship_obj->setName(obj_filename);
1820 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1822 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1823 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1824 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1825 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1828 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1832 // temporary hack for deck lights - ultimately should move to PLib (when??)
1833 //const char *extn = file_extension ( obj_filename ) ;
1835 ssgVertexArray *lights = new ssgVertexArray( 100 );
1836 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1837 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1838 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1839 int ltype[500], light_type;
1840 static int ltcount = 0;
1842 sgVec3 rway_dir,rway_normal,lightpt;
1844 modelpath.append(obj_filename);
1845 sg_gzifstream in1( modelpath.str() );
1846 if ( ! in1.is_open() ) {
1847 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1849 while ( ! in1.eof() ) {
1851 if ( in1.get( c ) && c == '#' ) {
1856 //cout << token << endl;
1857 if ( token == "runway" ) {
1859 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1860 } else if ( token == "edgelight" ) {
1862 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1864 } else if ( token == "taxi" ) {
1866 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1868 } else if ( token == "vasi" ) {
1870 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1872 } else if ( token == "threshold" ) {
1874 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1876 } else if ( token == "rabbit" ) {
1878 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1880 } else if ( token == "ols" ) {
1882 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1884 } else if ( token == "red" ) {
1886 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1888 } else if ( token == "green" ) {
1890 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1892 } else if ( token == "lp" ) {
1894 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1895 lightpoints->add( lightpt );
1896 lightnormals->add( rway_normal );
1897 lightdir->add( rway_dir );
1898 ltype[ltcount]= light_type;
1901 if (in1.eof()) break;
1905 if ( lightpoints->getNum() ) {
1906 ssgBranch *lightpoints_branch;
1907 long int dummy = -999;
1908 dummy_tile = new FGTileEntry((SGBucket)dummy);
1909 dummy_tile->lightmaps_sequence = new ssgSelector;
1910 dummy_tile->ols_transform = new ssgTransform;
1912 // call function to generate the runway lights
1913 lightpoints_branch =
1914 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1916 lightpoints_brightness->addKid(lightpoints_branch);
1917 lightpoints_transform->addKid(lightpoints_brightness);
1918 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1919 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1920 lightpoints_transform->ref();
1921 globals->get_scenery()->get_gnd_lights_branch()->addKid( lightpoints_transform );
1925 // end hack for deck lights
1929 if (in.eof()) break;
1933 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1935 globals->get_scenery()->get_terrain_branch()->addKid( ship_sel ); //add selector node to root node
1942 void fgUpdateDCS (void) {
1944 // double eye_lat,eye_lon,eye_alt;
1945 // static double obj_head;
1946 double sl_radius,obj_latgc;
1947 // float nresultmat[4][4];
1948 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1951 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1952 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1954 // Deck should be the first object in objects.txt in case of fdm=ada
1956 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1957 if ((fdm->get_iaux(1))==1)
1959 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1960 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1961 obj_alt[1] = fdm->get_daux(3);
1962 obj_pitch[1] = fdm->get_faux(1);
1963 obj_roll[1] = fdm->get_faux(2);
1967 for ( int m = 0; m < objc; m++ ) {
1968 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1971 //Geodetic to Geocentric angles for rotation
1972 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1974 //moving object gbs-posn in cartesian coords
1975 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1976 Point3D obj_pos = sgGeodToCart( obj_posn );
1978 // Translate moving object w.r.t eye
1979 Point3D Objtrans = obj_pos - globals->get_scenery()->get_center();
1984 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1987 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1989 sgVec3 ship_fwd,ship_rt,ship_up;
1990 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1991 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1992 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1994 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1995 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1996 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1997 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1998 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1999 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
2002 sgCopyMat4( sgTUX, sgROT_hdg );
2003 sgPostMultMat4( sgTUX, sgROT_pitch );
2004 sgPostMultMat4( sgTUX, sgROT_roll );
2005 sgPostMultMat4( sgTUX, sgROT_lat );
2006 sgPostMultMat4( sgTUX, sgROT_lon );
2007 sgPostMultMat4( sgTUX, sgTRANS );
2010 sgSetCoord(&shippos, sgTUX );
2011 ship_pos[m]->setTransform( &shippos );
2012 // temporary hack for deck lights - ultimately should move to PLib (when ??)
2014 if (lightpoints_transform) {
2015 lightpoints_transform->setTransform( &shippos );
2016 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
2017 if ( sun_angle > 89 ) {
2018 lightpoints_brightness->select(0x01);
2020 lightpoints_brightness->select(0x00);
2029 sgXformPnt3( rp, rway_ols, sgTUX );
2030 vp = globals->get_current_view()->get_view_pos();
2031 to[0] = rp[0]-vp[0];
2032 to[1] = rp[1]-vp[1];
2033 to[2] = rp[2]-vp[2];
2034 float dist = sgLengthVec3( to );
2035 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
2037 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
2039 ref_elev = elev - 3.75; // +ve above, -ve below
2043 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2044 // if (ref_elev > 0.51) sel = 0x21;
2045 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
2046 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
2047 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
2048 // if (ref_elev < -0.51) sel = 0x30;
2049 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
2050 dummy_tile->lightmaps_sequence->select(sel);
2053 sgCopyVec3 (up, ship_up);
2055 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
2057 sgScaleVec3 (up, 4.0*ref_elev);
2058 dummy_tile->ols_transform->setTransform(up);
2059 //cout << "ref_elev " << ref_elev << endl;
2061 // end hack for deck lights
2064 if ( ship_sel != NULL ) {
2065 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
2069 // $$$ end - added VS Renganathan, 15 Oct 2K
2070 // added Venky , 12 Nov 2K