1 // main.cxx -- top level sim routines
3 // Written by Curtis Olson for OpenGL, started May 1997.
5 // Copyright (C) 1997 - 1999 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>
34 #include <simgear/misc/exception.hxx>
36 #ifdef SG_MATH_EXCEPTION_CLASH
56 #ifdef HAVE_SYS_STAT_H
57 # include <sys/stat.h> // for stat()
61 # include <unistd.h> // for stat()
64 #include <plib/netChat.h>
68 #include <simgear/constants.h> // for VERSION
69 #include <simgear/debug/logstream.hxx>
70 #include <simgear/math/polar3d.hxx>
71 #include <simgear/math/sg_random.h>
72 #include <simgear/misc/sg_path.hxx>
73 #include <simgear/sky/sky.hxx>
74 #include <simgear/timing/sg_time.hxx>
76 #include <Include/general.hxx>
78 #include <Aircraft/aircraft.hxx>
80 #include <ATC/ATCmgr.hxx>
81 #include <ATC/ATCdisplay.hxx>
82 #include <Autopilot/newauto.hxx>
84 #include <Cockpit/cockpit.hxx>
85 #include <Cockpit/radiostack.hxx>
86 #include <Cockpit/steam.hxx>
88 #include <FDM/UIUCModel/uiuc_aircraftdir.h>
90 #include <GUI/sgVec3Slider.hxx>
91 // #include <Joystick/joystick.hxx>
93 #include <NetworkOLK/network.h>
95 #include <Objects/matlib.hxx>
96 #include <Scenery/scenery.hxx>
97 #include <Scenery/tilemgr.hxx>
98 #ifdef ENABLE_AUDIO_SUPPORT
99 # include <Sound/soundmgr.hxx>
100 # include <Sound/fg_fx.hxx>
101 # include <Sound/morse.hxx>
103 #include <Time/event.hxx>
104 #include <Time/fg_timer.hxx>
105 #include <Time/light.hxx>
106 #include <Time/sunpos.hxx>
107 #include <Time/tmp.hxx>
109 #include <Input/input.hxx>
112 #include <simgear/misc/sgstream.hxx>
113 #include <simgear/math/point3d.hxx>
114 #include <FDM/flight.hxx>
115 #include <FDM/ADA.hxx>
116 #include <Scenery/tileentry.hxx>
118 // Should already be inlcluded by gl.h if needed by your platform so
119 // we shouldn't include this here.
120 // #include <GL/glext.h>
122 // PFNGLPOINTPARAMETERFEXTPROC glPointParameterfEXT = 0;
123 // PFNGLPOINTPARAMETERFVEXTPROC glPointParameterfvEXT = 0;
125 float default_attenuation[3] = {1.0, 0.0, 0.0};
126 //Required for using GL_extensions
127 void fgLoadDCS (void);
128 void fgUpdateDCS (void);
129 ssgSelector *ship_sel=NULL;
130 // upto 32 instances of a same object can be loaded.
131 ssgTransform *ship_pos[32];
132 double obj_lat[32],obj_lon[32],obj_alt[32],obj_pitch[32],obj_roll[32];
134 ssgSelector *lightpoints_brightness = new ssgSelector;
135 ssgTransform *lightpoints_transform = new ssgTransform;
136 FGTileEntry *dummy_tile;
140 #ifndef FG_NEW_ENVIRONMENT
141 # include <WeatherCM/FGLocalWeatherDatabase.h>
143 # include <Environment/environment_mgr.hxx>
148 #include "fg_init.hxx"
150 #include "fg_props.hxx"
151 #include "globals.hxx"
152 #include "splash.hxx"
153 #include "viewmgr.hxx"
154 #include "options.hxx"
155 #include "logger.hxx"
159 # include <console.h> // -dw- for command line dialog
163 // This is a record containing a bit of global housekeeping information
166 // Specify our current idle function state. This is used to run all
167 // our initializations out of the glutIdleLoop() so that we can get a
168 // splash screen up and running right away.
169 static int idle_state = 0;
170 static long global_multi_loop;
172 // forward declaration
173 void fgReshape( int width, int height );
176 ssgRoot *scene = NULL;
177 ssgBranch *terrain_branch = NULL;
178 ssgBranch *gnd_lights_branch = NULL;
179 ssgBranch *rwy_lights_branch = NULL;
181 ssgRoot *lighting = NULL;
182 // ssgBranch *airport = NULL;
184 #ifdef FG_NETWORK_OLK
185 ssgSelector *fgd_sel = NULL;
186 ssgTransform *fgd_pos = NULL;
189 // current fdm/position used for view
190 FGInterface cur_view_fdm;
196 sgMat4 copy_of_ssgOpenGLAxisSwapMatrix =
198 { 1.0f, 0.0f, 0.0f, 0.0f },
199 { 0.0f, 0.0f, -1.0f, 0.0f },
200 { 0.0f, 1.0f, 0.0f, 0.0f },
201 { 0.0f, 0.0f, 0.0f, 1.0f }
204 // The following defines flightgear options. Because glutlib will also
205 // want to parse its own options, those options must not be included here
206 // or they will get parsed by the main program option parser. Hence case
207 // is significant for any option added that might be in conflict with
210 // glutlib parses for:
212 // -direct (invalid in Win32)
216 // -indirect (invalid in Win32)
219 // Note that glutlib depends upon strings while this program's
220 // option parser wants only initial characters followed by numbers
225 ssgSimpleState *default_state;
226 ssgSimpleState *hud_and_panel;
227 ssgSimpleState *menus;
229 SGTimeStamp start_time_stamp;
230 SGTimeStamp current_time_stamp;
232 void fgBuildRenderStates( void ) {
233 default_state = new ssgSimpleState;
234 default_state->ref();
235 default_state->disable( GL_TEXTURE_2D );
236 default_state->enable( GL_CULL_FACE );
237 default_state->enable( GL_COLOR_MATERIAL );
238 default_state->setColourMaterial( GL_AMBIENT_AND_DIFFUSE );
239 default_state->setMaterial( GL_EMISSION, 0, 0, 0, 1 );
240 default_state->setMaterial( GL_SPECULAR, 0, 0, 0, 1 );
241 default_state->disable( GL_BLEND );
242 default_state->disable( GL_ALPHA_TEST );
243 default_state->disable( GL_LIGHTING );
245 hud_and_panel = new ssgSimpleState;
246 hud_and_panel->ref();
247 hud_and_panel->disable( GL_CULL_FACE );
248 hud_and_panel->disable( GL_TEXTURE_2D );
249 hud_and_panel->disable( GL_LIGHTING );
250 hud_and_panel->enable( GL_BLEND );
252 menus = new ssgSimpleState;
254 menus->disable( GL_CULL_FACE );
255 menus->disable( GL_TEXTURE_2D );
256 menus->enable( GL_BLEND );
259 // fgFindNode -- a function that finds a named node in an ssg graph
260 ssgEntity *fgFindNode( ssgEntity *node, const char *name ) {
261 if ( node->getName() != NULL && strcmp( name, node->getName() ) == 0 ) {
263 } else if ( node->isAKindOf(ssgTypeBranch()) ) {
264 ssgEntity *kid = ((ssgBranch*)node)->getKid(0);
265 while ( kid != NULL ) {
266 ssgEntity *n = fgFindNode(kid, name);
270 kid = ((ssgBranch*)node)->getNextKid();
277 // fgInitVisuals() -- Initialize various GL/view parameters
278 void fgInitVisuals( void ) {
281 l = &cur_light_params;
283 #ifndef GLUT_WRONG_VERSION
284 // Go full screen if requested ...
285 if ( fgGetBool("/sim/startup/fullscreen") ) {
290 // If enabled, normal vectors specified with glNormal are scaled
291 // to unit length after transformation. See glNormal.
292 // glEnable( GL_NORMALIZE );
294 glEnable( GL_LIGHTING );
295 glEnable( GL_LIGHT0 );
296 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
299 sgSetVec3( sunpos, l->sun_vec[0], l->sun_vec[1], l->sun_vec[2] );
300 ssgGetLight( 0 ) -> setPosition( sunpos );
302 // glFogi (GL_FOG_MODE, GL_LINEAR);
303 glFogi (GL_FOG_MODE, GL_EXP2);
304 if ( (fgGetString("/sim/rendering/fog") == "disabled") ||
305 (!fgGetBool("/sim/rendering/shading"))) {
306 // if fastest fog requested, or if flat shading force fastest
307 glHint ( GL_FOG_HINT, GL_FASTEST );
308 } else if ( fgGetString("/sim/rendering/fog") == "nicest" ) {
309 glHint ( GL_FOG_HINT, GL_NICEST );
311 if ( fgGetBool("/sim/rendering/wireframe") ) {
313 glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
316 // This is the default anyways, but it can't hurt
317 glFrontFace ( GL_CCW );
320 // glEnable(GL_POINT_SMOOTH);
321 // glEnable(GL_LINE_SMOOTH);
322 // glEnable(GL_POLYGON_SMOOTH);
326 // For HiRes screen Dumps using Brian Pauls TR Library
327 void trRenderFrame( void ) {
329 if ( fgPanelVisible() ) {
330 GLfloat height = fgGetInt("/sim/startup/ysize");
332 (current_panel->getViewHeight() - current_panel->getYOffset())
333 * (height / 768.0) + 1;
334 glTranslatef( 0.0, view_h, 0.0 );
337 static double m_log01 = -log( 0.01 );
338 static double sqrt_m_log01 = sqrt( m_log01 );
340 static GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
341 static GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
343 fgLIGHT *l = &cur_light_params;
345 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
346 l->adj_fog_color[2], l->adj_fog_color[3]);
348 glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
350 // set the opengl state to known default values
351 default_state->force();
354 double actual_visibility = thesky->get_visibility();
355 // GLfloat fog_exp_density = m_log01 / actual_visibility;
356 GLfloat fog_exp2_density = sqrt_m_log01 / actual_visibility;
357 GLfloat fog_exp2_punch_through = sqrt_m_log01 / ( actual_visibility * 1.5 );
360 glFogf ( GL_FOG_DENSITY, fog_exp2_density);
361 glFogi ( GL_FOG_MODE, GL_EXP2 );
362 glFogfv ( GL_FOG_COLOR, l->adj_fog_color );
364 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
365 // we only update GL_AMBIENT for our lights we will never get
366 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
367 // explicitely to black.
368 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
370 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
372 // texture parameters
373 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
374 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
376 // we need a white diffuse light for the phase of the moon
377 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
380 // draw the ssg scene
381 // return to the desired diffuse color
382 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
383 glEnable( GL_DEPTH_TEST );
384 ssgCullAndDraw( scene );
387 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
388 ssgCullAndDraw( lighting );
390 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
392 // need to do this here as hud_and_panel state is static to
393 // main.cxx and HUD and Panel routines have to be called with
394 // knowledge of the the TR struct < see gui.cxx::HighResDump()
395 hud_and_panel->apply();
399 // Update all Visuals (redraws anything graphics related)
400 void fgRenderFrame( void ) {
401 static const SGPropertyNode *longitude
402 = fgGetNode("/position/longitude-deg");
403 static const SGPropertyNode *latitude
404 = fgGetNode("/position/latitude-deg");
405 static const SGPropertyNode *altitude
406 = fgGetNode("/position/altitude-ft");
408 // Update the default (kludged) properties.
411 fgLIGHT *l = &cur_light_params;
412 static double last_visibility = -9999;
414 static GLfloat fog_exp_density;
415 static GLfloat fog_exp2_density;
416 static GLfloat fog_exp2_punch_through;
419 // GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
420 // GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
421 // GLfloat terrain_color[4] = { 0.54, 0.44, 0.29, 1.0 };
422 // GLfloat mat_shininess[] = { 10.0 };
423 GLbitfield clear_mask;
425 if ( idle_state != 1000 ) {
426 // still initializing, draw the splash screen
427 if ( fgGetBool("/sim/startup/splash-screen") ) {
430 start_time_stamp.stamp(); // Keep resetting the start time
432 // idle_state is now 1000 meaning we've finished all our
433 // initializations and are running the main loop, so this will
434 // now work without seg faulting the system.
436 // Update the elapsed time.
437 current_time_stamp.stamp();
438 globals->set_elapsed_time_ms((current_time_stamp - start_time_stamp)
441 // calculate our current position in cartesian space
442 scenery.set_center( scenery.get_next_center() );
444 FGViewerRPH *pilot_view =
445 (FGViewerRPH *)globals->get_viewmgr()->get_view( 0 );
447 pilot_view->set_geod_view_pos( longitude->getDoubleValue()
448 * SGD_DEGREES_TO_RADIANS,
449 latitude->getDoubleValue()
450 * SGD_DEGREES_TO_RADIANS,
451 altitude->getDoubleValue()
452 * SG_FEET_TO_METER );
453 pilot_view->set_rph( cur_fdm_state->get_Phi(),
454 cur_fdm_state->get_Theta(),
455 cur_fdm_state->get_Psi() );
457 if (fgGetString("/sim/flight-model") == "ada") {
458 //+ve x is aft, +ve z is up (see viewer.hxx)
459 pilot_view->set_pilot_offset( -5.0, 0.0, 1.0 );
462 FGViewerLookAt *chase_view =
463 (FGViewerLookAt *)globals->get_viewmgr()->get_view( 1 );
465 sgVec3 po; // chase view pilot_offset
466 sgVec3 wup; // chase view world up
467 sgSetVec3( po, 0.0, 0.0, 100.0 );
468 sgCopyVec3( wup, pilot_view->get_world_up() );
469 sgMat4 CXFM; // chase view + pilot offset xform
471 chase_view->get_view_offset() * SGD_RADIANS_TO_DEGREES -
472 cur_fdm_state->get_Psi() * SGD_RADIANS_TO_DEGREES,
474 sgVec3 npo; // new pilot offset after rotation
475 sgVec3 *pPO = PilotOffsetGet();
476 sgXformVec3( po, *pPO, pilot_view->get_UP() );
477 sgXformVec3( npo, po, CXFM );
479 chase_view->set_geod_view_pos( longitude->getDoubleValue()
480 * SGD_DEGREES_TO_RADIANS,
481 latitude->getDoubleValue()
482 * SGD_DEGREES_TO_RADIANS,
483 altitude->getDoubleValue()
484 * SG_FEET_TO_METER );
485 chase_view->set_pilot_offset( npo[0], npo[1], npo[2] );
486 chase_view->set_view_forward( pilot_view->get_view_pos() );
487 chase_view->set_view_up( wup );
490 fgReshape( fgGetInt("/sim/startup/xsize"),
491 fgGetInt("/sim/startup/ysize") );
493 // set the sun position
494 glLightfv( GL_LIGHT0, GL_POSITION, l->sun_vec );
496 clear_mask = GL_DEPTH_BUFFER_BIT;
497 if ( fgGetBool("/sim/rendering/wireframe") ) {
498 clear_mask |= GL_COLOR_BUFFER_BIT;
501 if ( fgGetBool("/sim/rendering/skyblend") ) {
502 if ( fgGetBool("/sim/rendering/textures") ) {
503 // glClearColor(black[0], black[1], black[2], black[3]);
504 glClearColor(l->adj_fog_color[0], l->adj_fog_color[1],
505 l->adj_fog_color[2], l->adj_fog_color[3]);
506 clear_mask |= GL_COLOR_BUFFER_BIT;
509 glClearColor(l->sky_color[0], l->sky_color[1],
510 l->sky_color[2], l->sky_color[3]);
511 clear_mask |= GL_COLOR_BUFFER_BIT;
513 glClear( clear_mask );
515 // Tell GL we are switching to model view parameters
517 // I really should create a derived ssg node or use a call
518 // back or something so that I can draw the sky within the
519 // ssgCullAndDraw() function, but for now I just mimic what
520 // ssg does to set up the model view matrix
521 glMatrixMode(GL_MODELVIEW);
523 ssgSetCamera( (sgVec4 *)globals->get_current_view()->get_VIEW() );
525 // set the opengl state to known default values
526 default_state->force();
528 // update fog params if visibility has changed
529 thesky->set_visibility(fgGetDouble("/environment/visibility-m"));
531 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
532 ( global_multi_loop * fgGetInt("/sim/speed-up") )
533 / (double)fgGetInt("/sim/model-hz") );
535 double actual_visibility = thesky->get_visibility();
536 // cout << "actual visibility = " << actual_visibility << endl;
538 if ( actual_visibility != last_visibility ) {
539 last_visibility = actual_visibility;
541 // cout << "----> updating fog params" << endl;
544 fog_exp_density = -log(0.01) / actual_visibility;
547 fog_exp2_density = sqrt( -log(0.01) ) / actual_visibility;
548 fog_exp2_punch_through = sqrt( -log(0.01) ) /
549 ( actual_visibility * 1.5 );
552 // Set correct opengl fog density
553 glFogf (GL_FOG_DENSITY, fog_exp2_density);
555 // update the sky dome
556 if ( fgGetBool("/sim/rendering/skyblend") ) {
557 /* cout << "thesky->repaint() sky_color = "
558 << cur_light_params.sky_color[0] << " "
559 << cur_light_params.sky_color[1] << " "
560 << cur_light_params.sky_color[2] << " "
561 << cur_light_params.sky_color[3] << endl;
563 << cur_light_params.fog_color[0] << " "
564 << cur_light_params.fog_color[1] << " "
565 << cur_light_params.fog_color[2] << " "
566 << cur_light_params.fog_color[3] << endl;
567 cout << " sun_angle = " << cur_light_params.sun_angle
568 << " moon_angle = " << cur_light_params.moon_angle
570 thesky->repaint( cur_light_params.sky_color,
571 cur_light_params.adj_fog_color,
572 cur_light_params.sun_angle,
573 cur_light_params.moon_angle,
574 globals->get_ephem()->getNumPlanets(),
575 globals->get_ephem()->getPlanets(),
576 globals->get_ephem()->getNumStars(),
577 globals->get_ephem()->getStars() );
579 /* cout << "thesky->reposition( view_pos = " << view_pos[0] << " "
580 << view_pos[1] << " " << view_pos[2] << endl;
581 cout << " zero_elev = " << zero_elev[0] << " "
582 << zero_elev[1] << " " << zero_elev[2]
583 << " lon = " << cur_fdm_state->get_Longitude()
584 << " lat = " << cur_fdm_state->get_Latitude() << endl;
585 cout << " sun_rot = " << cur_light_params.sun_rotation
586 << " gst = " << SGTime::cur_time_params->getGst() << endl;
587 cout << " sun ra = " << globals->get_ephem()->getSunRightAscension()
588 << " sun dec = " << globals->get_ephem()->getSunDeclination()
589 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
590 << " moon dec = " << globals->get_ephem()->getMoonDeclination() << endl; */
592 thesky->reposition( globals->get_current_view()->get_view_pos(),
593 globals->get_current_view()->get_zero_elev(),
594 globals->get_current_view()->get_world_up(),
595 longitude->getDoubleValue()
596 * SGD_DEGREES_TO_RADIANS,
597 latitude->getDoubleValue()
598 * SGD_DEGREES_TO_RADIANS,
599 altitude->getDoubleValue() * SG_FEET_TO_METER,
600 cur_light_params.sun_rotation,
601 globals->get_time_params()->getGst(),
602 globals->get_ephem()->getSunRightAscension(),
603 globals->get_ephem()->getSunDeclination(),
605 globals->get_ephem()->getMoonRightAscension(),
606 globals->get_ephem()->getMoonDeclination(),
610 glEnable( GL_DEPTH_TEST );
611 if ( fgGetString("/sim/rendering/fog") != (string)"disabled" ) {
613 glFogi( GL_FOG_MODE, GL_EXP2 );
614 glFogfv( GL_FOG_COLOR, l->adj_fog_color );
617 // set sun/lighting parameters
618 ssgGetLight( 0 ) -> setPosition( l->sun_vec );
620 // GL_LIGHT_MODEL_AMBIENT has a default non-zero value so if
621 // we only update GL_AMBIENT for our lights we will never get
622 // a completely dark scene. So, we set GL_LIGHT_MODEL_AMBIENT
623 // explicitely to black.
624 GLfloat black[4] = { 0.0, 0.0, 0.0, 1.0 };
625 GLfloat white[4] = { 1.0, 1.0, 1.0, 1.0 };
626 glLightModelfv( GL_LIGHT_MODEL_AMBIENT, black );
628 ssgGetLight( 0 ) -> setColour( GL_AMBIENT, l->scene_ambient );
629 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
630 // ssgGetLight( 0 ) -> setColour( GL_SPECULAR, l->scene_white );
632 // texture parameters
633 // glEnable( GL_TEXTURE_2D );
634 glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ) ;
635 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ) ;
637 // glMatrixMode( GL_PROJECTION );
639 ssgSetFOV( globals->get_current_view()->get_h_fov(),
640 globals->get_current_view()->get_v_fov() );
642 double agl = current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER
643 - scenery.get_cur_elev();
645 if (fgGetBool("/cockpit"))
646 ssgSetNearFar( 0.2f, 120000.0f );
647 else if ( agl > 10.0)
648 ssgSetNearFar( 10.0f, 120000.0f );
650 ssgSetNearFar( 0.5f, 120000.0f );
652 current_model.update(0); // FIXME: use real delta time
654 // $$$ begin - added VS Renganthan 17 Oct 2K
656 // $$$ end - added VS Renganthan 17 Oct 2K
658 # ifdef FG_NETWORK_OLK
659 if ( fgGetBool("/sim/networking/network-olk") ) {
661 other = head->next; /* put listpointer to start */
662 while ( other != tail) { /* display all except myself */
663 if ( strcmp( other->ipadr, fgd_mcp_ip) != 0) {
664 other->fgd_sel->select(1);
665 sgSetCoord( &fgdpos, other->sgFGD_COORD );
666 other->fgd_pos->setTransform( &fgdpos );
671 // fgd_sel->select(1);
672 // sgCopyMat4( sgTUX, current_view.sgVIEW);
674 // sgSetCoord( &fgdpos, sgFGD_VIEW );
675 // fgd_pos->setTransform( &fgdpos);
679 // position tile nodes and update range selectors
680 global_tile_mgr.prep_ssg_nodes();
682 if ( fgGetBool("/sim/rendering/skyblend") ) {
683 // draw the sky backdrop
685 // we need a white diffuse light for the phase of the moon
686 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, white );
690 // return to the desired diffuse color
691 ssgGetLight( 0 ) -> setColour( GL_DIFFUSE, l->scene_diffuse );
694 // draw the ssg scene
695 glEnable( GL_DEPTH_TEST );
696 ssgCullAndDraw( scene );
698 // change state for lighting here
701 // Set punch through fog density
702 glFogf (GL_FOG_DENSITY, fog_exp2_punch_through);
704 #ifdef FG_EXPERIMENTAL_LIGHTING
705 // Enable states for drawing points with GL_extension
706 if (glutExtensionSupported("GL_EXT_point_parameters")) {
707 glEnable(GL_POINT_SMOOTH);
708 float quadratic[3] = {1.0, 0.01, 0.0001};
709 // get the address of our OpenGL extensions
711 glPointParameterfEXT = (PFNGLPOINTPARAMETERFEXTPROC)
712 wglGetProcAddress("glPointParameterfEXT");
713 glPointParameterfvEXT = (PFNGLPOINTPARAMETERFVEXTPROC)
714 wglGetProcAddress("glPointParameterfvEXT");
716 // makes the points fade as they move away
717 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT, quadratic);
718 glPointParameterfEXT(GL_POINT_SIZE_MIN_EXT, 1.0);
721 // Enable states for drawing runway lights with spherical mapping
722 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
723 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
724 glEnable(GL_TEXTURE_GEN_S);
725 glEnable(GL_TEXTURE_GEN_T);
727 //Maybe this is not the best way, but it works !!
728 glPolygonMode(GL_FRONT, GL_POINT);
730 glEnable(GL_CULL_FACE);
733 glDisable( GL_LIGHTING );
734 // blending function for runway lights
735 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ;
739 ssgCullAndDraw( lighting );
741 #ifdef FG_EXPERIMENTAL_LIGHTING
742 if (glutExtensionSupported("GL_EXT_point_parameters")) {
743 // Disable states used for runway lighting
744 glPolygonMode(GL_FRONT, GL_FILL);
746 glDisable(GL_TEXTURE_GEN_S);
747 glDisable(GL_TEXTURE_GEN_T);
748 glPointParameterfvEXT(GL_DISTANCE_ATTENUATION_EXT,
749 default_attenuation);
755 if ( fgGetBool("/sim/rendering/skyblend") ) {
756 // draw the sky cloud layers
757 thesky->postDraw( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER );
760 // display HUD && Panel
762 glDisable( GL_DEPTH_TEST );
763 // glDisable( GL_CULL_FACE );
764 // glDisable( GL_TEXTURE_2D );
766 // update the input subsystem
767 current_input.update(1); // FIXME: use real dt
769 // update the controls subsystem
770 globals->get_controls()->update(1); // FIXME: use real dt
772 hud_and_panel->apply();
775 // Use the hud_and_panel ssgSimpleState for rendering the ATC output
776 // This only works properly if called before the panel call
777 globals->get_ATC_display()->update(1); // FIXME: use real dt
779 // update the panel subsystem
780 if ( current_panel != NULL ) {
781 current_panel->update(1); // FIXME: use real dt
784 // We can do translucent menus, so why not. :-)
786 glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ) ;
788 // glDisable ( GL_BLEND ) ;
790 // glEnable( GL_FOG );
792 globals->get_logger()->update(0); // FIXME: use real dt
799 // Update internal time dependent calculations (i.e. flight model)
800 void fgUpdateTimeDepCalcs() {
801 static bool inited = false;
802 static const SGPropertyNode *master_freeze
803 = fgGetNode("/sim/freeze/master");
805 //SG_LOG(SG_FLIGHT,SG_INFO, "Updating time dep calcs()");
807 fgLIGHT *l = &cur_light_params;
812 // Initialize the FDM here if it hasn't been and if we have a
813 // scenery elevation hit.
815 // cout << "cur_fdm_state->get_inited() = " << cur_fdm_state->get_inited()
816 // << " cur_elev = " << scenery.get_cur_elev() << endl;
818 if ( !cur_fdm_state->get_inited() && scenery.get_cur_elev() > -9990 ) {
819 SG_LOG(SG_FLIGHT,SG_INFO, "Finally initializing fdm");
821 cur_fdm_state->init();
822 if ( cur_fdm_state->get_bound() ) {
823 cur_fdm_state->unbind();
825 cur_fdm_state->bind();
828 // conceptually, the following block could be done for each fdm
830 if ( !cur_fdm_state->get_inited() ) {
831 // do nothing, fdm isn't inited yet
832 } else if ( master_freeze->getBoolValue() ) {
833 // we are frozen, run the fdm's with 0 time slices in case
834 // they want to do something with that.
836 cur_fdm_state->update( 0 );
837 FGSteam::update( 0 );
839 // we have been inited, and we are not frozen, we are good to go ...
842 cur_fdm_state->stamp();
848 long elapsed = current - cur_fdm_state->get_time_stamp();
849 cur_fdm_state->set_time_stamp( current );
850 elapsed += cur_fdm_state->get_remainder();
851 // cout << "elapsed = " << elapsed << endl;
852 // cout << "dt = " << cur_fdm_state->get_delta_t() << endl;
853 multi_loop = (long)(((double)elapsed * 0.000001) /
854 cur_fdm_state->get_delta_t() );
855 cur_fdm_state->set_multi_loop( multi_loop );
856 long remainder = elapsed - (long)( (multi_loop*1000000) *
857 cur_fdm_state->get_delta_t() );
858 cur_fdm_state->set_remainder( remainder );
859 // cout << "remainder = " << remainder << endl;
861 // chop max interations to something reasonable if the sim was
862 // delayed for an excesive amount of time
863 if ( multi_loop > 2.0 / cur_fdm_state->get_delta_t() ) {
864 multi_loop = (int)(2.0 / cur_fdm_state->get_delta_t());
865 cur_fdm_state->set_remainder( 0 );
868 // cout << "multi_loop = " << multi_loop << endl;
869 for ( i = 0; i < multi_loop * fgGetInt("/sim/speed-up"); ++i ) {
870 // run Autopilot system
871 current_autopilot->run();
874 cur_fdm_state->update( 1 );
876 FGSteam::update( multi_loop * fgGetInt("/sim/speed-up") );
879 if ( fgGetString("/sim/view-mode") == "pilot" ) {
880 cur_view_fdm = *cur_fdm_state;
884 // update the view angle
885 globals->get_current_view()->update(multi_loop);
889 // Update solar system
890 globals->get_ephem()->update( globals->get_time_params()->getMjd(),
891 globals->get_time_params()->getLst(),
892 cur_fdm_state->get_Latitude() );
894 // Update radio stack model
895 current_radiostack->update(multi_loop);
899 void fgInitTimeDepCalcs( void ) {
902 // #ifdef HAVE_SETITIMER
903 // fgTimerInit( 1.0 / fgGetInt("/sim/model-hz"),
904 // fgUpdateTimeDepCalcs );
905 // #endif HAVE_SETITIMER
909 static const double alt_adjust_ft = 3.758099;
910 static const double alt_adjust_m = alt_adjust_ft * SG_FEET_TO_METER;
913 // What should we do when we have nothing else to do? Let's get ready
914 // for the next move and update the display?
915 static void fgMainLoop( void ) {
916 static const SGPropertyNode *longitude
917 = fgGetNode("/position/longitude-deg");
918 static const SGPropertyNode *latitude
919 = fgGetNode("/position/latitude-deg");
920 static const SGPropertyNode *altitude
921 = fgGetNode("/position/altitude-ft");
922 static const SGPropertyNode *clock_freeze
923 = fgGetNode("/sim/freeze/clock", true);
924 static const SGPropertyNode *cur_time_override
925 = fgGetNode("/sim/time/cur-time-override", true);
927 static long remainder = 0;
929 #ifdef FANCY_FRAME_COUNTER
933 static time_t last_time = 0;
934 static int frames = 0;
935 #endif // FANCY_FRAME_COUNTER
937 SGTime *t = globals->get_time_params();
939 SG_LOG( SG_ALL, SG_DEBUG, "Running Main Loop");
940 SG_LOG( SG_ALL, SG_DEBUG, "======= ==== ====");
942 #ifdef FG_NETWORK_OLK
943 if ( fgGetBool("/sim/networking/network-olk") ) {
944 if ( net_is_registered == 0 ) { // We first have to reg. to fgd
945 // printf("FGD: Netupdate\n");
946 fgd_send_com( "A", FGFS_host); // Send Mat4 data
947 fgd_send_com( "B", FGFS_host); // Recv Mat4 data
952 #if defined( ENABLE_PLIB_JOYSTICK )
953 // Read joystick and update control settings
954 // if ( fgGetString("/sim/control-mode") == "joystick" )
958 #elif defined( ENABLE_GLUT_JOYSTICK )
959 // Glut joystick support works by feeding a joystick handler
960 // function to glut. This is taken care of once in the joystick
961 // init routine and we don't have to worry about it again.
964 #ifdef FG_NEW_ENVIRONMENT
965 globals->get_environment_mgr()->update(0); // FIXME: use real delta time
968 // Fix elevation. I'm just sticking this here for now, it should
969 // probably move eventually
971 /* printf("Before - ground = %.2f runway = %.2f alt = %.2f\n",
972 scenery.get_cur_elev(),
973 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
974 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
976 if ( scenery.get_cur_elev() > -9990 && cur_fdm_state->get_inited() ) {
977 if ( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER <
978 (scenery.get_cur_elev() + alt_adjust_m - 3.0) ) {
979 // now set aircraft altitude above ground
980 printf("(*) Current Altitude = %.2f < %.2f forcing to %.2f\n",
981 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
982 scenery.get_cur_elev() + alt_adjust_m - 3.0,
983 scenery.get_cur_elev() + alt_adjust_m );
984 cur_fdm_state->set_Altitude( scenery.get_cur_elev()
987 SG_LOG( SG_ALL, SG_DEBUG,
988 "<*> resetting altitude to "
989 << cur_fdm_state->get_Altitude() * SG_FEET_TO_METER
994 /* printf("Adjustment - ground = %.2f runway = %.2f alt = %.2f\n",
995 scenery.get_cur_elev(),
996 cur_fdm_state->get_Runway_altitude() * SG_FEET_TO_METER,
997 cur_fdm_state->get_Altitude() * SG_FEET_TO_METER); */
999 // cout << "Warp = " << globals->get_warp() << endl;
1002 static bool last_clock_freeze = false;
1004 if ( clock_freeze->getBoolValue() ) {
1005 // clock freeze requested
1006 if ( cur_time_override->getLongValue() == 0 ) {
1007 fgSetLong( "/sim/time/cur-time-override", t->get_cur_time() );
1008 globals->set_warp( 0 );
1011 // no clock freeze requested
1012 if ( last_clock_freeze == true ) {
1013 // clock just unfroze, let's set warp as the difference
1014 // between frozen time and current time so we don't get a
1015 // time jump (and corresponding sky object and lighting
1017 globals->set_warp( cur_time_override->getLongValue() - time(NULL) );
1018 fgSetLong( "/sim/time/cur-time-override", 0 );
1020 if ( globals->get_warp_delta() != 0 ) {
1021 globals->inc_warp( globals->get_warp_delta() );
1025 last_clock_freeze = clock_freeze->getBoolValue();
1027 t->update( longitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1028 latitude->getDoubleValue() * SGD_DEGREES_TO_RADIANS,
1029 cur_time_override->getLongValue(),
1030 globals->get_warp() );
1032 if ( globals->get_warp_delta() != 0 ) {
1033 fgUpdateSkyAndLightingParams();
1036 // update magvar model
1037 globals->get_mag()->update( longitude->getDoubleValue()
1038 * SGD_DEGREES_TO_RADIANS,
1039 latitude->getDoubleValue()
1040 * SGD_DEGREES_TO_RADIANS,
1041 altitude->getDoubleValue() * SG_FEET_TO_METER,
1042 globals->get_time_params()->getJD() );
1044 // Get elapsed time (in usec) for this past frame
1045 elapsed = fgGetTimeInterval();
1046 SG_LOG( SG_ALL, SG_DEBUG,
1047 "Elapsed time interval is = " << elapsed
1048 << ", previous remainder is = " << remainder );
1050 // Calculate frame rate average
1051 #ifdef FANCY_FRAME_COUNTER
1052 /* old fps calculation */
1053 if ( elapsed > 0 ) {
1056 for ( i = FG_FRAME_RATE_HISTORY - 2; i >= 0; i-- ) {
1057 tmp = general.get_frame(i);
1059 // printf("frame[%d] = %.2f\n", i, g->frames[i]);
1060 general.set_frame(i+1,tmp);
1062 tmp = 1000000.0 / (float)elapsed;
1063 general.set_frame(0,tmp);
1064 // printf("frame[0] = %.2f\n", general.frames[0]);
1066 general.set_frame_rate(accum / (float)FG_FRAME_RATE_HISTORY);
1067 // printf("ave = %.2f\n", general.frame_rate);
1070 if ( (t->get_cur_time() != last_time) && (last_time > 0) ) {
1071 general.set_frame_rate( frames );
1072 SG_LOG( SG_ALL, SG_DEBUG,
1073 "--> Frame rate is = " << general.get_frame_rate() );
1076 last_time = t->get_cur_time();
1080 // Run ATC subsystem
1081 globals->get_ATC_mgr()->update(1); // FIXME: use real dt
1085 // Calculate model iterations needed for next frame
1086 elapsed += remainder;
1088 global_multi_loop = (long)(((double)elapsed * 0.000001) *
1089 fgGetInt("/sim/model-hz"));
1090 remainder = elapsed - ( (global_multi_loop*1000000) /
1091 fgGetInt("/sim/model-hz") );
1092 SG_LOG( SG_ALL, SG_DEBUG,
1093 "Model iterations needed = " << global_multi_loop
1094 << ", new remainder = " << remainder );
1096 // chop max interations to something reasonable if the sim was
1097 // delayed for an excesive amount of time
1098 if ( global_multi_loop > 2.0 * fgGetInt("/sim/model-hz") ) {
1099 global_multi_loop = (int)(2.0 * fgGetInt("/sim/model-hz") );
1104 if ( global_multi_loop > 0 ) {
1105 fgUpdateTimeDepCalcs();
1107 SG_LOG( SG_ALL, SG_DEBUG,
1108 "Elapsed time is zero ... we're zinging" );
1111 #if ! defined( macintosh )
1112 // Do any I/O channel work that might need to be done
1116 // see if we need to load any new scenery tiles
1117 global_tile_mgr.update( longitude->getDoubleValue(),
1118 latitude->getDoubleValue() );
1120 // see if we need to load any deferred-load textures
1121 material_lib.load_next_deferred();
1123 // Process/manage pending events
1124 global_events.Process();
1126 // Run audio scheduler
1127 #ifdef ENABLE_AUDIO_SUPPORT
1128 if ( fgGetBool("/sim/sound/audible")
1129 && globals->get_soundmgr()->is_working() ) {
1130 globals->get_fx()->update(1); // FIXME: use dt
1131 globals->get_soundmgr()->update(1); // FIXME: use dt
1138 SG_LOG( SG_ALL, SG_DEBUG, "" );
1142 // This is the top level master main function that is registered as
1143 // our idle funciton
1146 // The first few passes take care of initialization things (a couple
1147 // per pass) and once everything has been initialized fgMainLoop from
1150 static void fgIdleFunction ( void ) {
1151 // printf("idle state == %d\n", idle_state);
1153 if ( idle_state == 0 ) {
1154 // Initialize the splash screen right away
1155 if ( fgGetBool("/sim/startup/splash-screen") ) {
1160 } else if ( idle_state == 1 ) {
1161 // Initialize audio support
1162 #ifdef ENABLE_AUDIO_SUPPORT
1164 // Start the intro music
1165 if ( fgGetBool("/sim/startup/intro-music") ) {
1166 SGPath mp3file( globals->get_fg_root() );
1167 mp3file.append( "Sounds/intro.mp3" );
1169 SG_LOG( SG_GENERAL, SG_INFO,
1170 "Starting intro music: " << mp3file.str() );
1172 #if defined( __CYGWIN__ )
1173 string command = "start /m `cygpath -w " + mp3file.str() + "`";
1174 #elif defined( WIN32 )
1175 string command = "start /m " + mp3file.str();
1177 string command = "mpg123 " + mp3file.str() + "> /dev/null 2>&1";
1180 system ( command.c_str() );
1186 } else if ( idle_state == 2 ) {
1187 // These are a few miscellaneous things that aren't really
1188 // "subsystems" but still need to be initialized.
1191 if ( strstr ( general.get_glRenderer(), "Glide" ) ) {
1192 grTexLodBiasValue ( GR_TMU0, 1.0 ) ;
1197 } else if ( idle_state == 3 ) {
1198 // This is the top level init routine which calls all the
1199 // other subsystem initialization routines. If you are adding
1200 // a subsystem to flightgear, its initialization call should
1201 // located in this routine.
1202 if( !fgInitSubsystems()) {
1203 SG_LOG( SG_GENERAL, SG_ALERT,
1204 "Subsystem initializations failed ..." );
1209 } else if ( idle_state == 4 ) {
1210 // setup OpenGL view parameters
1214 } else if ( idle_state == 5 ) {
1217 } else if ( idle_state == 6 ) {
1221 cout << "Panel visible = " << fgPanelVisible() << endl;
1222 fgReshape( fgGetInt("/sim/startup/xsize"),
1223 fgGetInt("/sim/startup/ysize") );
1226 if ( idle_state == 1000 ) {
1227 // We've finished all our initialization steps, from now on we
1228 // run the main loop.
1232 if ( fgGetBool("/sim/startup/splash-screen") ) {
1233 fgSplashUpdate(0.0);
1238 // options.cxx needs to see this for toggle_panel()
1239 // Handle new window size or exposure
1240 void fgReshape( int width, int height ) {
1243 if ( (!fgGetBool("/sim/virtual-cockpit"))
1244 && fgPanelVisible() && idle_state == 1000 ) {
1245 view_h = (int)(height * (current_panel->getViewHeight() -
1246 current_panel->getYOffset()) / 768.0);
1252 for ( int i = 0; i < globals->get_viewmgr()->size(); ++i ) {
1253 globals->get_viewmgr()->get_view(i)->
1254 set_aspect_ratio((float)view_h / (float)width);
1257 glViewport( 0, (GLint)(height - view_h), (GLint)(width), (GLint)(view_h) );
1259 fgSetInt("/sim/startup/xsize", width);
1260 fgSetInt("/sim/startup/ysize", height);
1261 guiInitMouse(width, height);
1263 ssgSetFOV( globals->get_current_view()->get_h_fov(),
1264 globals->get_current_view()->get_v_fov() );
1270 // Initialize GLUT and define a main window
1271 int fgGlutInit( int *argc, char **argv ) {
1273 #if !defined( macintosh )
1274 // GLUT will extract all glut specific options so later on we only
1275 // need wory about our own.
1276 glutInit(argc, argv);
1279 // Define Display Parameters
1280 glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE );
1282 SG_LOG( SG_GENERAL, SG_INFO, "Opening a window: " <<
1283 fgGetInt("/sim/startup/xsize") << "x"
1284 << fgGetInt("/sim/startup/ysize") );
1286 // Define initial window size
1287 glutInitWindowSize( fgGetInt("/sim/startup/xsize"),
1288 fgGetInt("/sim/startup/ysize") );
1290 // Initialize windows
1291 if ( !fgGetBool("/sim/startup/game-mode")) {
1292 // Open the regular window
1293 glutCreateWindow("FlightGear");
1294 #ifndef GLUT_WRONG_VERSION
1296 // Open the cool new 'game mode' window
1297 char game_mode_str[256];
1298 sprintf( game_mode_str, "width=%d height=%d bpp=%d",
1299 fgGetInt("/sim/startup/xsize"),
1300 fgGetInt("/sim/startup/ysize"),
1301 fgGetInt("/sim/rendering/bits-per-pixel"));
1303 SG_LOG( SG_GENERAL, SG_INFO,
1304 "game mode params = " << game_mode_str );
1305 glutGameModeString( game_mode_str );
1306 glutEnterGameMode();
1310 // This seems to be the absolute earliest in the init sequence
1311 // that these calls will return valid info. Too bad it's after
1312 // we've already created and sized out window. :-(
1313 general.set_glVendor( (char *)glGetString ( GL_VENDOR ) );
1314 general.set_glRenderer( (char *)glGetString ( GL_RENDERER ) );
1315 general.set_glVersion( (char *)glGetString ( GL_VERSION ) );
1316 SG_LOG( SG_GENERAL, SG_INFO, general.get_glRenderer() );
1319 glGetIntegerv( GL_MAX_TEXTURE_SIZE, &tmp );
1320 general.set_glMaxTexSize( tmp );
1321 SG_LOG ( SG_GENERAL, SG_INFO, "Max texture size = " << tmp );
1323 glGetIntegerv( GL_DEPTH_BITS, &tmp );
1324 general.set_glDepthBits( tmp );
1325 SG_LOG ( SG_GENERAL, SG_INFO, "Depth buffer bits = " << tmp );
1331 // Initialize GLUT event handlers
1332 int fgGlutInitEvents( void ) {
1333 // call fgReshape() on window resizes
1334 glutReshapeFunc( fgReshape );
1336 // call GLUTkey() on keyboard event
1337 glutKeyboardFunc(GLUTkey);
1338 glutKeyboardUpFunc(GLUTkeyup);
1339 glutSpecialFunc(GLUTspecialkey);
1340 glutSpecialUpFunc(GLUTspecialkeyup);
1342 // call guiMouseFunc() whenever our little rodent is used
1343 glutMouseFunc ( guiMouseFunc );
1344 glutMotionFunc (guiMotionFunc );
1345 glutPassiveMotionFunc (guiMotionFunc );
1347 // call fgMainLoop() whenever there is
1348 // nothing else to do
1349 glutIdleFunc( fgIdleFunction );
1352 glutDisplayFunc( fgRenderFrame );
1359 int mainLoop( int argc, char **argv ) {
1361 #if defined( macintosh )
1362 freopen ("stdout.txt", "w", stdout );
1363 freopen ("stderr.txt", "w", stderr );
1364 argc = ccommand( &argv );
1367 // set default log levels
1368 sglog().setLogLevels( SG_ALL, SG_INFO );
1371 #ifdef FLIGHTGEAR_VERSION
1372 version = FLIGHTGEAR_VERSION;
1374 version = "unknown version";
1376 SG_LOG( SG_GENERAL, SG_INFO, "FlightGear: Version "
1377 << version << endl );
1379 // Allocate global data structures. This needs to happen before
1380 // we parse command line options
1382 globals = new FGGlobals;
1384 #if defined(FG_NEW_ENVIRONMENT)
1385 globals->set_environment_mgr(new FGEnvironmentMgr);
1388 // seed the random number generater
1391 SGRoute *route = new SGRoute;
1392 globals->set_route( route );
1394 FGControls *controls = new FGControls;
1395 globals->set_controls( controls );
1397 FGViewMgr *viewmgr = new FGViewMgr;
1398 globals->set_viewmgr( viewmgr );
1400 FGViewerRPH *pv = new FGViewerRPH;
1401 globals->get_viewmgr()->add_view( pv );
1403 FGViewerLookAt *chase = new FGViewerLookAt;
1404 globals->get_viewmgr()->add_view( chase );
1406 string_list *col = new string_list;
1407 globals->set_channel_options_list( col );
1409 // set current view to 0 (first) which is our main pilot view
1410 globals->set_current_view( globals->get_viewmgr()->get_view( 0 ) );
1412 // Scan the config file(s) and command line options to see if
1413 // fg_root was specified (ignore all other options for now)
1414 fgInitFGRoot(argc, argv);
1416 // Check for the correct base package version
1417 string base_version = fgBasePackageVersion();
1418 if ( !(base_version == "0.7.9") ) {
1419 // tell the operator how to use this application
1422 SG_LOG( SG_GENERAL, SG_ALERT, "Base package check failed ... "
1423 << "Found version " << base_version );
1424 SG_LOG( SG_GENERAL, SG_ALERT, "Please upgrade to version 0.7.9" );
1428 // Initialize the Aircraft directory to "" (UIUC)
1431 // Load the configuration parameters
1432 if ( !fgInitConfig(argc, argv) ) {
1433 SG_LOG( SG_GENERAL, SG_ALERT, "Config option parsing failed ..." );
1437 // Initialize the Window/Graphics environment.
1438 if( !fgGlutInit(&argc, argv) ) {
1439 SG_LOG( SG_GENERAL, SG_ALERT, "GLUT initialization failed ..." );
1443 // Initialize the various GLUT Event Handlers.
1444 if( !fgGlutInitEvents() ) {
1445 SG_LOG( SG_GENERAL, SG_ALERT,
1446 "GLUT event handler initialization failed ..." );
1450 // Initialize plib net interface
1451 netInit( &argc, argv );
1453 // Initialize ssg (from plib). Needs to come before we do any
1454 // other ssg stuff, but after opengl/glut has been initialized.
1457 // Initialize the user interface (we need to do this before
1458 // passing off control to glut and before fgInitGeneral to get our
1462 #ifdef GL_EXT_texture_lod_bias
1463 glTexEnvf( GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, -0.5 ) ;
1466 // Set position relative to glide slope if requested
1467 fgSetPosFromGlideSlope();
1469 // set current_options lon/lat if an airport id is specified
1470 // cout << "3. airport_id = " << fgGetString("/sim/startup/airport-id") << endl;
1471 if ( fgGetString("/sim/startup/airport-id").length() ) {
1472 // fgSetPosFromAirportID( fgGetString("/sim/startup/airport-id") );
1473 fgSetPosFromAirportIDandHdg( fgGetString("/sim/startup/airport-id"),
1474 fgGetDouble("/orientation/heading-deg") );
1477 SGTime *t = fgInitTime();
1478 globals->set_time_params( t );
1480 // Do some quick general initializations
1481 if( !fgInitGeneral()) {
1482 SG_LOG( SG_GENERAL, SG_ALERT,
1483 "General initializations failed ..." );
1487 SGPath modelpath( globals->get_fg_root() );
1488 ssgModelPath( (char *)modelpath.c_str() );
1491 scene = new ssgRoot;
1492 scene->setName( "Scene" );
1494 lighting = new ssgRoot;
1495 lighting->setName( "Lighting" );
1497 // Initialize the sky
1498 SGPath ephem_data_path( globals->get_fg_root() );
1499 ephem_data_path.append( "Astro" );
1500 SGEphemeris *ephem = new SGEphemeris( ephem_data_path.c_str() );
1501 ephem->update( globals->get_time_params()->getMjd(),
1502 globals->get_time_params()->getLst(),
1504 globals->set_ephem( ephem );
1508 SGPath sky_tex_path( globals->get_fg_root() );
1509 sky_tex_path.append( "Textures" );
1510 sky_tex_path.append( "Sky" );
1511 thesky->texture_path( sky_tex_path.str() );
1513 thesky->build( 550.0, 550.0,
1514 globals->get_ephem()->getNumPlanets(),
1515 globals->get_ephem()->getPlanets(), 60000.0,
1516 globals->get_ephem()->getNumStars(),
1517 globals->get_ephem()->getStars(), 60000.0 );
1519 if ( fgGetBool("/environment/clouds/status") ) {
1520 // thesky->add_cloud_layer( 2000.0, 200.0, 50.0, 40000.0,
1521 // SG_CLOUD_OVERCAST );
1522 thesky->add_cloud_layer( fgGetDouble("/environment/clouds/altitude-ft") *
1524 200.0, 50.0, 40000.0,
1525 SG_CLOUD_MOSTLY_CLOUDY );
1526 // thesky->add_cloud_layer( 3000.0, 200.0, 50.0, 40000.0,
1527 // SG_CLOUD_MOSTLY_SUNNY );
1528 thesky->add_cloud_layer( 6000.0, 20.0, 10.0, 40000.0,
1532 // Initialize MagVar model
1533 SGMagVar *magvar = new SGMagVar();
1534 globals->set_mag( magvar );
1537 terrain_branch = new ssgBranch;
1538 terrain_branch->setName( "Terrain" );
1539 scene->addKid( terrain_branch );
1542 gnd_lights_branch = new ssgBranch;
1543 gnd_lights_branch->setName( "Ground Lighting" );
1544 lighting->addKid( gnd_lights_branch );
1546 rwy_lights_branch = new ssgBranch;
1547 rwy_lights_branch->setName( "Runway Lighting" );
1548 lighting->addKid( rwy_lights_branch );
1550 // airport = new ssgBranch;
1551 // airport->setName( "Airport Lighting" );
1552 // lighting->addKid( airport );
1558 // temporary visible aircraft "own ship"
1559 current_model.init();
1561 #ifdef FG_NETWORK_OLK
1562 // Do the network intialization
1563 if ( fgGetBool("/sim/networking/network-olk") ) {
1564 printf("Multipilot mode %s\n", fg_net_init( scene ) );
1568 // build our custom render states
1569 fgBuildRenderStates();
1571 // pass control off to the master GLUT event handler
1574 // we never actually get here ... but to avoid compiler warnings,
1580 // $$$ end - added VS Renganathan, 15 Oct 2K
1581 // - added Venky , 12 Nov 2K
1583 #if defined(__linux__) && defined(__i386__)
1585 static void handleFPE (int);
1590 fpu_control_t fpe_flags = 0;
1591 _FPU_GETCW(fpe_flags);
1592 // fpe_flags &= ~_FPU_MASK_IM; // invalid operation
1593 // fpe_flags &= ~_FPU_MASK_DM; // denormalized operand
1594 // fpe_flags &= ~_FPU_MASK_ZM; // zero-divide
1595 // fpe_flags &= ~_FPU_MASK_OM; // overflow
1596 // fpe_flags &= ~_FPU_MASK_UM; // underflow
1597 // fpe_flags &= ~_FPU_MASK_PM; // precision (inexact result)
1598 _FPU_SETCW(fpe_flags);
1599 signal(SIGFPE, handleFPE);
1606 SG_LOG(SG_GENERAL, SG_ALERT, "Floating point interrupt (SIGFPE)");
1610 // Main entry point; catch any exceptions that have made it this far.
1611 int main ( int argc, char **argv ) {
1613 // Enable floating-point exceptions for Linux/x86
1614 #if defined(__linux__) && defined(__i386__)
1618 // Enable floating-point exceptions for Windows
1619 #if defined( _MSC_VER ) && defined( DEBUG )
1620 // Christian, we should document what this does
1621 _control87( _EM_INEXACT, _MCW_EM );
1624 #if defined( HAVE_BC5PLUS )
1625 _control87(MCW_EM, MCW_EM); /* defined in float.h */
1628 // FIXME: add other, more specific
1631 mainLoop(argc, argv);
1632 } catch (sg_throwable &t) {
1633 SG_LOG(SG_GENERAL, SG_ALERT,
1634 "Fatal error: " << t.getFormattedMessage()
1635 << "\n (received from " << t.getOrigin() << ')');
1643 void fgLoadDCS(void) {
1645 ssgEntity *ship_obj = NULL;
1647 char obj_filename[25];
1649 for ( int k = 0; k < 32; k++ ) {
1653 SGPath tile_path( globals->get_fg_root());
1654 tile_path.append( "Scenery" );
1655 tile_path.append( "Objects.txt" );
1656 sg_gzifstream in( tile_path.str() );
1657 if ( ! in.is_open() ) {
1658 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << tile_path.str() );
1661 SGPath modelpath( globals->get_fg_root() );
1662 modelpath.append( "Models" );
1663 modelpath.append( "Geometry" );
1665 SGPath texturepath( globals->get_fg_root() );
1666 texturepath.append( "Models" );
1667 texturepath.append( "Textures" );
1669 ssgModelPath( (char *)modelpath.c_str() );
1670 ssgTexturePath( (char *)texturepath.c_str() );
1672 ship_sel = new ssgSelector;
1675 while ( ! in.eof() ) {
1677 if ( in.get( c ) && c == '#' ) {
1681 in >> obj_filename >> obj_lat[objc] >> obj_lon[objc] >> obj_alt[objc];
1682 /* cout << endl << obj_filename << " " << obj_lat[objc] << " " << obj_lon[objc] << " " << obj_alt[objc] << endl;
1683 int chj=getchar();*/
1685 obj_lon[objc] *=SGD_DEGREES_TO_RADIANS;
1686 obj_lat[objc] *=SGD_DEGREES_TO_RADIANS;
1688 ship_pos[objc] = new ssgTransform;
1690 // type "repeat" in objects.txt to load one more
1691 // instance of the last object.
1693 if ( strcmp(obj_filename,"repeat") != 0) {
1694 ship_obj = ssgLoad( obj_filename );
1697 if ( ship_obj != NULL ) {
1698 ship_obj->setName(obj_filename);
1700 ship_obj->clrTraversalMaskBits( SSGTRAV_HOT );
1702 ship_obj->setTraversalMaskBits( SSGTRAV_HOT );
1703 ship_pos[objc]->addKid( ship_obj ); // add object to transform node
1704 ship_sel->addKid( ship_pos[objc] ); // add transform node to selector
1705 SG_LOG( SG_TERRAIN, SG_ALERT, "Loaded file: "
1708 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: "
1712 // temporary hack for deck lights - ultimately should move to PLib (when??)
1713 //const char *extn = file_extension ( obj_filename ) ;
1715 ssgVertexArray *lights = new ssgVertexArray( 100 );
1716 ssgVertexArray *lightpoints = new ssgVertexArray( 100 );
1717 ssgVertexArray *lightnormals = new ssgVertexArray( 100 );
1718 ssgVertexArray *lightdir = new ssgVertexArray( 100 );
1719 int ltype[500], light_type;
1720 static int ltcount = 0;
1722 sgVec3 rway_dir,rway_normal,lightpt;
1724 modelpath.append(obj_filename);
1725 sg_gzifstream in1( modelpath.str() );
1726 if ( ! in1.is_open() ) {
1727 SG_LOG( SG_TERRAIN, SG_ALERT, "Cannot open file: " << modelpath.str() );
1729 while ( ! in1.eof() ) {
1731 if ( in1.get( c ) && c == '#' ) {
1736 //cout << token << endl;
1737 if ( token == "runway" ) {
1739 sgSetVec3 (rway_dir, node[0], node[1], node[2] );
1740 } else if ( token == "edgelight" ) {
1742 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1744 } else if ( token == "taxi" ) {
1746 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1748 } else if ( token == "vasi" ) {
1750 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1752 } else if ( token == "threshold" ) {
1754 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1756 } else if ( token == "rabbit" ) {
1758 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1760 } else if ( token == "ols" ) {
1762 sgSetVec3 (rway_ols, node[0], node[1], node[2] );
1764 } else if ( token == "red" ) {
1766 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1768 } else if ( token == "green" ) {
1770 sgSetVec3 (rway_normal, node[0], node[1], node[2] );
1772 } else if ( token == "lp" ) {
1774 sgSetVec3 (lightpt, node[0], node[1], node[2] );
1775 lightpoints->add( lightpt );
1776 lightnormals->add( rway_normal );
1777 lightdir->add( rway_dir );
1778 ltype[ltcount]= light_type;
1781 if (in1.eof()) break;
1785 if ( lightpoints->getNum() ) {
1786 ssgBranch *lightpoints_branch;
1787 long int dummy = -999;
1788 dummy_tile = new FGTileEntry((SGBucket)dummy);
1789 dummy_tile->lightmaps_sequence = new ssgSelector;
1790 dummy_tile->ols_transform = new ssgTransform;
1792 // call function to generate the runway lights
1793 lightpoints_branch =
1794 dummy_tile->gen_runway_lights( lightpoints, lightnormals,
1796 lightpoints_brightness->addKid(lightpoints_branch);
1797 lightpoints_transform->addKid(lightpoints_brightness);
1798 //dummy_tile->lightmaps_sequence->setTraversalMaskBits( SSGTRAV_HOT );
1799 lightpoints_transform->addKid( dummy_tile->lightmaps_sequence );
1800 lightpoints_transform->ref();
1801 gnd_lights_branch->addKid( lightpoints_transform );
1805 // end hack for deck lights
1809 if (in.eof()) break;
1813 SG_LOG ( SG_TERRAIN, SG_ALERT, "Finished object processing." );
1815 terrain_branch->addKid( ship_sel ); //add selector node to root node
1822 void fgUpdateDCS (void) {
1824 // double eye_lat,eye_lon,eye_alt;
1825 // static double obj_head;
1826 double sl_radius,obj_latgc;
1827 // float nresultmat[4][4];
1828 // sgMat4 Trans,rothead,rotlon,rot180,rotlat,resultmat1,resultmat2,resultmat3;
1831 // Instantaneous Geodetic Lat/Lon/Alt of moving object
1832 FGADA *fdm = (FGADA *)current_aircraft.fdm_state;
1834 // Deck should be the first object in objects.txt in case of fdm=ada
1836 if (fgGetString("/sim/flight-model") == "ada") {
1837 if ((fdm->get_iaux(1))==1)
1839 obj_lat[1] = fdm->get_daux(1)*SGD_DEGREES_TO_RADIANS;
1840 obj_lon[1] = fdm->get_daux(2)*SGD_DEGREES_TO_RADIANS;
1841 obj_alt[1] = fdm->get_daux(3);
1842 obj_pitch[1] = fdm->get_faux(1);
1843 obj_roll[1] = fdm->get_faux(2);
1847 for ( int m = 0; m < objc; m++ ) {
1848 //cout << endl << obj_lat[m]*SGD_RADIANS_TO_DEGREES << " " << obj_lon[m]*SGD_RADIANS_TO_DEGREES << " " << obj_alt[m] << " " << objc << endl;
1851 //Geodetic to Geocentric angles for rotation
1852 sgGeodToGeoc(obj_lat[m],obj_alt[m],&sl_radius,&obj_latgc);
1854 //moving object gbs-posn in cartesian coords
1855 Point3D obj_posn = Point3D( obj_lon[m],obj_lat[m],obj_alt[m]);
1856 Point3D obj_pos = sgGeodToCart( obj_posn );
1858 // Translate moving object w.r.t eye
1859 Point3D Objtrans = obj_pos-scenery.get_center();
1864 // rotate dynamic objects for lat,lon & alt and other motion about its axes
1867 sgMakeTransMat4( sgTRANS, bz[0],bz[1],bz[2]);
1869 sgVec3 ship_fwd,ship_rt,ship_up;
1870 sgSetVec3( ship_fwd, 1.0, 0.0, 0.0);//east,roll
1871 sgSetVec3( ship_rt, 0.0, 1.0, 0.0);//up,pitch
1872 sgSetVec3( ship_up, 0.0, 0.0, 1.0); //north,yaw
1874 sgMat4 sgROT_lon, sgROT_lat, sgROT_hdg, sgROT_pitch, sgROT_roll;
1875 sgMakeRotMat4( sgROT_lon, obj_lon[m]*SGD_RADIANS_TO_DEGREES, ship_up );
1876 sgMakeRotMat4( sgROT_lat, 90-obj_latgc*SGD_RADIANS_TO_DEGREES, ship_rt );
1877 sgMakeRotMat4( sgROT_hdg, 180.0, ship_up );
1878 sgMakeRotMat4( sgROT_pitch, obj_pitch[m], ship_rt );
1879 sgMakeRotMat4( sgROT_roll, obj_roll[m], ship_fwd );
1882 sgCopyMat4( sgTUX, sgROT_hdg );
1883 sgPostMultMat4( sgTUX, sgROT_pitch );
1884 sgPostMultMat4( sgTUX, sgROT_roll );
1885 sgPostMultMat4( sgTUX, sgROT_lat );
1886 sgPostMultMat4( sgTUX, sgROT_lon );
1887 sgPostMultMat4( sgTUX, sgTRANS );
1890 sgSetCoord(&shippos, sgTUX );
1891 ship_pos[m]->setTransform( &shippos );
1892 // temporary hack for deck lights - ultimately should move to PLib (when ??)
1894 if (lightpoints_transform) {
1895 lightpoints_transform->setTransform( &shippos );
1896 float sun_angle = cur_light_params.sun_angle * SGD_RADIANS_TO_DEGREES;
1897 if ( sun_angle > 89 ) {
1898 lightpoints_brightness->select(0x01);
1900 lightpoints_brightness->select(0x00);
1909 sgXformPnt3( rp, rway_ols, sgTUX );
1910 vp = globals->get_current_view()->get_view_pos();
1911 to[0] = rp[0]-vp[0];
1912 to[1] = rp[1]-vp[1];
1913 to[2] = rp[2]-vp[2];
1914 float dist = sgLengthVec3( to );
1915 alt = (current_aircraft.fdm_state->get_Altitude() * SG_FEET_TO_METER)-rway_ols[2];
1917 elev = asin(alt/dist)*SGD_RADIANS_TO_DEGREES;
1919 ref_elev = elev - 3.75; // +ve above, -ve below
1923 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1924 // if (ref_elev > 0.51) sel = 0x21;
1925 // if ((ref_elev <= 0.51) & (ref_elev > 0.17)) sel = 0x22;
1926 // if ((ref_elev <= 0.17) & (ref_elev >= -0.17)) sel = 0x24;
1927 // if ((ref_elev < -0.17) & (ref_elev >= -0.51)) sel = 0x28;
1928 // if (ref_elev < -0.51) sel = 0x30;
1929 // DO NOT DELETE THIS CODE - This is to compare a discrete FLOLS (without LOD) with analog FLOLS
1930 dummy_tile->lightmaps_sequence->select(sel);
1933 sgCopyVec3 (up, ship_up);
1935 sgScaleVec3 (up, 4.0*ref_elev*dist/750.0);
1937 sgScaleVec3 (up, 4.0*ref_elev);
1938 dummy_tile->ols_transform->setTransform(up);
1939 //cout << "ref_elev " << ref_elev << endl;
1941 // end hack for deck lights
1944 if ( ship_sel != NULL ) {
1945 ship_sel->select(0xFFFFFFFE); // first object is ownship, added to acmodel
1949 // $$$ end - added VS Renganathan, 15 Oct 2K
1950 // added Venky , 12 Nov 2K