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>
39 #include <simgear/misc/exception.hxx>
40 #include <simgear/ephemeris/ephemeris.hxx>
41 #include <simgear/route/route.hxx>
43 #ifdef SG_MATH_EXCEPTION_CLASH
56 #include <string.h> // for strcmp()
63 #ifdef HAVE_SYS_STAT_H
64 # include <sys/stat.h> // for stat()
68 # include <unistd.h> // for stat()
71 #include <plib/netChat.h>
75 #include <simgear/constants.h> // for VERSION
76 #include <simgear/debug/logstream.hxx>
77 #include <simgear/math/polar3d.hxx>
78 #include <simgear/math/sg_random.h>
79 #include <simgear/misc/sg_path.hxx>
80 #include <simgear/sky/sky.hxx>
81 #include <simgear/timing/sg_time.hxx>
83 #include <Include/general.hxx>
85 #include <Aircraft/aircraft.hxx>
87 #include <ATC/ATCmgr.hxx>
88 #include <ATC/ATCdisplay.hxx>
89 #include <ATC/AIMgr.hxx>
91 #include <Autopilot/newauto.hxx>
93 #include <Cockpit/cockpit.hxx>
94 #include <Cockpit/radiostack.hxx>
95 #include <Cockpit/steam.hxx>
97 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
99 #include <Model/acmodel.hxx>
100 #include <Model/modelmgr.hxx>
101 #ifdef FG_NETWORK_OLK
102 #include <NetworkOLK/network.h>
104 #include <Objects/matlib.hxx>
105 #include <Scenery/scenery.hxx>
106 #include <Scenery/tilemgr.hxx>
107 #ifdef ENABLE_AUDIO_SUPPORT
108 # include <Sound/soundmgr.hxx>
109 # include <Sound/fg_fx.hxx>
110 # include <Sound/morse.hxx>
112 #include <Time/FGEventMgr.hxx>
113 #include <Time/fg_timer.hxx>
114 #include <Time/light.hxx>
115 #include <Time/sunpos.hxx>
116 #include <Time/tmp.hxx>
118 #include <Input/input.hxx>
121 #include <simgear/misc/sgstream.hxx>
122 #include <simgear/math/point3d.hxx>
123 #include <FDM/flight.hxx>
124 #include <FDM/ADA.hxx>
125 #include <Scenery/tileentry.hxx>
128 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
129 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
131 float default_attenuation[3] = {1.0, 0.0, 0.0};
132 //Required for using GL_extensions
133 void fgLoadDCS (void);
134 void fgUpdateDCS (void);
135 ssgSelector *ship_sel=NULL;
136 // upto 32 instances of a same object can be loaded.
137 ssgTransform *ship_pos[32];
138 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
140 ssgSelector *lightpoints_brightness = new ssgSelector;
141 ssgTransform *lightpoints_transform = new ssgTransform;
142 FGTileEntry *dummy_tile;
145 // Clip plane settings...
146 float scene_nearplane = 0.5f;
147 float scene_farplane = 120000.0f;
150 #ifndef FG_NEW_ENVIRONMENT
151 # include <WeatherCM/FGLocalWeatherDatabase.h>
153 # include <Environment/environment_mgr.hxx>
158 #include "fg_init.hxx"
160 #include "fg_props.hxx"
161 #include "globals.hxx"
162 #include "splash.hxx"
163 #include "viewmgr.hxx"
164 #include "options.hxx"
165 #include "logger.hxx"
168 # include <console.h> // -dw- for command line dialog
172 FGEventMgr global_events;
174 // This is a record containing a bit of global housekeeping information
177 // Specify our current idle function state. This is used to run all
178 // our initializations out of the glutIdleLoop() so that we can get a
179 // splash screen up and running right away.
180 static int idle_state = 0;
181 static long global_multi_loop;
183 // forward declaration
184 void fgReshape( int width, int height );
187 ssgRoot *scene = NULL;
188 ssgBranch *terrain_branch = NULL;
189 ssgBranch *gnd_lights_branch = NULL;
190 ssgBranch *rwy_lights_branch = NULL;
192 // fog constants. I'm a little nervous about putting actual code out
193 // here but it seems to work (?)
194 static const double m_log01 = -log( 0.01 );
195 static const double sqrt_m_log01 = sqrt( m_log01 );
196 static GLfloat fog_exp_density;
197 static GLfloat fog_exp2_density;
198 static GLfloat fog_exp2_punch_through;
200 ssgRoot *lighting = NULL;
201 // ssgBranch *airport = NULL;
203 #ifdef FG_NETWORK_OLK
204 ssgSelector *fgd_sel = NULL;
205 ssgTransform *fgd_pos = NULL;
208 // current fdm/position used for view
209 FGInterface cur_view_fdm;
215 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
217 { 1.0f, 0.0f, 0.0f, 0.0f },
218 { 0.0f, 0.0f, -1.0f, 0.0f },
219 { 0.0f, 1.0f, 0.0f, 0.0f },
220 { 0.0f, 0.0f, 0.0f, 1.0f }
223 // The following defines flightgear options. Because glutlib will also
224 // want to parse its own options, those options must not be included here
225 // or they will get parsed by the main program option parser. Hence case
226 // is significant for any option added that might be in conflict with
229 // glutlib parses for:
231 // -direct (invalid in Win32)
235 // -indirect (invalid in Win32)
238 // Note that glutlib depends upon strings while this program's
239 // option parser wants only initial characters followed by numbers
244 ssgSimpleState *default_state;
245 ssgSimpleState *hud_and_panel;
246 ssgSimpleState *menus;
248 SGTimeStamp start_time_stamp;
249 SGTimeStamp current_time_stamp;
251 void fgBuildRenderStates( void ) {
252 default_state = new ssgSimpleState;
253 default_state->ref();
254 default_state->disable( GL_TEXTURE_2D );
255 default_state->enable( GL_CULL_FACE );
256 default_state->enable( GL_COLOR_MATERIAL );
257 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
258 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
259 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
260 default_state->disable( GL_BLEND );
261 default_state->disable( GL_ALPHA_TEST );
262 default_state->disable( GL_LIGHTING );
264 hud_and_panel = new ssgSimpleState;
265 hud_and_panel->ref();
266 hud_and_panel->disable( GL_CULL_FACE );
267 hud_and_panel->disable( GL_TEXTURE_2D );
268 hud_and_panel->disable( GL_LIGHTING );
269 hud_and_panel->enable( GL_BLEND );
271 menus = new ssgSimpleState;
273 menus->disable( GL_CULL_FACE );
274 menus->disable( GL_TEXTURE_2D );
275 menus->enable( GL_BLEND );
279 // fgInitVisuals() -- Initialize various GL/view parameters
280 void fgInitVisuals( void ) {
283 l = &cur_light_params;
285 #ifndef GLUT_WRONG_VERSION
286 // Go full screen if requested ...
287 if ( fgGetBool("/sim/startup/fullscreen") ) {
292 // If enabled, normal vectors specified with glNormal are scaled
293 // to unit length after transformation. Enabling this has
294 // performance implications. See the docs for glNormal.
295 // glEnable( GL_NORMALIZE );
297 glEnable( GL_LIGHTING );
298 glEnable( GL_LIGHT0 );
299 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
302 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
303 ssgGetLight( 0 ) -> setPosition( sunpos );
305 glFogi (GL_FOG_MODE, GL_EXP2);
306 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
307 (!fgGetBool("/sim/rendering/shading"))) {
308 // if fastest fog requested, or if flat shading force fastest
309 glHint ( GL_FOG_HINT, GL_FASTEST );
310 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
311 glHint ( GL_FOG_HINT, GL_NICEST );
313 if ( fgGetBool("/sim/rendering/wireframe") ) {
315 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
318 // This is the default anyways, but it can't hurt
319 glFrontFace ( GL_CCW );
322 // glEnable(GL_POINT_SMOOTH);
323 // glEnable(GL_LINE_SMOOTH);
324 // glEnable(GL_POLYGON_SMOOTH);
328 // For HiRes screen Dumps using Brian Pauls TR Library
329 void trRenderFrame( void ) {
331 if ( fgPanelVisible() ) {
332 GLfloat height = fgGetInt("/sim/startup/ysize");
334 (current_panel->getViewHeight() - current_panel->getYOffset())
335 * (height / 768.0) + 1;
336 glTranslatef( 0.0, view_h, 0.0 );
339 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
340 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
342 fgLIGHT *l = &cur_light_params;
344 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
345 l->adj_fog_color[2], l->adj_fog_color[3]);
347 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
349 // set the opengl state to known default values
350 default_state->force();
353 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
354 glFogi ( GL_FOG_MODE, GL_EXP2 );
355 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
357 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
358 // we only update GL_AMBIENT for our lights we will never get
359 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
360 // explicitely to black.
361 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
363 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
365 // texture parameters
366 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
367 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
369 // we need a white diffuse light for the phase of the moon
370 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
373 // draw the ssg scene
374 // return to the desired diffuse color
375 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
376 glEnable( GL_DEPTH_TEST );
377 ssgSetNearFar( scene_nearplane, scene_farplane );
378 ssgCullAndDraw( scene );
381 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
382 ssgSetNearFar( scene_nearplane, scene_farplane );
383 ssgCullAndDraw( lighting );
385 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
387 globals->get_model_mgr()->draw();
388 globals->get_aircraft_model()->draw();
390 // need to do this here as hud_and_panel state is static to
391 // main.cxx and HUD and Panel routines have to be called with
392 // knowledge of the the TR struct < see gui.cxx::HighResDump()
393 hud_and_panel->apply();
397 // Update all Visuals (redraws anything graphics related)
398 void fgRenderFrame( void ) {
400 static long old_elapsed_ms = 0;
402 int dt_ms = int(globals->get_elapsed_time_ms() - old_elapsed_ms);
403 old_elapsed_ms = globals->get_elapsed_time_ms();
405 // Process/manage pending events
406 global_events.update( dt_ms );
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");
415 // Update the default (kludged) properties.
418 FGViewer *current__view = globals->get_current_view();
420 fgLIGHT *l = &cur_light_params;
421 static double last_visibility = -9999;
424 double actual_visibility = thesky->get_visibility();
425 if ( actual_visibility != last_visibility ) {
426 last_visibility = actual_visibility;
428 fog_exp_density = m_log01 / actual_visibility;
429 fog_exp2_density = sqrt_m_log01 / actual_visibility;
430 fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 2.5 );
434 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
435 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
436 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
437 // GLfloat mat_shininess[] = { 10.0 };
438 GLbitfield clear_mask;
440 if ( idle_state != 1000 ) {
441 // still initializing, draw the splash screen
442 if ( fgGetBool("/sim/startup/splash-screen") ) {
445 start_time_stamp.stamp(); // Keep resetting the start time
447 // idle_state is now 1000 meaning we've finished all our
448 // initializations and are running the main loop, so this will
449 // now work without seg faulting the system.
451 // Update the elapsed time.
452 current_time_stamp.stamp();
453 globals->set_elapsed_time_ms( (current_time_stamp - start_time_stamp)
456 // calculate our current position in cartesian space
457 scenery.set_center( scenery.get_next_center() );
460 fgReshape( fgGetInt("/sim/startup/xsize"),
461 fgGetInt("/sim/startup/ysize") );
463 // set the sun position
464 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
466 clear_mask = GL_DEPTH_BUFFER_BIT;
467 if ( fgGetBool("/sim/rendering/wireframe") ) {
468 clear_mask |= GL_COLOR_BUFFER_BIT;
471 if ( fgGetBool("/sim/rendering/skyblend") ) {
472 if ( fgGetBool("/sim/rendering/textures") ) {
473 // glClearColor(black[0], black[1], black[2], black[3]);
474 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
475 l->adj_fog_color[2], l->adj_fog_color[3]);
476 clear_mask |= GL_COLOR_BUFFER_BIT;
479 glClearColor(l->sky_color[0], l->sky_color[1],
480 l->sky_color[2], l->sky_color[3]);
481 clear_mask |= GL_COLOR_BUFFER_BIT;
483 glClear( clear_mask );
485 // Tell GL we are switching to model view parameters
487 // I really should create a derived ssg node or use a call
488 // back or something so that I can draw the sky within the
489 // ssgCullAndDraw() function, but for now I just mimic what
490 // ssg does to set up the model view matrix
491 glMatrixMode(GL_MODELVIEW);
493 ssgSetCamera( (sgVec4 *)current__view->get_VIEW() );
495 // set the opengl state to known default values
496 default_state->force();
498 // update fog params if visibility has changed
499 double visibility_meters = fgGetDouble("/environment/visibility-m");
500 thesky->set_visibility(visibility_meters);
502 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
503 ( global_multi_loop * fgGetInt("/sim/speed-up") )
504 / (double)fgGetInt("/sim/model-hz") );
506 // Set correct opengl fog density
507 glFogf (GL_FOG_DENSITY, fog_exp2_density);
509 // update the sky dome
510 if ( fgGetBool("/sim/rendering/skyblend") ) {
511 /* cout << "thesky->repaint() sky_color = "
512 << cur_light_params.sky_color[0] << " "
513 << cur_light_params.sky_color[1] << " "
514 << cur_light_params.sky_color[2] << " "
515 << cur_light_params.sky_color[3] << endl;
517 << cur_light_params.fog_color[0] << " "
518 << cur_light_params.fog_color[1] << " "
519 << cur_light_params.fog_color[2] << " "
520 << cur_light_params.fog_color[3] << endl;
521 cout << " sun_angle = " << cur_light_params.sun_angle
522 << " moon_angle = " << cur_light_params.moon_angle
524 thesky->repaint( cur_light_params.sky_color,
525 cur_light_params.adj_fog_color,
526 cur_light_params.sun_angle,
527 cur_light_params.moon_angle,
528 globals->get_ephem()->getNumPlanets(),
529 globals->get_ephem()->getPlanets(),
530 globals->get_ephem()->getNumStars(),
531 globals->get_ephem()->getStars() );
533 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
534 << view_pos[1] << " " << view_pos[2] << endl;
535 cout << " zero_elev = " << zero_elev[0] << " "
536 << zero_elev[1] << " " << zero_elev[2]
537 << " lon = " << cur_fdm_state->get_Longitude()
538 << " lat = " << cur_fdm_state->get_Latitude() << endl;
539 cout << " sun_rot = " << cur_light_params.sun_rotation
540 << " gst = " << SGTime::cur_time_params->getGst() << endl;
541 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
542 << " sun dec = " << globals->get_ephem()->getSunDeclination()
543 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
544 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
546 thesky->reposition( current__view->get_view_pos(),
547 current__view->get_zero_elev(),
548 current__view->get_world_up(),
549 longitude->getDoubleValue()
550 * SGD_DEGREES_TO_RADIANS,
551 latitude->getDoubleValue()
552 * SGD_DEGREES_TO_RADIANS,
553 altitude->getDoubleValue() * SG_FEET_TO_METER,
554 cur_light_params.sun_rotation,
555 globals->get_time_params()->getGst(),
556 globals->get_ephem()->getSunRightAscension(),
557 globals->get_ephem()->getSunDeclination(),
559 globals->get_ephem()->getMoonRightAscension(),
560 globals->get_ephem()->getMoonDeclination(),
564 glEnable( GL_DEPTH_TEST );
565 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
567 glFogi( GL_FOG_MODE, GL_EXP2 );
568 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
571 // set sun/lighting parameters
572 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
574 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
575 // we only update GL_AMBIENT for our lights we will never get
576 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
577 // explicitely to black.
578 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
579 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
580 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
582 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
583 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
584 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
586 // texture parameters
587 // glEnable( GL_TEXTURE_2D );
588 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
589 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
591 // glMatrixMode( GL_PROJECTION );
593 ssgSetFOV( current__view->get_h_fov(),
594 current__view->get_v_fov() );
596 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
597 - scenery.get_cur_elev();
599 // if (fgGetBool("/sim/view/internal"))
600 // ssgSetNearFar( 0.2f, 120000.0f );
601 // else if ( agl > 10.0)
604 scene_nearplane = 10.0f;
605 scene_farplane = 120000.0f;
607 scene_nearplane = 0.5f;
608 scene_farplane = 120000.0f;
611 ssgSetNearFar( scene_nearplane, scene_farplane );
613 // $$$ begin - added VS Renganthan 17 Oct 2K
616 // $$$ end - added VS Renganthan 17 Oct 2K
618 # ifdef FG_NETWORK_OLK
619 if ( fgGetBool("/sim/networking/network-olk") ) {
621 other = head->next; /* put listpointer to start */
622 while ( other != tail) { /* display all except myself */
623 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
624 other->fgd_sel->select(1);
625 sgSetCoord( &fgdpos, other->sgFGD_COORD );
626 other->fgd_pos->setTransform( &fgdpos );
631 // fgd_sel->select(1);
632 // sgCopyMat4( sgTUX, current_view.sgVIEW);
634 // sgSetCoord( &fgdpos, sgFGD_VIEW );
635 // fgd_pos->setTransform( &fgdpos);
639 // position tile nodes and update range selectors
640 global_tile_mgr.prep_ssg_nodes(visibility_meters);
642 if ( fgGetBool("/sim/rendering/skyblend") ) {
643 // draw the sky backdrop
645 // we need a white diffuse light for the phase of the moon
646 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
650 // return to the desired diffuse color
651 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
654 // draw the ssg scene
655 glEnable( GL_DEPTH_TEST );
657 ssgSetNearFar( scene_nearplane, scene_farplane );
658 ssgCullAndDraw( scene );
660 // change state for lighting here
663 // Set punch through fog density
664 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
666 #ifdef FG_EXPERIMENTAL_LIGHTING
667 // Enable states for drawing points with GL_extension
668 if (glutExtensionSupported("GL_EXT_point_parameters")) {
669 glEnable(GL_POINT_SMOOTH);
670 float quadratic[3] = {1.0, 0.01, 0.0001};
671 // get the address of our OpenGL extensions
673 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
674 wglGetProcAddress("glPointParameterfEXT");
675 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
676 wglGetProcAddress("glPointParameterfvEXT");
678 // makes the points fade as they move away
679 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
680 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
683 // Enable states for drawing runway lights with spherical mapping
684 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
685 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
686 glEnable(GL_TEXTURE_GEN_S);
687 glEnable(GL_TEXTURE_GEN_T);
689 //Maybe this is not the best way, but it works !!
690 glPolygonMode(GL_FRONT, GL_POINT);
692 glEnable(GL_CULL_FACE);
695 glDisable( GL_LIGHTING );
696 // blending function for runway lights
697 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
701 ssgSetNearFar( scene_nearplane, scene_farplane );
702 ssgCullAndDraw( lighting );
705 #ifdef FG_EXPERIMENTAL_LIGHTING
706 if (glutExtensionSupported("GL_EXT_point_parameters")) {
707 // Disable states used for runway lighting
708 glPolygonMode(GL_FRONT, GL_FILL);
710 glDisable(GL_TEXTURE_GEN_S);
711 glDisable(GL_TEXTURE_GEN_T);
712 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
713 default_attenuation);
719 if ( fgGetBool("/sim/rendering/skyblend") ) {
720 // draw the sky cloud layers
721 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
724 globals->get_model_mgr()->draw();
725 globals->get_aircraft_model()->draw();
727 // display HUD && Panel
729 glDisable( GL_DEPTH_TEST );
730 // glDisable( GL_CULL_FACE );
731 // glDisable( GL_TEXTURE_2D );
733 // update the input subsystem
734 current_input.update(dt_ms);
736 // update the controls subsystem
737 globals->get_controls()->update(dt_ms);
739 hud_and_panel->apply();
742 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
743 // This only works properly if called before the panel call
744 globals->get_ATC_display()->update(dt_ms);
746 // update the panel subsystem
747 if ( current_panel != NULL ) {
748 current_panel->update(dt_ms);
751 // We can do translucent menus, so why not. :-)
753 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
755 // glDisable ( GL_BLEND ) ;
757 // glEnable( GL_FOG );
759 globals->get_logger()->update(dt_ms);
766 // Update internal time dependent calculations (i.e. flight model)
767 void fgUpdateTimeDepCalcs() {
768 static bool inited = false;
769 static const SGPropertyNode *master_freeze
770 = fgGetNode("/sim/freeze/master");
772 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
774 fgLIGHT *l = &cur_light_params;
779 // Initialize the FDM here if it hasn't been and if we have a
780 // scenery elevation hit.
782 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
783 // << " cur_elev = " << scenery.get_cur_elev() << endl;
785 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
786 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
788 cur_fdm_state->init();
789 if ( cur_fdm_state->get_bound() ) {
790 cur_fdm_state->unbind();
792 cur_fdm_state->bind();
795 // conceptually, the following block could be done for each fdm
797 if ( !cur_fdm_state->get_inited() ) {
798 // do nothing, fdm isn't inited yet
799 } else if ( master_freeze->getBoolValue() ) {
800 // we are frozen, run the fdm's with 0 time slices in case
801 // they want to do something with that.
803 cur_fdm_state->update( 0 );
804 FGSteam::update( 0 );
806 // we have been inited, and we are not frozen, we are good to go ...
809 cur_fdm_state->stamp();
815 long elapsed = current - cur_fdm_state->get_time_stamp();
816 cur_fdm_state->set_time_stamp( current );
817 elapsed += cur_fdm_state->get_remainder();
818 // cout << "elapsed = " << elapsed << endl;
819 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
820 multi_loop = (long)(((double)elapsed * 0.000001) /
821 cur_fdm_state->get_delta_t() );
822 cur_fdm_state->set_multi_loop( multi_loop );
823 long remainder = elapsed - (long)( (multi_loop*1000000) *
824 cur_fdm_state->get_delta_t() );
825 cur_fdm_state->set_remainder( remainder );
826 // cout << "remainder = " << remainder << endl;
828 // chop max interations to something reasonable if the sim was
829 // delayed for an excesive amount of time
830 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
831 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
832 cur_fdm_state->set_remainder( 0 );
835 // cout << "multi_loop = " << multi_loop << endl;
836 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
837 // run Autopilot system
838 globals->get_autopilot()->update(0); // FIXME: use real dt
841 cur_fdm_state->update( 1 );
843 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
846 if ( !strcmp(fgGetString("/sim/view-mode"), "pilot") ) {
847 cur_view_fdm = *cur_fdm_state;
852 globals->get_model_mgr()->update(multi_loop);
853 globals->get_aircraft_model()->update(multi_loop);
855 // update the view angle
856 globals->get_viewmgr()->update(multi_loop);
860 // Update solar system
861 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
862 globals->get_time_params()->getLst(),
863 cur_fdm_state->get_Latitude() );
865 // Update radio stack model
866 current_radiostack->update(multi_loop);
870 void fgInitTimeDepCalcs( void ) {
875 static const double alt_adjust_ft = 3.758099;
876 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
879 // What should we do when we have nothing else to do? Let's get ready
880 // for the next move and update the display?
881 static void fgMainLoop( void ) {
882 static const SGPropertyNode *longitude
883 = fgGetNode("/position/longitude-deg");
884 static const SGPropertyNode *latitude
885 = fgGetNode("/position/latitude-deg");
886 static const SGPropertyNode *altitude
887 = fgGetNode("/position/altitude-ft");
888 static const SGPropertyNode *clock_freeze
889 = fgGetNode("/sim/freeze/clock", true);
890 static const SGPropertyNode *cur_time_override
891 = fgGetNode("/sim/time/cur-time-override", true);
893 static long remainder = 0;
895 #ifdef FANCY_FRAME_COUNTER
899 static time_t last_time = 0;
900 static int frames = 0;
901 #endif // FANCY_FRAME_COUNTER
903 SGTime *t = globals->get_time_params();
905 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
906 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
908 #ifdef FG_NETWORK_OLK
909 if ( fgGetBool("/sim/networking/network-olk") ) {
910 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
911 // printf("FGD: Netupdate\n");
912 fgd_send_com( "A", FGFS_host); // Send Mat4 data
913 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
918 #if defined( ENABLE_PLIB_JOYSTICK )
919 // Read joystick and update control settings
920 // if ( fgGetString("/sim/control-mode") == "joystick" )
924 #elif defined( ENABLE_GLUT_JOYSTICK )
925 // Glut joystick support works by feeding a joystick handler
926 // function to glut. This is taken care of once in the joystick
927 // init routine and we don't have to worry about it again.
930 #ifdef FG_NEW_ENVIRONMENT
931 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
934 // Fix elevation. I'm just sticking this here for now, it should
935 // probably move eventually
937 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
938 scenery.get_cur_elev(),
939 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
940 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
942 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
943 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
944 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
945 // now set aircraft altitude above ground
946 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
947 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
948 scenery.get_cur_elev() + alt_adjust_m - 3.0,
949 scenery.get_cur_elev() + alt_adjust_m );
950 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
953 SG_LOG( SG_ALL, SG_DEBUG,
954 "<*> resetting altitude to "
955 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
960 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
961 scenery.get_cur_elev(),
962 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
963 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
965 // cout << "Warp = " << globals->get_warp() << endl;
968 static bool last_clock_freeze = false;
970 if ( clock_freeze->getBoolValue() ) {
971 // clock freeze requested
972 if ( cur_time_override->getLongValue() == 0 ) {
973 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
974 globals->set_warp( 0 );
977 // no clock freeze requested
978 if ( last_clock_freeze == true ) {
979 // clock just unfroze, let's set warp as the difference
980 // between frozen time and current time so we don't get a
981 // time jump (and corresponding sky object and lighting
983 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
984 fgSetLong( "/sim/time/cur-time-override", 0 );
986 if ( globals->get_warp_delta() != 0 ) {
987 globals->inc_warp( globals->get_warp_delta() );
991 last_clock_freeze = clock_freeze->getBoolValue();
993 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
994 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
995 cur_time_override->getLongValue(),
996 globals->get_warp() );
998 if ( globals->get_warp_delta() != 0 ) {
999 fgUpdateSkyAndLightingParams();
1002 // update magvar model
1003 globals->get_mag()->update( longitude->getDoubleValue()
1004 * SGD_DEGREES_TO_RADIANS,
1005 latitude->getDoubleValue()
1006 * SGD_DEGREES_TO_RADIANS,
1007 altitude->getDoubleValue() * SG_FEET_TO_METER,
1008 globals->get_time_params()->getJD() );
1010 // Get elapsed time (in usec) for this past frame
1011 elapsed = fgGetTimeInterval();
1012 SG_LOG( SG_ALL, SG_DEBUG,
1013 "Elapsed time interval is = " << elapsed
1014 << ", previous remainder is = " << remainder );
1016 // Calculate frame rate average
1017 #ifdef FANCY_FRAME_COUNTER
1018 /* old fps calculation */
1019 if ( elapsed > 0 ) {
1022 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1023 tmp = general.get_frame(i);
1025 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1026 general.set_frame(i+1,tmp);
1028 tmp = 1000000.0 / (float)elapsed;
1029 general.set_frame(0,tmp);
1030 // printf("frame[0] = %.2f\n", general.frames[0]);
1032 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1033 // printf("ave = %.2f\n", general.frame_rate);
1036 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1037 general.set_frame_rate( frames );
1038 SG_LOG( SG_ALL, SG_DEBUG,
1039 "--> Frame rate is = " << general.get_frame_rate() );
1042 last_time = t->get_cur_time();
1046 // Run ATC subsystem
1047 globals->get_ATC_mgr()->update(1); // FIXME - use real dt.
1049 // Run the AI subsystem
1050 globals->get_AI_mgr()->update(1); // FIXME - use real dt.
1054 // Calculate model iterations needed for next frame
1055 elapsed += remainder;
1057 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1058 fgGetInt("/sim/model-hz"));
1059 remainder = elapsed - ( (global_multi_loop*1000000) /
1060 fgGetInt("/sim/model-hz") );
1061 SG_LOG( SG_ALL, SG_DEBUG,
1062 "Model iterations needed = " << global_multi_loop
1063 << ", new remainder = " << remainder );
1065 // chop max interations to something reasonable if the sim was
1066 // delayed for an excesive amount of time
1067 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1068 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1073 if ( global_multi_loop > 0 ) {
1074 fgUpdateTimeDepCalcs();
1076 SG_LOG( SG_ALL, SG_DEBUG,
1077 "Elapsed time is zero ... we're zinging" );
1080 #if ! defined( macintosh )
1081 // Do any I/O channel work that might need to be done
1085 // see if we need to load any new scenery tiles
1086 double visibility_meters = fgGetDouble("/environment/visibility-m");
1087 global_tile_mgr.update( longitude->getDoubleValue(),
1088 latitude->getDoubleValue(), visibility_meters );
1090 // see if we need to load any deferred-load textures
1091 material_lib.load_next_deferred();
1093 // Run audio scheduler
1094 #ifdef ENABLE_AUDIO_SUPPORT
1095 if ( fgGetBool("/sim/sound/audible")
1096 && globals->get_soundmgr()->is_working() ) {
1097 globals->get_fx()->update(1); // FIXME: use dt
1098 globals->get_soundmgr()->update(1); // FIXME: use dt
1105 SG_LOG( SG_ALL, SG_DEBUG, "" );
1109 // This is the top level master main function that is registered as
1110 // our idle funciton
1112 // The first few passes take care of initialization things (a couple
1113 // per pass) and once everything has been initialized fgMainLoop from
1116 static void fgIdleFunction ( void ) {
1117 // printf("idle state == %d\n", idle_state);
1119 if ( idle_state == 0 ) {
1120 // Initialize the splash screen right away
1121 if ( fgGetBool("/sim/startup/splash-screen") ) {
1126 } else if ( idle_state == 1 ) {
1127 // Initialize audio support
1128 #ifdef ENABLE_AUDIO_SUPPORT
1130 // Start the intro music
1131 if ( fgGetBool("/sim/startup/intro-music") ) {
1132 SGPath mp3file( globals->get_fg_root() );
1133 mp3file.append( "Sounds/intro.mp3" );
1135 SG_LOG( SG_GENERAL, SG_INFO,
1136 "Starting intro music: " << mp3file.str() );
1138 #if defined( __CYGWIN__ )
1139 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1140 #elif defined( WIN32 )
1141 string command = "start /m " + mp3file.str();
1143 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1146 system ( command.c_str() );
1149 // This is an 'easter egg' which is kind of a hard thing to
1150 // hide in an open source project -- so I won't try very hard
1151 // to hide it. If you are looking at this now, please, you
1152 // don't want to ruin the surprise. :-) Just forget about it
1153 // and don't look any further; unless it is causing an actual
1154 // problem for you, which it shouldn't, and I hope it doesn't!
1156 if ( globals->get_time_params()->getGmt()->tm_mon == 4
1157 && globals->get_time_params()->getGmt()->tm_mday == 19 )
1159 string url = "http://www.flightgear.org/Music/invasion.mp3";
1160 #if defined( __CYGWIN__ ) || defined( WIN32 )
1161 string command = "start /m " + url;
1163 string command = "mpg123 " + url + "> /dev/null 2>&1";
1165 system( command.c_str() );
1171 } else if ( idle_state == 2 ) {
1172 // These are a few miscellaneous things that aren't really
1173 // "subsystems" but still need to be initialized.
1176 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1177 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1182 } else if ( idle_state == 3 ) {
1183 // This is the top level init routine which calls all the
1184 // other subsystem initialization routines. If you are adding
1185 // a subsystem to flightgear, its initialization call should
1186 // located in this routine.
1187 if( !fgInitSubsystems()) {
1188 SG_LOG( SG_GENERAL, SG_ALERT,
1189 "Subsystem initializations failed ..." );
1194 } else if ( idle_state == 4 ) {
1195 // setup OpenGL view parameters
1199 } else if ( idle_state == 5 ) {
1202 } else if ( idle_state == 6 ) {
1206 cout << "Panel visible = " << fgPanelVisible() << endl;
1207 fgReshape( fgGetInt("/sim/startup/xsize"),
1208 fgGetInt("/sim/startup/ysize") );
1211 if ( idle_state == 1000 ) {
1212 // We've finished all our initialization steps, from now on we
1213 // run the main loop.
1215 glutIdleFunc(fgMainLoop);
1217 if ( fgGetBool("/sim/startup/splash-screen") ) {
1218 fgSplashUpdate(0.0);
1223 // options.cxx needs to see this for toggle_panel()
1224 // Handle new window size or exposure
1225 void fgReshape( int width, int height ) {
1228 if ( (!fgGetBool("/sim/virtual-cockpit"))
1229 && fgPanelVisible() && idle_state == 1000 ) {
1230 view_h = (int)(height * (current_panel->getViewHeight() -
1231 current_panel->getYOffset()) / 768.0);
1237 FGViewMgr *viewmgr = globals->get_viewmgr();
1238 for ( int i = 0; i < viewmgr->size(); ++i ) {
1239 viewmgr->get_view(i)->
1240 set_aspect_ratio((float)view_h / (float)width);
1243 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1245 fgSetInt("/sim/startup/xsize", width);
1246 fgSetInt("/sim/startup/ysize", height);
1247 guiInitMouse(width, height);
1249 ssgSetFOV( viewmgr->get_current_view()->get_h_fov(),
1250 viewmgr->get_current_view()->get_v_fov() );
1255 // Initialize GLUT and define a main window
1256 int fgGlutInit( int *argc, char **argv ) {
1258 #if !defined( macintosh )
1259 // GLUT will extract all glut specific options so later on we only
1260 // need wory about our own.
1261 glutInit(argc, argv);
1264 // Define Display Parameters
1265 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1267 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1268 fgGetInt("/sim/startup/xsize") << "x"
1269 << fgGetInt("/sim/startup/ysize") );
1271 // Define initial window size
1272 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1273 fgGetInt("/sim/startup/ysize") );
1275 // Initialize windows
1276 if ( !fgGetBool("/sim/startup/game-mode")) {
1277 // Open the regular window
1278 glutCreateWindow("FlightGear");
1279 #ifndef GLUT_WRONG_VERSION
1281 // Open the cool new 'game mode' window
1282 char game_mode_str[256];
1283 //#define SYNC_OPENGL_WITH_DESKTOP_SETTINGS
1284 #if defined(WIN32) && defined(SYNC_OPENGL_WITH_DESKTOP_SETTINGS)
1285 #ifndef ENUM_CURRENT_SETTINGS
1286 #define ENUM_CURRENT_SETTINGS ((DWORD)-1)
1287 #define ENUM_REGISTRY_SETTINGS ((DWORD)-2)
1291 dm.dmSize = sizeof(DEVMODE);
1292 EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm);
1293 fgSetInt("/sim/startup/xsize", dm.dmPelsWidth);
1294 fgSetInt("/sim/startup/ysize", dm.dmPelsHeight);
1295 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1296 fgGetInt("/sim/startup/ysize") );
1297 sprintf( game_mode_str, "%dx%d:%d@%d",
1301 dm.dmDisplayFrequency );
1303 // Open the cool new 'game mode' window
1304 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1305 fgGetInt("/sim/startup/xsize"),
1306 fgGetInt("/sim/startup/ysize"),
1307 fgGetInt("/sim/rendering/bits-per-pixel"));
1309 #endif // HAVE_WINDOWS_H
1310 SG_LOG( SG_GENERAL, SG_INFO,
1311 "game mode params = " << game_mode_str );
1312 glutGameModeString( game_mode_str );
1313 glutEnterGameMode();
1314 #endif // GLUT_WRONG_VERSION
1317 // This seems to be the absolute earliest in the init sequence
1318 // that these calls will return valid info. Too bad it's after
1319 // we've already created and sized out window. :-(
1320 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1321 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1322 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1323 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1326 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1327 general.set_glMaxTexSize( tmp );
1328 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1330 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1331 general.set_glDepthBits( tmp );
1332 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1338 // Initialize GLUT event handlers
1339 int fgGlutInitEvents( void ) {
1340 // call fgReshape() on window resizes
1341 glutReshapeFunc( fgReshape );
1343 // keyboard and mouse callbacks are set in FGInput::init
1346 // call guiMouseFunc() whenever our little rodent is used
1347 glutMouseFunc ( guiMouseFunc );
1348 glutMotionFunc (guiMotionFunc );
1349 glutPassiveMotionFunc (guiMotionFunc );
1352 // call fgMainLoop() whenever there is
1353 // nothing else to do
1354 glutIdleFunc( fgIdleFunction );
1357 glutDisplayFunc( fgRenderFrame );
1364 int mainLoop( int argc, char **argv ) {
1366 #if defined( macintosh )
1367 freopen ("stdout.txt", "w", stdout );
1368 freopen ("stderr.txt", "w", stderr );
1369 argc = ccommand( &argv );
1372 // set default log levels
1373 sglog().setLogLevels( SG_ALL, SG_INFO );
1376 #ifdef FLIGHTGEAR_VERSION
1377 version = FLIGHTGEAR_VERSION;
1379 version = "unknown version";
1381 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1382 << version << endl );
1384 // Allocate global data structures. This needs to happen before
1385 // we parse command line options
1387 globals = new FGGlobals;
1389 #if defined(FG_NEW_ENVIRONMENT)
1390 globals->set_environment_mgr(new FGEnvironmentMgr);
1393 // seed the random number generater
1396 SGRoute *route = new SGRoute;
1397 globals->set_route( route );
1399 FGControls *controls = new FGControls;
1400 globals->set_controls( controls );
1402 string_list *col = new string_list;
1403 globals->set_channel_options_list( col );
1405 // Scan the config file(s) and command line options to see if
1406 // fg_root was specified (ignore all other options for now)
1407 fgInitFGRoot(argc, argv);
1409 // Check for the correct base package version
1410 string base_version = fgBasePackageVersion();
1411 if ( !(base_version == "0.7.9") ) {
1412 // tell the operator how to use this application
1415 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1416 << "Found version " << base_version << " at: "
1417 << globals->get_fg_root() );
1418 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1422 // Initialize the Aircraft directory to "" (UIUC)
1425 // Load the configuration parameters
1426 if ( !fgInitConfig(argc, argv) ) {
1427 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1431 // Initialize the Window/Graphics environment.
1432 if( !fgGlutInit(&argc, argv) ) {
1433 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1437 // Initialize the various GLUT Event Handlers.
1438 if( !fgGlutInitEvents() ) {
1439 SG_LOG( SG_GENERAL, SG_ALERT,
1440 "GLUT event handler initialization failed ..." );
1444 // Initialize plib net interface
1445 netInit( &argc, argv );
1447 // Initialize ssg (from plib). Needs to come before we do any
1448 // other ssg stuff, but after opengl/glut has been initialized.
1451 // Initialize the user interface (we need to do this before
1452 // passing off control to glut and before fgInitGeneral to get our
1456 #ifdef GL_EXT_texture_lod_bias
1457 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1460 // Set position relative to glide slope if requested
1461 fgSetPosFromGlideSlope();
1463 // set current_options lon/lat if an airport id is specified
1464 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1465 if ( fgGetString("/sim/startup/airport-id")[0] != '\0' ) {
1466 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1467 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1468 fgGetDouble("/orientation/heading-deg") );
1469 // set tower position (a little off the heading for single runway airports)
1470 fgSetTowerPosFromAirportID( fgGetString("/sim/startup/airport-id"), fgGetDouble("orientation/heading") );
1473 SGTime *t = fgInitTime();
1474 globals->set_time_params( t );
1476 // Do some quick general initializations
1477 if( !fgInitGeneral()) {
1478 SG_LOG( SG_GENERAL, SG_ALERT,
1479 "General initializations failed ..." );
1483 SGPath modelpath( globals->get_fg_root() );
1484 ssgModelPath( (char *)modelpath.c_str() );
1486 ////////////////////////////////////////////////////////////////////
1487 // Initialize the general model subsystem.
1488 ////////////////////////////////////////////////////////////////////
1490 globals->set_model_mgr(new FGModelMgr);
1491 globals->get_model_mgr()->init();
1492 globals->get_model_mgr()->bind();
1494 ////////////////////////////////////////////////////////////////////
1495 // Initialize the 3D aircraft model subsystem.
1496 ////////////////////////////////////////////////////////////////////
1498 globals->set_aircraft_model(new FGAircraftModel);
1499 globals->get_aircraft_model()->init();
1500 globals->get_aircraft_model()->bind();
1502 ////////////////////////////////////////////////////////////////////
1503 // Initialize the view manager subsystem.
1504 ////////////////////////////////////////////////////////////////////
1506 FGViewMgr *viewmgr = new FGViewMgr;
1507 globals->set_viewmgr( viewmgr );
1513 scene = new ssgRoot;
1514 scene->setName( "Scene" );
1516 lighting = new ssgRoot;
1517 lighting->setName( "Lighting" );
1519 // Initialize the sky
1520 SGPath ephem_data_path( globals->get_fg_root() );
1521 ephem_data_path.append( "Astro" );
1522 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1523 ephem->update( globals->get_time_params()->getMjd(),
1524 globals->get_time_params()->getLst(),
1526 globals->set_ephem( ephem );
1530 SGPath sky_tex_path( globals->get_fg_root() );
1531 sky_tex_path.append( "Textures" );
1532 sky_tex_path.append( "Sky" );
1533 thesky->texture_path( sky_tex_path.str() );
1535 thesky->build( 550.0, 550.0,
1536 globals->get_ephem()->getNumPlanets(),
1537 globals->get_ephem()->getPlanets(), 60000.0,
1538 globals->get_ephem()->getNumStars(),
1539 globals->get_ephem()->getStars(), 60000.0 );
1541 if ( fgGetBool("/environment/clouds/status") ) {
1542 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1543 // SG_CLOUD_OVERCAST );
1544 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1546 200.0, 50.0, 40000.0,
1547 SG_CLOUD_MOSTLY_CLOUDY );
1548 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1549 // SG_CLOUD_MOSTLY_SUNNY );
1550 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1554 // Initialize MagVar model
1555 SGMagVar *magvar = new SGMagVar();
1556 globals->set_mag( magvar );
1559 terrain_branch = new ssgBranch;
1560 terrain_branch->setName( "Terrain" );
1561 scene->addKid( terrain_branch );
1564 gnd_lights_branch = new ssgBranch;
1565 gnd_lights_branch->setName( "Ground Lighting" );
1566 lighting->addKid( gnd_lights_branch );
1568 rwy_lights_branch = new ssgBranch;
1569 rwy_lights_branch->setName( "Runway Lighting" );
1570 lighting->addKid( rwy_lights_branch );
1572 // airport = new ssgBranch;
1573 // airport->setName( "Airport Lighting" );
1574 // lighting->addKid( airport );
1580 #ifdef FG_NETWORK_OLK
1581 // Do the network intialization
1582 if ( fgGetBool("/sim/networking/network-olk") ) {
1583 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1587 // build our custom render states
1588 fgBuildRenderStates();
1590 // pass control off to the master GLUT event handler
1593 // we never actually get here ... but to avoid compiler warnings,
1599 // $$$ end - added VS Renganathan, 15 Oct 2K
1600 // - added Venky , 12 Nov 2K
1602 #if defined(__linux__) && defined(__i386__)
1604 static void handleFPE (int);
1609 fpu_control_t fpe_flags = 0;
1610 _FPU_GETCW(fpe_flags);
1611 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1612 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1613 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1614 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1615 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1616 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1617 _FPU_SETCW(fpe_flags);
1618 signal(SIGFPE, handleFPE);
1625 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1629 // Main entry point; catch any exceptions that have made it this far.
1630 int main ( int argc, char **argv ) {
1632 // Enable floating-point exceptions for Linux/x86
1633 #if defined(__linux__) && defined(__i386__)
1637 // Enable floating-point exceptions for Windows
1638 #if defined( _MSC_VER ) && defined( DEBUG )
1639 // Christian, we should document what this does
1640 _control87( _EM_INEXACT, _MCW_EM );
1643 #if defined( HAVE_BC5PLUS )
1644 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1647 // FIXME: add other, more specific
1650 mainLoop(argc, argv);
1651 } catch (sg_throwable &t) {
1652 // We must use cerr rather than
1653 // logging, since logging may be
1655 cerr << "Fatal error: " << t.getFormattedMessage()
1656 << "\n (received from " << t.getOrigin() << ')' << endl;
1664 void fgLoadDCS(void) {
1666 ssgEntity *ship_obj = NULL;
1668 char obj_filename[25];
1670 for ( int k = 0; k < 32; k++ ) {
1674 SGPath tile_path( globals->get_fg_root());
1675 tile_path.append( "Scenery" );
1676 tile_path.append( "Objects.txt" );
1677 sg_gzifstream in( tile_path.str() );
1678 if ( ! in.is_open() ) {
1679 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1682 SGPath modelpath( globals->get_fg_root() );
1683 modelpath.append( "Models" );
1684 modelpath.append( "Geometry" );
1686 SGPath texturepath( globals->get_fg_root() );
1687 texturepath.append( "Models" );
1688 texturepath.append( "Textures" );
1690 ssgModelPath( (char *)modelpath.c_str() );
1691 ssgTexturePath( (char *)texturepath.c_str() );
1693 ship_sel = new ssgSelector;
1696 while ( ! in.eof() ) {
1698 if ( in.get( c ) && c == '#' ) {
1702 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1703 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1704 int chj=getchar();*/
1706 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1707 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1709 ship_pos[objc] = new ssgTransform;
1711 // type "repeat" in objects.txt to load one more
1712 // instance of the last object.
1714 if ( strcmp(obj_filename,"repeat") != 0) {
1715 ship_obj = ssgLoad( obj_filename );
1718 if ( ship_obj != NULL ) {
1719 ship_obj->setName(obj_filename);
1721 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1723 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1724 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1725 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1726 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1729 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1733 // temporary hack for deck lights - ultimately should move to PLib (when??)
1734 //const char *extn = file_extension ( obj_filename ) ;
1736 ssgVertexArray *lights = new ssgVertexArray( 100 );
1737 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1738 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1739 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1740 int ltype[500], light_type;
1741 static int ltcount = 0;
1743 sgVec3 rway_dir,rway_normal,lightpt;
1745 modelpath.append(obj_filename);
1746 sg_gzifstream in1( modelpath.str() );
1747 if ( ! in1.is_open() ) {
1748 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1750 while ( ! in1.eof() ) {
1752 if ( in1.get( c ) && c == '#' ) {
1757 //cout << token << endl;
1758 if ( token == "runway" ) {
1760 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1761 } else if ( token == "edgelight" ) {
1763 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1765 } else if ( token == "taxi" ) {
1767 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1769 } else if ( token == "vasi" ) {
1771 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1773 } else if ( token == "threshold" ) {
1775 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1777 } else if ( token == "rabbit" ) {
1779 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1781 } else if ( token == "ols" ) {
1783 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1785 } else if ( token == "red" ) {
1787 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1789 } else if ( token == "green" ) {
1791 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1793 } else if ( token == "lp" ) {
1795 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1796 lightpoints->add( lightpt );
1797 lightnormals->add( rway_normal );
1798 lightdir->add( rway_dir );
1799 ltype[ltcount]= light_type;
1802 if (in1.eof()) break;
1806 if ( lightpoints->getNum() ) {
1807 ssgBranch *lightpoints_branch;
1808 long int dummy = -999;
1809 dummy_tile = new FGTileEntry((SGBucket)dummy);
1810 dummy_tile->lightmaps_sequence = new ssgSelector;
1811 dummy_tile->ols_transform = new ssgTransform;
1813 // call function to generate the runway lights
1814 lightpoints_branch =
1815 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1817 lightpoints_brightness->addKid(lightpoints_branch);
1818 lightpoints_transform->addKid(lightpoints_brightness);
1819 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1820 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1821 lightpoints_transform->ref();
1822 gnd_lights_branch->addKid( lightpoints_transform );
1826 // end hack for deck lights
1830 if (in.eof()) break;
1834 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1836 terrain_branch->addKid( ship_sel ); //add selector node to root node
1843 void fgUpdateDCS (void) {
1845 // double eye_lat,eye_lon,eye_alt;
1846 // static double obj_head;
1847 double sl_radius,obj_latgc;
1848 // float nresultmat[4][4];
1849 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1852 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1853 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1855 // Deck should be the first object in objects.txt in case of fdm=ada
1857 if (!strcmp(fgGetString("/sim/flight-model"), "ada")) {
1858 if ((fdm->get_iaux(1))==1)
1860 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1861 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1862 obj_alt[1] = fdm->get_daux(3);
1863 obj_pitch[1] = fdm->get_faux(1);
1864 obj_roll[1] = fdm->get_faux(2);
1868 for ( int m = 0; m < objc; m++ ) {
1869 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1872 //Geodetic to Geocentric angles for rotation
1873 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1875 //moving object gbs-posn in cartesian coords
1876 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1877 Point3D obj_pos = sgGeodToCart( obj_posn );
1879 // Translate moving object w.r.t eye
1880 Point3D Objtrans = obj_pos-scenery.get_center();
1885 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1888 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1890 sgVec3 ship_fwd,ship_rt,ship_up;
1891 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1892 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1893 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1895 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1896 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1897 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1898 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1899 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1900 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1903 sgCopyMat4( sgTUX, sgROT_hdg );
1904 sgPostMultMat4( sgTUX, sgROT_pitch );
1905 sgPostMultMat4( sgTUX, sgROT_roll );
1906 sgPostMultMat4( sgTUX, sgROT_lat );
1907 sgPostMultMat4( sgTUX, sgROT_lon );
1908 sgPostMultMat4( sgTUX, sgTRANS );
1911 sgSetCoord(&shippos, sgTUX );
1912 ship_pos[m]->setTransform( &shippos );
1913 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1915 if (lightpoints_transform) {
1916 lightpoints_transform->setTransform( &shippos );
1917 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1918 if ( sun_angle > 89 ) {
1919 lightpoints_brightness->select(0x01);
1921 lightpoints_brightness->select(0x00);
1930 sgXformPnt3( rp, rway_ols, sgTUX );
1931 vp = globals->get_current_view()->get_view_pos();
1932 to[0] = rp[0]-vp[0];
1933 to[1] = rp[1]-vp[1];
1934 to[2] = rp[2]-vp[2];
1935 float dist = sgLengthVec3( to );
1936 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1938 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1940 ref_elev = elev - 3.75; // +ve above, -ve below
1944 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1945 // if (ref_elev > 0.51) sel = 0x21;
1946 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1947 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1948 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1949 // if (ref_elev < -0.51) sel = 0x30;
1950 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1951 dummy_tile->lightmaps_sequence->select(sel);
1954 sgCopyVec3 (up, ship_up);
1956 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1958 sgScaleVec3 (up, 4.0*ref_elev);
1959 dummy_tile->ols_transform->setTransform(up);
1960 //cout << "ref_elev " << ref_elev << endl;
1962 // end hack for deck lights
1965 if ( ship_sel != NULL ) {
1966 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1970 // $$$ end - added VS Renganathan, 15 Oct 2K
1971 // added Venky , 12 Nov 2K